当前位置:网站首页>[flask] flask starts and implements a minimal application based on flask

[flask] flask starts and implements a minimal application based on flask

2022-07-01 13:46:00 Coriander Chrysanthemum

background

Although he is an algorithm engineer , But the actual situation is not only to understand the algorithm , And understand engineering . After the algorithm is implemented , Algorithm effect demonstration , Algorithm implementation requires some engineering content . A simple way of algorithm engineering is to package the landing algorithm into a service , For others to call .
So here comes the question , We need to know something about service . There are also many ways to provide services , For example, based on GRPC Service for , be based on Restful Of api Interface services, etc . Of course , I personally feel that the use is based on restful Of api Interface mode is used more . So I understand Python web The relevant framework of , Such as Django,Flask, FastAPI etc. , Consider using Flask To do this work .
Then the best way to learn a technology is to read official documents , But many of the official documents are interfaces , Use of methods , boring 、 tasteless . Here I usually see if there is Quickstart as well as Tutorial, Because on the one hand, it is the generalization of mainstream methods . On the one hand, it is a small demo The implementation of the , Reading it can roughly understand what a technology contains , On the other hand, we can know that if we use this technology to complete some tasks . As for more details , You can further mine knowledge by consulting documents .
see Flask file , There are exactly these two parts . So I am happy to learn and record relevant content . Of course, I won't swallow a fat man in one bite , Read quickly , Learn a little and record a little over time , After all, my main work is the expansion and practice of algorithms .
 Please add a picture description
Of course , The following records are not only the translation of official documents, but also their own summaries and notes , Make a fool of yourself .

Environmental preparation

flask How to install can refer to Official website , This study record mainly uses 2.1.x edition .

In order to better approach the development mode in actual work , I installed one on the virtual machine centos7 System , And configured anaconda development environment . according to flask 2.1.x Version for Python The version is 3.7+, I also created a python3.7 Empty development environment , So that you can export requirements.txt file . We can use venv Module to create a virtual environment . But I'm still used to it conda To create a virtual environment , as follows :

conda create -n web_flask python=3.7

Then install in this environment flask:pip install flask==2.1

Here's how to use pycharm Connect to this virtual development environment by remote connection . You might think , Will developing on your own virtual machine have an impact on performance ? I don't think there's any need to worry about this , This kind of development will not eat too much computer performance .

A minimal application

One of the smallest Flask Applications can be as follows :

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

The corresponding functions of the above code are as follows :

  1. Imported Flask class , He is WSGI An example of an application . If you don't know this , You can refer to Baidu entries :wsgi
  2. The next thing is right Flask instantiate . The first parameter is the name of the application module or package .__name__ stay python The role of : The first case refers to the currently running module , Then the current module __name__ The value is __main__; The second case refers to that the module uses import Imported modules , Then the imported module __name__ The value of the variable is the file name of the module . This is a required operation , In order to Flask Know where to find resources , For example, templates and static files .
  3. When we use route This decorator is , Just tell Flask Go to this method to deal with what URL link .
  4. This function returns the message we want to display in the user browser . The default content type is HTML, So... In the string HTML Will be rendered by the browser .

Save the above contents to hello.py In this file or use other file names . But you need to make sure it's not flask.py The name , Otherwise, it will be with Flask Conflict .

We use flask This command or python -m flask Run this application . We are linux System hello.py Start it under the corresponding file path , Of course, before that, you need to export FLASK_APP Environment variables to tell the terminal the application to use :

$ export FLASK_APP=hello
$ flask run

So there was :
 Insert picture description here
Now it is running , But only the server machine can access .

Application discovery behavior : Actually flask There are shortcuts for application startup , When the service program is app.py perhaps wsgi.py when , You don't need to set up FLASK_APP Environment variable .

When the program runs , Essentially, it starts a very simple built-in server , Its coping test is no problem , But it is not suitable for use in production . When other programs in the system occupy flask Default port for 5000 when , If enabled, a OSError:[Errno98] or OSError:[WinError 10013] Error of , At this time, you need to change the port this program listens to . One way to solve this problem is to add --port Other port numbers .

The current program can only be accessed by the current server itself , In order to make the program a Extenally Visible Server, One way to do this is to add --host=0.0.0.0, Such as :flask run --host=0.0.0.0. This tells the operating system to monitor all public networks IP 了 .

According to the above two questions , The summary opening procedure is as follows :flask run --port 5001 --host=0.0.0.0
 Insert picture description here
Visit the host computer as follows :
 Insert picture description here
Besides , If the host cannot access , It may be the problem of the system firewall of the virtual machine , It needs to be turned on 5000 Port monitoring . See 【Centos7】 A firewall (firewall) Summary of common commands .

Debug Pattern

flask run Command can also turn on debugging mode . By turning on debugging mode , If the code changes, the server can automatically load , And if an error occurs during the request , Then the interactive debugger is displayed in the browser .
 Insert picture description here
