Python project Flask ipv6 dual stack support transformation

1. Background

Insert image description here

  Flask is a micro (lightweight) WSGI Web framework (a set of libraries and modules) developed in Python language, based on the Werkzeug WSGI toolbox/library and Jinja2 template engine. Of course, Python's WEB frameworks include: Django, Tornado, Webpy, let’s not mention it for now. Flask is licensed under the BSD license. Flask is also called a microframework . Flask's goal is to keep the core simple and extensible, that is, it uses a simple core. By default, Flask does not include a database abstraction layer, form validation, or other existing What the library can handle, other functions can be added with Flask-extension: ORM, form validation tools, file uploads, various open authentication technologies, etc., just like Flask natively. Due to these features, it is simple to use and has strong freedom. It can help users quickly and easily build their own web servers. It is widely used and is especially suitable for building small to medium-sized web applications. In addition, Flask supports RESTful. Flask makes it easy to use RESTful API and can easily create RESTful web services. The difference between Flask and other frameworks (especially frameworks using other programming languages) is that it does not bind functional libraries such as database queries or form processing, and the entire ecosystem they constitute. It tends to put no restrictions on the implementation of these functions, allowing developers to focus more on the core code and expand as needed. The following figure is a Flask Web architecture of the scene:

Insert image description here
  The on-site business scenario adopts a similar architecture as shown above, and also uses gunicorn to manage the Flask web project and provide external services; however, the group requires that all IPv6 be implemented (three-level ipv6 implementation: the browser converts the third-level function, and all support ipv6) ; It was found on site that the Flask web application was not monitoring the ipv6 address, nor was Gunicore; how to configure it, and finally achieve IPv4/6 dual-stack support.
Insert image description here

Live environment versions: Python3.6.3 and 2.7.18, Werkzeug (0.16.0), tensorflow (1.6.0), numpy (1.18.0), wheel (0.33.6)
, wrapt (1.11.2), setuptools (42.0 .2), six (1.13.0), opencv-python (4.1.2.30), pandas (0.25.3), Jinja2 (2.10.3), gunicorn (19.9.0), gevent (1.3.5), Flask ( 1.1.1), Click (7.0), backports.lzma (0.0.14),

Related resource links : jinja , Flask Chinese documentation , Flask English documentation , python-docx , pandas , sourceforge , codingdict programming dictionary , pytorch Chinese , numpy Chinese , numpy documentation , python3 , Flask Chinese documentation , Flask introduction , Flask quick guide , Flask GitHub , Flask third-party documentation , gunicorn configuration guide , front-end entry and advanced learning notes , Flask official documentation

2. Flask framework and description

2.1. Review of related concepts

WSGI : Web Server Gateway Interface (WSGI), which is a specification for a common interface between Web servers and Web applications. It has been adopted as the standard for Python web application development. 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. Python uses wsgi gateway for web development. Flask is based on wsgi gateway. The app instance in flask is also called a wsgi application.
Insert image description here

WERKZEUG : It is a WSGI toolkit that implements request, response objects and other utility functions. This can be used to build web frameworks on top of. The Flask framework uses Werkzeug as one of its basic modules.

Jinja2 : It is a popular template engine for Python . The web template system combines templates with specific data sources to render dynamic web pages.

Python’s frameworks are basically those of MTV :

M: Models model layer, responsible for database modeling and dealing with databases
T: Templates template layer, used to process web page content displayed by users
V: Views: View layer, responsible for business logic, and calling Model and Template at appropriate times for processing The part that interacts with the user, handles the user's request and gives the response content.
URL dispatcher: distributes page requests for each URL to different Views for processing, and the Views then call the corresponding Model and Template.

Insert image description here

Insert image description here
Insert image description here
When the Flask Web project is running, if a front-end request is received, it is parsed through the control layer and matched with the route to find the corresponding view function and then executes business layer logic processing. If necessary, the REST API can be quickly called during business logic processing. The interface is used to connect to specific services; when there is a need to operate the database, it can be handed over to the data layer for processing. The database operation can call the ORM model to instantiate the database content into objects to complete data access.

Other language frameworks mostly use the MVC architecture:

M: Models model layer, responsible for the relational mapping (ORM) of business objects and databases.
V: Wiews view layer, used to process the content displayed by the user, equivalent to MTV's TC
C: Controller: controller, used to process user requests and responses, equivalent to MTV's V
Insert image description here

The schematic diagram of the relationship between the three parts is as follows:
Insert image description here
Some concepts of the Flask framework:

1. Application object : The application object is the core object of the Flask application. It is an instance of the Flask class . The application object is the main interface used to create web applications.

