When a Python beginner tried using Bottle, it worked unexpectedly easily.

Introduction

This is a memo for myself, the details are as follows.

Execution environment

Thing you want to do

What i did

Let's move it for the time being.

Don't think it's difficult, first try until Hello World is displayed in the browser.

#pip install to import
$ pip install bottle
# -*- coding:utf-8 -*-

from bottle import route, run


@route('/hello')
def hello():
    return "Hello World!"


run(host='localhost', port=8080, debug=True)

Run it in PyCharm and open it in your browser. http://localhost:8080/hello

image

Now you can see Hello World in your browser !! Amazing Bottle

Try dynamic routing

# -*- coding:utf-8 -*-

from bottle import route, run


@route('/hello/')
@route('/hello/<user>')
def hello(user="taro"):
    return "Hello {user}".format(user=user)


@route('/date/<month:re:[a-z]+>/<day:int>/<path:path>')
def date(month, day, path):
    return "{month}/{day} {path}".format(month=month, day=day, path=path)


run(host='localhost', port=8080, debug=True)

Use the received parameters

By defining the default in the argument of the method to be executed, it can be displayed even when user is not passed. http://localhost:8080/hello/ image

http://localhost:8080/hello/masaibar image

Constraint parameters

Simple value constraints can be given.

http://localhost:8080/date/april/29//dev/null image

Try GET, POST

It seems that there are two ways to write annotations such as GET and POST. @get ('/ hoge') and @route ('/ hoge', method ='GET') have the same behavior.

The passed value is received by referring to the following variables.

In addition, you can receive various data such as headers and request body. Reference

# -*- coding:utf-8 -*-

from bottle import route, run
from bottle import get, post, request


@route('/login', method='GET')  # or @get('/login')
def login():
    username = request.query.get('user')
    password = request.query.get('pass')

    #Username when nothing is passed in GET,Don't put anything in password
    username = "" if username is None else username
    password = "" if password is None else password

    return '''
    <form action="/login" method="post">
            Username: <input name="username" type="text" value="{username}"/>
            Password: <input name="password" type="password" value="{password}"/>
            <input value="Login" type="submit" />
        </form>
    '''.format(username=username, password=password)


@route('/login', method='POST')  # or @post('/post')
def do_login():
    username = request.forms.get('username')
    password = request.forms.get('password')

    return "{username} {password}".format(username=username, password=password)


run(host='localhost', port=8080, debug=True)

GET http://localhost:8080/login image

http://localhost:8080/login?user=hoge&pass=fuga image

POST image

Try to display the error page

# -*- coding:utf-8 -*-

from bottle import route, run
from bottle import error


@route('/hello')
def hello():
    return "Hello World!"


@error(404)
def error404(error):
    return "Nothing here sorry {error}".format(error=error)


run(host='localhost', port=8080, debug=True)

I deliberately step on a URL that doesn't exist. http://localhost:8080/hellow image

in conclusion

To be honest, I was surprised that it moved easier than I expected. This time, I focused on moving it without thinking about templates, but when I looked it up, I felt that there were quite a few people using only the template engine. (Is Jinja2 popular?)

reference

Tutorial — Bottle 0.13-dev documentation : http://bottlepy.org/docs/dev/tutorial.html Easy introduction of 6 kinds of Python web frameworks --Mojilog: http://mojix.org/2013/04/13/python-six-wafs Master the Request / Response object for Bottle-Qiita: http://qiita.com/tomotaka_ito/items/62fc4d58d1be7867a158 Comparison of None in Python is using is not the == - is Hello Hello monmon! : http://monmon.hateblo.jp/entry/20110214/1297710749

Recommended Posts

When a Python beginner tried using Bottle, it worked unexpectedly easily.
When I tried to create a project using Python on Docker with PyCharm, it didn't work, but it worked with Docker Compose.
I tried to make a todo application using bottle with python
I tried to create a sample to access Salesforce using Python and Bottle
I tried reading a CSV file using Python
A python beginner tried to intern at an IT company [Day 2 chatbot survey]
A python beginner tried to intern at an IT company [Day 1 development process]
When I tried to create a virtual environment with Python, it didn't work
A story that was convenient when I tried using the python ip address module
I made a login / logout process using Python Bottle.
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 7-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 1-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 2-
A python beginner tried to intern at an IT company [Day 3: Going to the clouds ...]
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 0-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 5-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 6-
[Python] I tried running a local server using flask
I tried drawing a pseudo fractal figure using Python
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 3-
I tried using Python (3) instead of a scientific calculator
When I tried the AtCoder Beginner Contest, it was a terrible result, so I look back
A memo when creating a directed graph using Graphviz in Python
Scripts that can be used when using bottle in Python
[Python] I tried using OpenPose
When I tried to scrape using requests in python, I was addicted to SSLError, so a workaround memo
Rubyist tried to make a simple API with Python + bottle + MySQL
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
[Python] Appears when using iterdir () etc. [Errno 20] Not a directory:'*** / .DS_Store'
I tried to make a regular expression of "date" using Python
A note on using tab completion when running Python interactively on Windows
Error log output method when using Bottle framework on GAE / Python
Try it when Visual Studio Code can't load a Python module
A memorandum when using beautiful soup
Precautions when using pit in Python
I made a Line-bot using Python!
Create a python GUI using tkinter
Drawing a silverstone curve using python
I tried using Thonny (Python / IDE)
Python beginner tried 100 language processing knock 2015 (05 ~ 09)
Precautions when creating a Python generator
Precautions when using phantomjs from python
When using MeCab with virtualenv python
Precautions when using six with Python 2.5
[VS Code] ~ Tips when using python ~
When using regular expressions in Python
When writing a program in Python
[Python] I tried using YOLO v3
Easily create homemade RPA using Python
Python beginner tried 100 language processing knock 2015 (00 ~ 04)
I made a Discord bot in Python that translates when it reacts
I tried using eval (a, b) for Fibonacci, but it wasn't fast
A beginner of machine learning tried to predict Arima Kinen with python
A useful note when using Python for the first time in a while
Start a web server using Bottle and Flask (I also tried using Apache)
When I try to go back using chainer, it fits a little