It should be noted that :degugger Although easy to use , But it's best not to use it in the production environment , It may leak the information of the system .
Starting mode :

export FLASK_ENV=development
flask run

HTML escape

flask Default returned response( Respond to ) yes HTML, Of course, you can also return json Format data, etc . When the returned content is HTML when , At this time, we need to consider a problem :injection attacks,flask Page side html The rendering engine is Jinja, Anti injection attack processing will be carried out automatically , Is to escape .

The following is the way to prevent injection attack by manual invocation :escape(). To describe simply , The following contents are omitted , But what we need to know is , The data we are dealing with are all untrustworthy data .

from markupsafe import escape

@app.route("/<name>")
def hello(name):
    return f"Hello, {
      escape(name)}!"

for example , User submitted name The data is <script>alert("bad")</script>, that escape It will be escaped , The page side will not execute this line of code .

Probably <name> You don't understand this way of using , It's from URL It is convenient for the server to deal with different problems according to different situations , Later on .

route Routing

modern Web Applications use meaningful URL To help users . If the page uses meaningful URL, They can be remembered and used to access the page directly , Users are more likely to like the page and return .

Every URL All represent a certain meaning , According to these URL It is important to return to the page with the specified meaning . So in flask in , Will use route() This little thing binds a function and URL request . for example :

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'

In fact, with this , We can do more ! Can make part URL Dynamically and attach multiple rules to a function . Because we have seen that you can get URL Parameters in . It's a little bit Restful The meaning of interface .

variable rile

So how to do things dynamically ? We can do that by using <variable_name> Mark part to add variable part to URL in . Our handler accepts this <variable_name> , It can be used as the parameter of the function . besides , We can use converters to specify the type of parameters , for example <converter:variable_name>. Use cases are as follows :

from markupsafe import escape

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return f'User {
      escape(username)}'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f'Post {
      post_id}'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return f'Subpath {
      escape(subpath)}'

Function of converting parameter types , In the lower version of flask It's not supported . So what are the types of conversions ? as follows :

string( The default value is ) Accept any text without slashes
int Accept positive integers
float Accept positive floating point values
path Like strings , But also accept slashes
uuid Accept UUID character string

Distinctive URLS/ Redirection behavior

The following two rules are different when using slashes .

@app.route('/projects/')
def projects():
    return 'The project page'

@app.route('/about')
def about():
    return 'The about page'

among ,projects This URL There is a slash at the end of "/", It seems more like a folder in a file system . If you visit URL Without slashes (/projects),Flask Will redirect you to with slashes (/projects/) The specification of URL.

about Specification of endpoint URL No trailing slashes . It is similar to the pathname of a file . Use trailing slashes (/about/) visit URL Will produce 404“ Not found ” error . This helps to make these resources URL Keep it unique , This helps search engines avoid indexing the same page twice .

in other words , In the program URL Add a slash in , User accessed URL When there is no slash , The system will complete . And in the program URL No slashes , User accessed URL When there is a slash , So it's a mistake .

URL structure

To build a specific function URL, have access to url_for() This function . It accepts the name of the function as its first argument and any number of keyword arguments , Each keyword parameter corresponds to URL Variable parts of rules . The unknown variable part is attached to... As a query parameter URL.

So why use it URL Inversion function url_for() structure URL, Instead of hard coding them into templates ?

  1. Inversion is usually compared to URL Hard coding is more descriptive .
  2. You can change... At one time URL, Without having to remember to manually change hard coded URL.
  3. URL Build to handle the escape of special characters transparently .
  4. The generated path is always absolute , Avoid unexpected behavior of relative path in browser .
  5. If your application is located in URL Beyond the root , for example , stay /myapplication instead of / in , be url_for() Will handle it correctly for you .

for example , Here we use test_request_context() Method to try url_for(). test_request_context() tell Flask Act as if it's processing a request .

from flask import url_for

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return f'{
      username}\'s profile'

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

Access to the results :

/
/login
/login?next=/
/user/John%20Doe

HTTP Methods in the protocol

Web The application is accessing URL Use different HTTP Method . In the use of Flask when , You should be familiar with HTTP Method . By default , The route only responds GET request . You can use route() Decorator method parameters to deal with different HTTP Method .

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

The above example keeps all methods of routing in one function , If every part uses some public data , It will be useful .

You can also divide the views of different methods into different functions . Flask For every common HTTP Method provides a way to use get()post() And other shortcuts to decorate such routes .

@app.get('/login')
def login_get():
    return show_the_login_form()

@app.post('/login')
def login_post():
    return do_the_login()

If GET There is ,Flask Will automatically add pairs HEAD Method support and according to HTTP RFC Handle HEAD request . Again ,OPTIONS Will automatically implement for you .

summary

I'm a little tired , Continue to do a wave next weekend .quickstart Half of it has passed before you know it , come on. !!!

原网站

版权声明
本文为[Coriander Chrysanthemum]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011328526052.html

随机推荐