The basic structure of the Flask program and the basic structure of the flask Program
1. Initialization
All Flask programs must create one program instance. The web server uses a protocol called Web Server Gateway to forward all requests received from the client to this object for processing.
from flask import Flaskapp = Flask(__name__)
The constructor of the Flask class has only one parameter that must be specified, that is, the name of the main module or package of the program.
2. Routing and view Functions
The client sends the request to the Web server, and the Web server then sends the request to the Flask program instance. The program instance needs to know which code is run for each URL request, so a ing between the URL and the Python function is saved. A program that processes the relationship between a URL and a function is called a route.
@app.route('/')def index(): return '
Functions such as index () are called view functions. The response returned by the view function can contain simple HTML strings or complex forms.
@app.route('/user/name')def index(name): return '
The content in the angle brackets is dynamic content. Any URL that matches the static part will be mapped to this route.
The dynamic part of the route uses a string by default, but you can also use the type definition. For example,/usr/<int: id> only matches the URL with the dynamic fragment as an integer. Flask supports int, float, and path types in routing.
3. Start the server
if __name__ == '__main__': app.run(debug=True)
Some option parameters can be accepted by the app. run () function to set the operation mode of the web server. Enabling the debug mode during the development process brings some convenience, such as activating the debugger and reload the program. To enable the debug mode, set the debug parameter to True.
4. A complete program
#!/usr/bin/env pythonfrom flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return '
Flask program containing Dynamic Routing
#!/usr/bin/env pythonfrom flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return '
Http: // 127.0.0.1: 5000/user/cairui
5. Request-response Loop
The following describes some design concepts of this framework.
① Program and request Context
To avoid a mess of view functions by a large number of dispensable parameters, the Flask request uses context to temporarily change some objects to globally accessible.
from flask import request@app.route('/')def index(): user_agent = request.headers.get('User-Agent') return '<p>Your browser is %s</p>' % user_agent
Flask uses context to make specific variables globally accessible in one thread, without interfering with other threads.
A thread is the minimum instruction set that can be managed separately. Processes often use multiple active threads and sometimes share resources such as memory or file handles. A multi-threaded web server creates a thread pool and selects a thread from the thread pool to process received requests.
(Table) Flask context global variables
Variable name |
Context |
Description |
Current_app |
Program Context |
Program instance of the current active program |
G |
Program Context |
The current request is used as a temporary storage object. This variable is reset in each request. |
Request |
Request Context |
The request object that encapsulates the content in the HTTP request sent by the client. |
Session |
Request Context |
User session, used to store the dictionary worth remembering between requests |
Flask activates (or pushes) the program and request context before distributing the request. After the request is processed, it is deleted.
from hello import appfrom flask import current_appcurrent_app.name=========================================Traceback (most recent call last)
from hello import appfrom flask import current_appapp_ctx = app.app_context()app_ctx.push()current_app.name
② Request Scheduling
from hello import appapp.url_map
③ Request hook
Sometimes it is useful to execute code before or after processing a request. For example, at the beginning of a request, we may need to create a database connection or authenticate the user who initiates the request. To avoid repeated code in each view function, Flask provides the function of registering a common function, which can be called before or after a request is distributed to the view function.
Flask supports the following four types of hooks:
-
- Before_first_request registers a function and runs it before processing the first request.
- Before_request registers a function and runs it before each request.
- After_request registers a function. If no unprocessed exception is thrown, it runs after each request.
- Teardown_request registers a function and runs after each request even if an unhandled exception is thrown.
④ Response
@app.route('/')def index(): return '
from flask import make_response@app.route('/')def index(): response = make_response('6. Flask Extension
Use Flask-Script to support command line options
#!/usr/bin/env pythonfrom flask_script import Managerfrom flask import Flaskapp = Flask(__name__)manager = Manager(app)@app.route('/')def index(): return '