


Python learning to analyze the operating principle of Flask (detailed explanation with pictures and texts)
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.
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.
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.
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:
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:
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:
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)
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:
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:
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>
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:
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)
同时,在该文件中创建了工厂方法实例:
app = create_app()
在工程方法中,对数据库进行了相关配置,创建了前端导航栏,同时对所创建的蓝本进行了注册。在创建的蓝本中主要涉及授权、路由及错误处理模块。
# 构造工厂方法 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
推荐学习: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!

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
