Introduction and usage of Python bottle ・ Try to set up a simple web server with login function

Introduction

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

Overview

  1. Introducing Bottle 1.1. Download bottle.py 1.2. Operation check
  2. Routing 2.1. Static routing 2.2. Dynamic routing
  3. About HTTP 3.1. What is HTTP? 3.2. HTTP request method
  4. Method support in Bottle 4.1. GET method 4.2. Methods other than GET
  5. Request object
  6. Create a login form

1. Introducing Bottle

1.1. Download bottle.py

First, create a working directory.

$ mkdir bottle_test
$ cd bottle_test

Execute the following command to download bottle.py.

$ wget http://bottlepy.org/bottle.py

1.2. Operation check

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```)

kakunin.PNG

Now you can see how the bottle works.

2. Routing

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')

2.1. Static routing

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!".

$ python3 index.py

The one I just tried is called static routing.

2.2. Dynamic 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

3. About HTTP

The content from here required knowledge of HTTP, so I studied a little. Put it together lightly.

3.1. What is HTTP?

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.

3.2. HTTP request method

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.

4. Method support in Bottle

4.1. GET method

@ 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>!')
    

4.2. Methods other than GET

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')

5. Request object

You can use bottle.request to access the request you are currently processing.

from bottle import request

For details, Master Bottle Request / Response object

6. Create a login form

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.

login.PNG

Enter the appropriate Username and the password you set (abc) and press Login, thenHello! <Entered Username> Should be displayed.

The site that I used as a reference

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)

Recommended Posts

Introduction and usage of Python bottle ・ Try to set up a simple web server with login function
[Vagrant] Set up a simple API server with python
Try to bring up a subwindow with PyQt5 and Python
How to start a simple WEB server that can execute cgi of php and python
Send mail with mailx to a dummy SMTP server set up with python.
Try to solve a set problem of high school math with Python
Set up a simple HTTPS server in Python 3
Set up a simple HTTPS server with asyncio
Start a simple Python web server with Docker
Launch a web server with Python and Flask
Set up a simple SMTP server in Python
Put Docker in Windows Home and run a simple web server with Python
WEB scraping with python and try to make a word cloud from reviews
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
screen and split screen with python and ssh login to remote server
Set up a web server with CentOS7 + Anaconda + Django + Apache
[Introduction to AWS] A memorandum of building a web server on AWS
How to set up a simple SMTP server that can be tested locally in Python
[Introduction to Python] How to split a character string with the split function
[Python] A simple function to find the center coordinates of a circle
Set up a Samba server with Docker
[Python] A quick web application with Bottle!
Set up a Lambda function and let it work with S3 events!
[Introduction to Python] How to sort the contents of a list efficiently with list sort
Try to set up a Vim test environment quite seriously (for Python)
Hit a method of a class instance with the Python Bottle Web API
Set up a local web server in 30 seconds using python 3's http.server
[Introduction to Python] How to write a character string with the format function
Set up a dummy SMTP server in Python and check the operation of sending from Action Mailer
I want to pass an argument to a python function and execute it from PHP on a web server
Set up a local server with Go-File upload-
I tried to make a simple mail sending application with tkinter of Python
Introduction to Tornado (1): Python web framework started with Tornado
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server --2 PHP introduction
Try to draw a life curve with python
[ES Lab] I tried to develop a WEB application with Python and Flask ②
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server ―― 1. Apache introduction
Set up a test SMTP server in Python.
Set up a local server with Go-File download-
[CleanArchitecture with Python] Apply CleanArchitecture step by step to a simple API and try to understand "what kind of change is strong" in the code base.
How to set up a local development server
[Introduction to Python] Basic usage of lambda expressions
[Introduction to Python] How to get the index of data with a for statement
An introduction to cross-platform GUI software made with Python / Tkinter! (And many Try and Error)! (In the middle of writing)
Get a large amount of Starbucks Twitter data with python and try data analysis Part 1
[Python3] Take a screenshot of a web page on the server and crop it further
Introduction to Simple Regression Analysis with Python (Comparison of 6 Libraries of Numerical Calculation/Computer Algebra System)
Perform a Twitter search from Python and try to generate sentences with Markov chains.
[Mac] I want to make a simple HTTP server that runs CGI with Python
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
Try making a simple website with responder and sqlite3
A memo connected to HiveServer2 of EMR with python
How to set up a Python environment using pyenv
Set up a simple local server on your Mac
Try to make a command standby tool with python
[Introduction to Python] How to iterate with the range function?
(Python) Try to develop a web application using Django
Try to operate DB with Python and visualize with d3
[Chapter 5] Introduction to Python with 100 knocks of language processing
Let's make a simple game with Python 3 and iPhone