Flash quick start 1

1, What is a Web framework?

  1. A piece of code has been encapsulated to assist the rapid development of the program, which is equivalent to the semi-finished product of the project
  2. Developers only need to write their own business logic code at the specified location according to the requirements of the framework agreement
  • For example, there are two ways to set up a hospital in a district:
 1. Enclosure, foundation, building, decoration and settlement
 2. Buy a building, decorate and settle in

2, Why use a Web framework?

  1. The development of web site, especially the server side, involves a wide range of knowledge and content. This will be more and more demanding for programmers. If a mature and robust framework is adopted, some basic work, such as security and data flow control, can be handled by the framework
  2. Program developers can focus on specific business logic.

Conclusion: reduce the development difficulty, improve the development efficiency, and there is no need to make wheels repeatedly

2, Three mainstream web frameworks of python

django
  characteristic:The large and fully equipped functions are much similar to aircraft carriers
  deficiencies:  Sometimes it's too heavy
 ​
 flask
  characteristic:Small and refined, with few functions, similar to Rangers
  There are many third-party modules, if flask Third party modules can be completely covered django
  And more and more like django
  deficiencies:
  More dependent on third-party developers
 
 tornado
  characteristic:Asynchronous non blocking supports high concurrency
  You can even develop game servers


 A:socket part
 B:Correspondence between route and view function(Route matching)
 C:Template syntax
 ​
 django
  A It's someone else's wsgiref modular
  B It's your own
  C It's your own(No, jinja2 Easy to use, but also very convenient)
 ​
 flask
  A It's someone else's werkzeug(Inside or wsgiref modular)
  B I wrote it myself
  C Use someone else's(jinja2)
 ​
 tornado
  A,B,C I wrote it myself

3, Introduction to Flask

Birth time: Flask was born in 2010. It is a lightweight Web development framework written by Armin roncher (human name) in Python language based on Werkzeug toolbox.
The Flask framework contains two cores: Werkzeug toolkit and Jinja2 template engine
Since flash does not provide additional functions, almost all functions need to be implemented by extension, as shown in the following list:

Flask-SQLalchemy: Operation database;
Flask-script: Insert script;
Flask-migrate: Manage the migration database;
Flask-Session: Session Storage mode designation;
Flask-WTF: Form;
Flask-Mail: Mail;
Flask-Bable: Provide internationalization and localization support, translation;
Flask-Login: Authentication user status;
Flask-OpenID: authentication;
Flask-RESTful: development REST API Tools for;
Flask-Bootstrap: Integrated front end Twitter Bootstrap Framework;
Flask-Moment: Localization date and time;
Flask-Admin: Simple and extensible management interface framework

More extended lists

Flash Chinese document

Flash English document

Web application role
The original purpose of the birth of the Web(World Wide Web) is to use the Internet to exchange working documents.

Everything starts with the request from the client.

  • All flash programs must create a program instance.
  • When the client wants to obtain resources, it usually initiates an HTTP request through the browser.
  • At this time, the web server uses a WSGI (Web Server Gateway Interface) protocol called web server gateway interface to hand over all requests from the client to the flash program instance.
  • Flask uses Werkzeug for routing distribution (correspondence between URL request and view function). Find the specific view function according to each URL request.
  • In the flash program, routing is generally realized through the decorator of the program instance. After obtaining the data by calling the view function, the data is transferred to the HTML template file. The template engine is responsible for rendering the HTTP response data, and then the flash returns the response data to the browser. Finally, the browser displays the returned results.

Flash program running process:
All flash programs must have one program instance.
After Flask calls the view function, it will return the return value of the view function to the client as the content of the response. Generally, the response content is mainly string and status code.
When the client wants to obtain resources, it usually initiates an HTTP request through the browser. At this time, the web server uses the WSGI (Web Server Gateway Interface) protocol to hand over all requests from the client to the flash program instance. WSGI is a simple and general interface between web server and web application defined for Python language. It encapsulates the underlying code and operations of accepting HTTP requests, parsing HTTP requests, sending HTTP responses, etc., so that developers can write web applications efficiently.
The program instance uses Werkzeug for routing distribution (the corresponding relationship between URL request and view function). Find the specific view function according to each URL request. In the flash program, the route is usually realized through the route decorator of the program instance. Add will be called inside the route decorator_ url_ The route () method implements route registration.
Call the view function to obtain the response data, and then transfer the data to the HTML template file. The template engine is responsible for rendering the response data, and then flash returns the response data to the browser. Finally, the browser processes the returned results and displays them to the client

# Import Flask class
from flask import Flask

#The Flask class receives a parameter__ name__
app = Flask(__name__)

# The decorator is used to map the route to the view function index
@app.route('/')
def index():
    return 'Hello World'

# The run method of the flash application instance starts the WEB server
if __name__ == '__main__':
    app.run()

During the running of the program, the URL will be used in the program instance_ Map saves the corresponding relationship between decorator route and view, and the print result is as follows:

Map([<Rule '/static/<filename>' (GET, HEAD, OPTIONS) -> static>,
 <Rule '/<string>' (GET, HEAD, OPTIONS) -> test>])

4, Flash initialization parameters

When creating a flash application instance, the package (module) specified by the current flash application needs to be passed in by default. Next, let's take a detailed look at some parameters that we need to pay attention to when creating a flash application:

app = Flask(__name__)

    def __init__(self, import_name, static_path=None, static_url_path=None,
                 static_folder='static', template_folder='templates',
                 instance_path=None, instance_relative_config=False,
                 root_path=None):