2. Context : There are two contexts in the Flask framework : application context and request context. The application context provides a global context for the application, while the request context provides a context for each request.

3. Routing : It is URL mapping in Flask application . It specifies the relationship between URLs and view functions.

4. View function : View function is the function in the Flask application that handles requests . They use decorators to bind routes to functions.

5. Templates : Templates are files used in Flask applications to render HTML pages . They are rendered using the Jinja2 template engine.

6. Form : A form is an HTML form used in a Flask application to collect user input data . Generally use the WTForms library for validation and processing.

In comparison, the main modules of the Flask framework are as follows:

1. Application module : The core module of Flask, responsible for creating Flask application objects, defining some application-level configurations and functions, and managing the entire application life cycle. It is the entrance to the entire Web application and is responsible for receiving HTTP requests and returning responses. It is also responsible for routing, error handling, context and other functions.
2. Routing module : Flask uses decorators to define the mapping relationship between URL routing and view functions . 3. View module : The view function is the core of the Flask web application. It processes HTTP requests and returns responses , and can return HTML pages, JSON data, etc. 4. Template module : Flask uses Jinja2 template engine to generate HTML pages. The template engine provides rich syntax and filters to easily generate complex HTML pages. A template is a file containing response text, usually an HTMl file. The file can contain "place variables" to represent dynamic content. The specific value can only be obtained in the request. The "place variables" will eventually be replaced by the real values. The template will eventually be parsed into a response string. This process is also called "rendering". By default, Flask will automatically search for templates in the templates subfolder in the program folder. By default, you need to create a templates subfolder and put HTML files in it. 5. Database module


: Flask can easily integrate a variety of databases, including MySQL, PostgreSQL, SQLite, etc.
6. Form module : Flask-WTF is a form processing extension of Flask. It provides convenient form processing methods and can easily create forms, verify form data, etc.
7. Extension module : Flask’s extension module provides various functions, such as email sending, caching, login authentication, etc.

Among them, application modules usually include the following content:

1) Create an application object : Use the Flask class to create an application object. The constructor of the Flask class requires the name of the application to be passed in as a parameter. 2) Configure the application : You can use the config attribute to configure the basic properties of the application, such as debugging mode, keys, database connections, etc. 3) Register route : Use the route decorator to register the mapping relationship between URL routes and view functions. Routing defines the mapping relationship between the URL address of the HTTP request and the view function. 4) Define view function : View function is a function that processes HTTP requests and can return HTML pages, JSON data, etc. View functions typically use the route decorator to define URL routes. 5) Context management : Flask applications use context objects to manage: request context and application context. The request context contains information related to each HTTP request, such as request headers, request parameters, etc. The application context contains application-related information, such as configuration information, database connections, etc. 6) Error handling : Flask applications can register error handling functions




To handle errors that occur in HTTP requests, such as 404 errors, 500 errors, etc.
7) Extension management : Flask applications can add application functions, such as database connections, caching, email sending, etc., by registering extension objects.
8) Start the application : Start the application through the run method so that it can receive HTTP requests.

#导入了 Flask 类和 render_template 函数,Flask使用render_template 函数封装了Jinja2模板引擎,web网页模板需要flask内的render_template模块
from flask import Flask,render_template
#创建了一个 Flask 应用程序对象,使用了__name__ 作为应用程序的名称
app = Flask(__name__)

#配置应用程序的基本属性,包括调试模式和密钥等
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'your_secret_key'

#或者单独写入待外部文件,这里调用即可
app.config.from_pyfile('config.ini')

'''注册路由和视图函数;使用 @app.route() 装饰器来注册 URL 路由和视图函数之间的映射关系
定义了三个视图函数,分别对应不同的 URL 地址,对应返回不同的响应内容'''
@app.route('/')
def hello():
    return 'hello world'
@app.route('/user/<name>')
def user(name):    
	return 'Hello, %s !'  % name
#/hello/ 和 /hello/<name> 两个路由对应的是同一个视图函数,使用了 Flask 支持的多路由规则
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):    
	return render_template('hello.html', name=name)  '''使用render_template模块来渲染模板文件,通过第二个参数传递数据变量;传入render_template()内的第一个参数是html模板名,后面的参数都是键值对;传参时是赋值式(在html内的标识)= (传入的变量名),也可以用args,把数据以key value 形式传入字典把整个字典变量名传入到html里,直接调用key即可'''
	
#字典传入模板案例
@app.route('/')
def index():
    my_str = 'hello world'
    my_int = 123
    my_list = [1, 2, 3, 48, 93]
    my_dict = {
   
    
    'name': '张兰', 'age': 19

Guess you like

Origin blog.csdn.net/ximenjianxue/article/details/132909939