Home > Backend Development > Python Tutorial > Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)

Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)

WBOY
Release: 2022-03-01 18:23:41
forward
5073 people have browsed it

This article brings you relevant knowledge about python, which mainly introduces issues related to the operating principle of Flask, and makes a brief analysis of the operating principle of Flask to enhance your understanding of Flask. ,I hope everyone has to help.

Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)

Recommended learning: python learning tutorial

 All Python web frameworks must follow the WSGI protocol, but here we still need to briefly review it Let’s take a look at the core concepts of WSGI.

There is a very important concept in WSGI: every Python web application is a callable object. In flask, this object is the app created by app = Flask(name), which is the green Application part in the picture below. To run a web application, you must have a web server, such as the familiar apache, nginx, or gunicorn in python. We will talk about the WSGIServer provided by werkzeug below. They are the yellow Server part in the picture below.
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
How to communicate between Server and Application is the function of WSGI. It specifies the interface of app(environ, start_response). The server will call application and pass it two parameters: environ contains all the information of the request. start_response is the function that needs to be called after application is processed. The parameters are status code and response. There is also an error message in the header.

The very important feature of WSGI application is that it can be nested. In other words, you can write an application that calls another application and then returns (similar to a proxy). Generally speaking, the last layer of nesting is the business application, and the middle is the middleware. The advantage of this is that business logic and other functions, such as current limiting, authentication, serialization, etc., can be implemented into different middle layers. Different middle layers and business logic are not related and can be maintained independently; and users can also Different middle layers can be dynamically combined to meet different needs.
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
Flask is based on the Werkzeug WSGI toolbox and Jinja2 template engine. Flask is licensed under the BSD license. Flask is also called a "microframework" because it uses a simple core and uses extensions to add additional functionality. Flask does not have a default database or form validation tool. However, Flask retains the flexibility of expansion, and you can use Flask-extension to add these functions: ORM, form validation tools, file uploads, and various open authentication technologies. We can understand that Flask is a core, and other functions are some plug-ins. Whatever function is needed, as long as the corresponding plug-in is found and inserted into the core, the function can be realized.

 How does Flask convert the code into a visible web page? First of all, we have to look at the general process of Web programs. For our Web applications, when the client wants to obtain dynamic resources (such as websites written in languages ​​​​such as ASP and PHP), it will initiate at this time An HTTP request (such as using a browser to access a URL), at this time the web application will perform corresponding business processing in the server background (such as operating the database or performing some calculation operations, etc.), fetching the data the user needs, and generating Corresponding HTTP response (of course, if you access static resources, the server will directly return the resources required by the user and will not perform business processing). The entire processing project is as follows:
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
In actual applications, different requests may call the same processing logic. HTTP requests with the same business processing logic can be identified by a type of URL. For example, in our blog site, all requests to obtain Articles content can be represented by URLs such as articles/. The article_id here is used to distinguish different articles. Then define a get_article(article_id) function in the background to obtain the corresponding data of the article. In addition, it is necessary to establish a one-to-one correspondence between the URL and the function. This is the so-called route distribution in Web development, as shown in the following figure:
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
In Flask, werkzeug is used for route distribution. Werkzeug is the underlying WSGI library used by Flask (WSGI, full name Web Server Gateway interface, or Python Web Server Gateway Interface, is a simple and common interface between web servers and web applications defined for the Python language).
 WSGI divides Web services into two parts: server and application. The WGSI server is only responsible for two things related to the network: receiving HTTP requests from the browser and sending HTTP responses to the browser; and the specific processing logic for HTTP requests is performed by calling the WSGI application. The WSGI workflow is shown in the figure below:
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
  In Flask, the route distribution code is very simple to write, as follows:

# 管理员注销页面
@main.route('/logout')
def logout():
    dm = DataManager()
    currentUsers = dm.getUsers('0')
    print(currentUsers[0])
    return render_template('currentUsers.html', users=currentUsers)
