1 the initialization

All FLASK applications must create an application instance, and the Web server uses a WSGI protocol to hand over all requests from clients (such as browsers) to this object.

from flask import Flask
app = Flask(__name__)
Copy the code

The Flask class constructor has only one parameter that you must specify, namely the name of the application’s main module or package. Flask uses this parameter to determine the location of the application, and thus the location of the other files in the application.

2 Routing and view functions

When you click on a website, the client (such as a browser) sends the request to the Web server, which sends the request to the Flask application instance. The application instance needs to know what code to execute for each URL request, so it saves a mapping of URLS to Python functions. The program that handles the relationship between urls and functions is called routing. Flask the easiest way to define a route in Flask is to use the decorator app.route:

@app.route('/')
def index(a):
    return '

hello world!

'
Copy the code

Decorators are a standard feature of the Pyton language. A common approach is to register functions as event handlers and call them when a particular event occurs. The function that handles the inbound request in this way is called the view function, and the return value of the function is called the response.

Flask supports dynamic urls. The contents of the route URL in Angle brackets are the dynamic parts, which Flask passes in as arguments to the view function when it is called.

@app.route('/user/<name>')
def user(name):
    return '

hello, {}!

'
.format(name) Copy the code

The dynamic part of the route uses strings by default, Flask supports string, int, float, and the path type, which is a special string that, unlike String, can contain forward slashes.

3 A complete application

## hello.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index(a):
    return '

hello world!

'
Copy the code

4 Web development server

Flask application comes with a Web development server and is started by Flask Run. This command looks for application instances in the Python script specified by the FLASK_APP environment variable. To start hello. Py from the previous section 1, make sure the virtual environment is activated 2, install flask 3, start the Web development server

  • Linux and MacOS users
(venv) $export FLASK_APP=hello.py (venv) $flask runCopy the code
  • Windows users
(venv) $set FLASK_APP=hello.py (venv) $flask runCopy the code

The server starts polling and processes requests.

  • Flask provides development servers for development and testing only, not for production.
  • Flask web servers can also be started programmatically by calling the app.run() method. In older Flask versions, starting an application at the end of the main script that runs the application contains:
if __name__ == '__main__':
    app.run()
Copy the code

5 Debugging Mode

Flask applications can be run in debug mode, in which the development server loads two handy tools by default: the overloader and the debugger. After the overloader is enabled, Flask monitors all source code and automatically restarts the server when changes are detected. It is particularly convenient to run the launcher during development and automatically restarts after every change, greatly increasing productivity. The debugger is a Web-based tool that when an application throws an unhandled exception, the information appears in the browser and the Web server becomes an interactive stack trace in which you can review code and evaluate expressions anywhere in the call stack.

Debug mode is disabled by default. To enable this, set the DEBUG environment variable before executing flask Run.

(venv) $export FLASK_APP=hello.py (venv) $export FLASK_DEBUG=1 (venv) $flask RunCopy the code
  • If you want to start debug mode under the programmatic Start Web server, use app.run(debug=Ture)
  • Never start debug mode on a production server. The client can request remote code execution through the debugger, which may result in an attack on the production server. As a simple safeguard, ask for a PIN code when starting the debugger.

6 Command-line options

The Flask command supports several options, and –help allows you to see which options are available

(venv) $flask --helpCopy the code

The host parameter is particularly useful because it tells the Web server on which network interface to listen for connections from clients. By default, Flask’s Web development server listens for connections from localhost, so the server only accepts connections sent from the computer on which the Web server is running. If you want the Web server to listen for connections on the public network

(venv) $flask run --host 0.0.0.0Copy the code

Any computer on the network can access the server through http://x.x.x.x:5000. X.X.X.X is the IP address of the computer running the server.

7 Request-response loop

The request-response loop is at the heart of Flask’s mechanics.

7.1 Application and Request Context

Flask, when receiving requests from the client, gives the view access to the request object, which encapsulates the HTTP request sent by the client. A straightforward approach is to pass the request object as a parameter to the view function, but this results in an extra parameter in each view function. Flask uses context to temporarily make some objects globally accessible, in order to avoid cluttering view functions with a large number of optional parameters.

In fact, request cannot be a global variable. Imagine a multi-threaded server with multiple threads processing different requests from different clients at the same time. Each thread must see a different request object. Flask uses context to make specific variables globally accessible in one thread, while at the same time not interfering with other threads.

Flask has two types of context, application context and request context, and the following table shows the variables provided by both contexts.

The variable name context instructions
current_app Application context Indicates the application instance of the current application
g Application context An object that is used as temporary storage while processing requests and is reset on each request
request Request context A request object that encapsulates the content of an HTTP request made by a client
session Request context User session, which is a dictionary that stores values to be “remembered” between requests

Flask activates (or pushes) the application and request context before dispatching the request, and then removes it after the request is processed. After the application and request context is pushed, you can use the variables in the table above, which will cause an error if there is no push activation.

7.2 Request Dispatch

When an application receives a request from the browser, it finds the view function that handles the request, called request dispatch. Flask uses the app.route decorator to build a mapping between urls and view functions.

7.3 Request Object

Flask exposes request objects to the outside world through the context variable Request. This object contains all the information about the HTTP request sent by the client. The most common properties and methods in the request object are as follows.

7.4 Requesting a Hook

Flask provides the ability to register generic functions in order to avoid repeating the code in each view. Request hooks are implemented through decorators.

7.5 the response

Flask calls the view function and returns its value as part of the response. In most cases, the response is a simple string that is sent back to the client as an HTTP page. The view function can also return a status code, which by default is 200, indicating successful processing. 400 indicates that the request is invalid.

@app.route('/')
def index(a):
    return '<h1>bad request</h1>'.400
Copy the code

View functions can also return a response object, and sometimes we need to generate the response object in the view function function and then call various methods on the response object to further set the response. The response has a special type called a redirect.

8 Flask extension

Flask is a flexible framework with scalability in mind and does not provide fixed features such as databases and user authentication, giving developers more freedom to choose the best package for their application on demand.