import_ Name: the package (module) where the flash program is located, which is passed to__ name__ Yes, it can determine the path that flash looks for when accessing static files
static_url_path: static file access path, which can not be transmitted. The default is: / + static
static_folder: the folder where static files are stored. It can not be transferred. The default is static
template_folder: the folder where template files are stored. It can not be transferred. The default is templates

5, Flag related configuration loading method

When the flash program is running, you can set related configurations, such as configuring the Debug mode, configuring the database connection address, etc. there are three ways to set the flash configuration:

  • Load from configuration object (common)
    app.config.from_object()

  • Load from configuration file
    app.config.from_pyfile()

  • Load from environment variables (understand)
    app.config.from_envvar()

Load the configuration information from the configuration object, configuration file or environment variable. The code is as follows:

#1. Import Flask class
from flask import Flask

#2. Create a Flask object to receive a parameter__ name__, It points to the package where the program is located
app = Flask(__name__)

# Configuration object, which defines a series of configurations to be added to the APP
class Config(object):
    DEBUG = True

# Load configuration from configuration object
app.config.from_object(Config)

# Load configuration from configuration file
#app.config.from_pyfile('config.ini')
# Load the relevant configuration corresponding to the specified environment variable name
#app.config.from_envvar('FLASKCONFIG') # FLASKCONFIG is also a file, similar to config.ini

#3. The decorator is used to map the route to the view function index
@app.route('/')
def index():
    return 'Hello World'

#4. Use the run method of the flash application instance to start the WEB server
if __name__ == '__main__':
    app.run()

In addition, the steps to add from the environment variable are as follows


Associated files are required.

5.2 parameters of app.run

You can specify the ip port of the running host, such as DEBUG.

app.run(host="0.0.0.0", port=5000, debug = True)

6, Flask routing

Route, path, parameter, request mode, etc.

6.1. Specify route

# Specify the access view function demo1, and the access path is / demo1
@app.route('/demo1')
def demo1():
    return 'demo1'

6.2. Pass parameters to routing

Sometimes we need to map the same type of URL to the same view function, for example, use the same view function to display the personal information of different users.

# Route pass parameter, integer
@app.route('/user/<int:user_id>')
def user_info(user_id):
    return 'the num is %d' % user_id


# Route pass parameter, string. If path is not specified, the default is string
@app.route('/user/<path:user_id>')
def user_info(user_id):
    return 'hello %s' % user_id

Tip: the reason why int and path can receive integers and strings is that werkzeug provides integerconverter and pathconverter

The system has its own converter:

DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

6.3 specify request method

In Flask, define a route. The default request method is:

  • GET
  • Options (included)
  • Head (self-contained)

If you want to add a requestor test, you can use methods to specify, for example:

@app.route('/demo2', methods=['GET', 'POST'])
def demo2():
    # Get the request method directly from the request and return it
    return request.method

7, View function, response

There are three main ways for view functions to return responses

  1. jsonfy
  2. url_for
  3. character string

1. String

1.Directly return the response body data
return 'character string'
2.Directly return the response body data+Status code
return 'character string',Status code
3.Directly return the response body data+Status code+Response header information
return 'character string',Status code,{'key':'value'}

2. Return json data through jsonify

format: jsonify(dict)
Simplified format: jsonify(key=value,key2=value2)

8, Request request

Request is the request object representing the current request in flash, including a request context variable (understood as a global variable, which can be used directly in the view function to get the current request)
Common attributes:

"""
- request.args: Get the query parameters after the question mark
- request.method: Get the request method
- request.url: Get the requested address
- request.files: What you get is input In label type Type is file File

"""
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def hello_world():

    print(request.method)
    print(request.url)
    print(request.args)
    print(request.args["name"]) #The dictionary does not recommend taking [] as a value
    print(request.args.get("name")) #If no error is reported, return None
    print(request.args.get("age",39)) #If not, set a default value

    return "helloworld"

if __name__ == '__main__':
    app.run(debug=True)

GET
http://127.0.0.1:5000/?name=laowang&age=12
ImmutableMultiDict([('name', 'laowang'), ('age', '12')])
laowang
laowang
12

9, Request hook

"""
- explain: When accessing the normal view function,Method of incidental execution
- There are four common request hooks:
- 1.before_first_request:Execute before processing the first request
- 2.before_request:Execute before each request,In this decorating function,once return,The view function is no longer executed
- 3.after_request:If no error is thrown, execute after each request
                  Accept a parameter: the response made by the view function
                  In this function, the response value can be,Do the last step before returning,Return again
- 4.teardown_request: Execute after each request
  Accept a parameter:Used to receive error messages

"""
from flask import Flask

app = Flask(__name__)


# before_ first_ The function decorated with request is executed during the first access. It is suitable for initialization operations, such as reading and writing io files
@app.before_first_request
def before_first_request():
    print("before_first_request")


# before_request is executed before each request. It is suitable for verifying request parameters and accessing statistics
@app.before_request
def before_request():
    print("before_request")


# after_request: after the view function is executed, this method is returned. It is suitable for unified processing of the returned value, such as returning a unified json data format
@app.after_request
def after_request(resp):
    print("after_request")
    resp.headers["Content-Type"] = "application/json"
    return resp


# teardown_request. After the request is destroyed, execute this method, which is suitable for exception information statistics
@app.teardown_request
def teardown_request(e):
    print(e)
    print("teardown_request")


@app.route('/')
def hello_world():
    return "helloworld"


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


if __name__ == '__main__':
    app.run(debug=True)

Keywords: Python Flask

Added by mdnghtblue on Sat, 16 Oct 2021 00:20:19 +0300