Copy after login

  After obtaining the data we need through the business logic function , the server will generate an HTTP response based on these data (for web applications, it is usually an HTML file, which can be directly read and interpreted by our client, that is, the browser). In Web development, the common practice is to pass the obtained data into an HTML template file provided by the Web application, and after rendering by the template system, we finally get the HTML response file we need.
  Generally speaking, although the requests are different, the display method of the data in the response is the same. In layman's terms, except for the data we request to obtain, everything else is the same, then we can design a template (Except for the fact that the data content can be changed, the rest are fixed HTML files). Let's take a blog site as an example. Although the specific article content of different articles is different, the content displayed on the page is the same except for the requested data, including title blocks, content columns, etc. In other words, for article, we only need to provide an HTML template and then pass in different article data to get different HTTP responses. This is the so-called template rendering, as shown in the figure below:
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
Use Jinja2 template rendering engine in Flask for template rendering (Jinja2 is a template engine based on python, and its function is similar to PHP smarty , J2ee's Freemarker and velocity. It fully supports unicode and has an integrated sandbox execution environment, which is widely used. Jinja2 uses BSD authorization). The workflow of Jinja2 is shown in the figure below:
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
In Flask, the template rendering code is also very convenient to write. The code is as follows:

@app.route('/articles/<article_id>/') 
defget_article(article_id):
returnrender_template('path/to/template.html', data_needed)</article_id>
Copy after login

In Flask, we process a The request process is to first determine which business logic function will be processed based on the URL submitted by the user, and then perform operations in the function to obtain the required data. The obtained data is then passed to the corresponding template file, and Jinja2 is responsible for rendering the HTTP response content, that is, the HTML file of the HTTP response, and then Flask returns the response content.
 The following mainly uses example projects to briefly analyze the operating principle of Flask. In the example project, the program factory function and blueprint are used. The project directory structure is as follows:
Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
In the manager.py file, the entry function for project startup is defined:

# 确保服务器只会在该脚本被 Python 解释器直接执行的时候才会运行,而不是作为模块导入的时候。
if __name__ == '__main__':
    # 启用cmd命令行
    # manager.run()
    app.run(host='0.0.0.0', port=9000, debug=True)
Copy after login

同时,在该文件中创建了工厂方法实例:

	app = create_app()
Copy after login

  在工程方法中,对数据库进行了相关配置,创建了前端导航栏,同时对所创建的蓝本进行了注册。在创建的蓝本中主要涉及授权、路由及错误处理模块。

# 构造工厂方法
def create_app():
    # 在这里__name__ == __main__
    app = Flask(__name__)
    app.url_map.converters['regex'] = RegexConverter
    # 防止跨站攻击 注:为了增强安全性,密钥不应直接写入代码,而应该保存在环境变量中
    # app.config['SECRET_KEY'] = 'hard to guess string SUNNY2017'
    # app.secret_key = 'Sunny123456'

    # flask提供的读取外部文件
    app.config.from_pyfile('config')

    # basedir = os.path.abspath(os.path.dirname(__file__))
    # print(basedir)

    # 配置数据库连接
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://lmapp:lmapp@localhost/smp'
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

    nav.register_element('top', Navbar(u'APP安盾',
                                       View(u'当前在线', 'main.index'),
                                       View(u'全部用户', 'main.all_users'),
                                       View(u'注销', 'main.logout'),
                                       View(u'修改密码', 'main.chgpwd'),
                                       ))
    nav.init_app(app)
    db.init_app(app)
    bootstrap.init_app(app)
    # init_views(app)
    from .auth import auth as auth_blueprint
    from .main import main as main_blueprint
    # 注册蓝本 url_prefix='/auth'
    app.register_blueprint(auth_blueprint,)
    app.register_blueprint(main_blueprint, static_folder='static')
    return app
Copy after login

 推荐学习:python教程

The above is the detailed content of Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template