I wanted to make IoT with Raspberry pi, but I was in trouble because I didn't have much knowledge about web and software. Frameworks such as Django, Zope, and Pyramid are used to implement web applications in Python, but while they have many features, they are too high-level for beginners like myself.
So I decided to study a lightweight Python framework called Bottle. The framework fits in one file, which makes it perfect for beginners to study.
__ ◎ Purpose of this time __ First, learn the basic usage of Bottle by using Bottle in a PC environment. A memorandum up to the point of setting up a server with a login form
__ ◎ Environment __ WSL Ubuntu 18.04.3 LTS
bottle.py
1.2. Operation checkbottle.py
First, create a working directory.
$ mkdir bottle_test
$ cd bottle_test
Execute the following command to download bottle.py
.
pip install bottle
or wget
.$ wget http://bottlepy.org/bottle.py
Check the operation with Hello world.
Create the following ʻindex.py in the same hierarchy as
bottle.py` (bottle_test in the above).
bottle_test/index.py
# -*- coding:utf-8 -*-
from bottle import route, run
@route('/hello')
def hello():
return "Hello world!"
run(host='localhost', port=8080, debug=True)
Doing this will bring up the web server.
$ python3 index.py
If you access http: // localhost: 8080 / hello with your browser, you should see Hello world!
. (End with `` `ctrl + c```)
Now you can see how the bottle works.
Bottle allows you to associate a python function with a URL requested by a client (browser). This is called routing.
For example, using code like the following, when the URL http: // xxxxx / hoge
is requested, the function hogehoge () will be executed and index.tpl (contents HTML) inside the view folder. Is sent to the client (browser).
routing
@route('/hoge')
def hogehoge():
return template('view/index')
Actually, try the combination of the routing function and html.
Rewrite and save bottle_test / index.py
as follows, and create bottle_test / view / index.tpl
.
bottle_test/index.py
# -*- coding:utf-8 -*-
from bottle import route, run, template
@route('/hello')
def hello():
return template('view/index')
run(host='localhost', port=8080, debug=True)
bottle_test/view/index.tpl
<html>
<head>
</head>
<body>
<p>Hello!</p>
</body>
</html>
In this state, if you run ʻindex.py` and access http: // localhost: 8080 / hello with the browser of the running PC, you should see "Hello!".
run
function is a command to start the WEB server of the Bottle framework. If you change it to host = '0.0.0.0'
and execute it, you can access it from terminals in the same network. In that case, the URL to access is http: // PC IP address: 8080 / hello
. If you can't connect successfully, it's probably because your firewall doesn't allow port 8080.
To allow port number communication in firewall settings$ python3 index.py
The one I just tried is called static routing
.
HTTP allows you to add a parameter to the end of the URL requested by the browser, but Bottle allows you to take it as a function argument. (See the next chapter for HTTP)
Rewrite bottle_test / index.py
and bottle_test / view / index.tpl
as follows and save.
bottle_test/index.py
# -*- coding:utf-8 -*-
from bottle import route, run, template
@route('/hello')
@route('/hello/<name>')
def hello(name = 'people who do not know'):
return template('view/index', nm = name)
run(host='localhost', port=8080, debug=True)
bottle_test/view/index.tpl
<html>
<head>
</head>
<body>
<p>Hello!{{nm}}</p>
</body>
</html>
As shown in the table below, the display result changes depending on the parameter added to the end of the URL. The parameter at the end of the URL is taken as a function argument, and the browser displays the tpl file with {{nm}} replaced by the argument. By setting the initial value to the variable of the function, the operation when there is no parameter at the end can also be specified.
URL to request | Display result |
---|---|
http://localhost:8080/hello | Hello!people who do not know |
http://localhost:8080/hello/tanaka | Hello!tanaka |
http://localhost:8080/hello/12345 | Hello!12345 |
The content from here required knowledge of HTTP, so I studied a little. Put it together lightly.
Hypertext Transfer Protocol (HTTP for short) is a communication protocol primarily used by web browsers to communicate with web servers and is a member of the Internet Protocol Suite. It is used to send and receive content such as Web pages written in text such as HTML. Wikipedia
HTTP performs request / response communication by the server / client. A format in which when a client (browser) sends a data request, the Web server that receives the request returns the data as a response.
There are several types of request methods that the client side (browser) sends to the server side, but here are five commonly used methods. For more information HTTP for Web beginners
① GET
Request method to get URI data, used when getting data such as HTML and images.
Simply put, it's a request to "send this page."
You can also send parameters to the server at the time of request by adding a? + Character string after the URI specified by the GET method. (Example: http: //localhost:8080/index.html? hoge = hoge
)
② POST A method that sends data from the client side to the server side. The GET method sends the parameter to the server by writing the parameter at the end of the URI, but this sends the parameter from the HTML form. There is no limit to the number of bytes of data that can be sent here. It is also possible to encrypt and send highly important data.
③ HEAD A method that gets only the header data of the URI. The GET method also acquires the body of the data at the same time, but the HEAD method can acquire only the header part of the data (data update date and time and data size).
④ PUT A method that creates and replaces the contents of a URI. If the specified resource does not exist, a new one is created, and if the specified resource exists, it is updated. The URI of the resource created by PUT is determined by the client side (browser).
⑤ DELETE A method that removes the contents of the URI.
@ route
If you use it without passing options to the decorator, it will be treated as a process for access of the GET method. (All the source code described in 2. Routing
describes the process for accessing the GET method.)
GET method
#With the GET method/hogehoge when accessed hoge()To run
@route('/hoge') #Or@get('/hoge')
def hogehoge():
return template('<b>Hello World</b>!')
When supporting methods other than GET, there are the following two description methods. The following shows how to write using the POST method as an example.
① Pass the option to the @ route
decorator
python
#Method 1: @pass options to the route decorator
#With the POST method/hogehoge when accessed hoge()To run
from bottle import route, run, template
@route('/hoge', method = 'POST')
def hogehoge():
return template('<b>Hello World</b>!')
(2) Use the decorator corresponding to the method
python
#Method 2:Use the decorator for the method
#With the POST method/hogehoge when accessed hoge()To run
from bottle import post, run, template
@post('/hoge')
def hogehoge():
return template('<b>Hello World</b>!')
__ List __
Method | Method ① | Method ② |
---|---|---|
GET | @route('/hoge') |
@get('/hoge') |
POST | @route('/hoge', method = 'POST') |
@post('/hoge') |
PUT | @route('/hoge', method='PUT') |
@put('/hoge') |
DELETE | @route('/hoge', method='DELETE') |
@delete('/hoga') |
You can use bottle.request
to access the request you are currently processing.
from bottle import request
request.query
: Parameters sent from the client in the GET method (query parameters)request.forms
: Form parameters submitted by the client with the POST / PUT methodrequest.url
: URL accessedrequest.files.get ('name')
: AttachmentsFor details, Master Bottle Request / Response object
Let's make a login form using the knowledge so far.
Rewrite bottle_test / index.py
and bottle_test / view / index.tpl
as follows and save.
bottle_test/index.py
# -*- coding:utf-8 -*-
from bottle import get, post, request, run, template
def check(password): #Login judgment
if password == "abc":
return True
else:
return False
@get('/login') #With the GET method/What happens when you access login
def login_form():
return '''
<form action = "/login" method = "post">
Username: <input name = "username" type = "text" />
Password: <input name = "password" type = "password" />
<input value = "Login" type = "submit"/>
</form>
'''
@post('/login')
def login():
#Access POSTed information
name = request.forms.get('username')
pasw = request.forms.get('password')
#Judgment
if check(pasw):
return template('view/index', nm = name)
else:
return "<p>Login failed.</p>"
run(host='localhost', port=8080, debug=True)
bottle_test/view/index.tpl
<html>
<head>
</head>
<body>
<p>Hello!{{nm}}</p>
</body>
</html>
Run ʻindex.py`.
$ python3 index.py
If you access http: // localhost: 8080 / login from your browser in this state, the login screen will be displayed.
Enter the appropriate Username and the password you set (abc) and press Login
, thenHello! <Entered Username>
Should be displayed.
Installation / Operation check / How to use route: Python's lightweight web framework "Bottle" Basic usage of Bottle: How to use the lightweight web server Bottle of Python Bottle Details: Python's smallest web framework bottle.py About HTTP: HTTP for Web Beginners Image file link generation in Bottle: Static file link generation in Python's Bottle framework Bottle Request / Response: Master Bottle Request / Response object (https://qiita.com/tomotaka_ito/items/62fc4d58d1be7867a158)