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)

Mar 01, 2022 pm 06:23 PM
python

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles