I’m sure I’ve struggled with the question: how to master flask completely?

Flask is a lightweight Web application framework written in Python. The WSGI toolkit uses Werkzeug and the template engine uses Jinja2. Flask uses BSD authorization.

Flask is also known as a “microframework” because it uses a simple core and adds additional functionality with Extension. Flask has no default database, form validation tools.

Today we have invited Bu, a teacher who has been developing Python for many years, to bring us the first practice of flask development.

Share the start

Flask Development Hi everyone, let’s start sharing flask development.

Flask Web Framework introduction

Flask is a micro Web framework, the framework itself is very simple, small does not mean that its function is weak, the core code is based on Werkzeug, Jinja 2 libraries, it is in the form of plug-ins for function expansion, and plug-ins are easy to install and use, and can be self-developed extension plug-ins

Similar to other Web frameworks, request, route and response constitute a complete basic HTTP flow in Flask.

2. The Flask framework is very easy to use as a starter

Once you understand its basic structure, you can quickly start MVC development or use it as a back-end restfulApi to respond to data.

The first step is to install the flask in a virtual environment

Virtual environment, the current running environment is completely isolated from the system’s Python environment, here we use the Pyenv library to build the environment

The following uses centos as an example to describe how to install a virtual environment.

4, yum install zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel

2, the curl -l https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer

| bash

To configure the environment variables, add the following to ~/.bash_profile:

Copy the code
  1. The export PATH = “~ /. Pyenv/bin: $PATH”
  2.  
  3. eval “$(pyenv init -)” 
  4.  
  5. Eval “$(pyenv virtualenv – init -)”

Step 2: Activate this PyEnv in the build virtual environment

Python 2.7.10 (python2.7.10

2. We will download a Python version of 2.7.12

3, use sohu image source: http://mirrors.sohu.com/python/

Find the python 2.7.12 package and download it locally

Why use a virtual environment? Because virtual environments are independent of each Python environment, it is possible to run multiple projects on a single machine with virtual environments isolated and without dependencies.

~/. Pyenv /cache / ~/. Pyenv /cache

Pyenv Install 2.7.12 pyenv Install 2.7.12

Create a python virtual environment with fully isolated directories after installing version 2.7.12 successfully:

Pyenv virtualenv 2.7.12 venv27

mkdir -pv virtu

cd virtu pyenv local venv27 cd .. CD Virtu automatically activates the VENv27 environment

Step 3: Install PIP

Pip is a tool for installing Python third-party libraries

Sudo yum install epel-release sudo yum install epel-release

Sudo yum — y install PIP

Use Aliyun’s Python package to speed up PIP installation

Pip configuration ali Cloud image:

mkdir ~/.pip

Vim ~/. PIP /pip.conf, enter the following information

[global] index-url=http://mirrors.aliyun.com/pypi/simple/

trusted-host=mirrors.aliyun.com

Install the flask:

CD vnvn27 (Switch to a full virtual environment from the virtual environment you just built)

Pip install flask

Pip Freeze lists the third-party Python libraries currently installed and their versions

You can test whether the flask installation is successful by running the Python terminal and importing flask

2.0: WSGI specification

Python uses the WSGI gateway for Web development, and Flask is based on the WSGI gateway, an app for flask instances, also known as a WSGI application

Wsgi is python define a gateway protocol specification, pep333 related explanation: https://www.python.org/dev/peps/pep-0333/

from wsgiref.simple_server import make_server

The WSGIRef package is a reference that implements the WSGI standard and can be used for debugging purposes. This package is intended for test environments and is not recommended for production environments.

Simple_server implements a simple HTTP server that we can use to run a WSGI application

2.1: wsgi specification 2

In the following example, we can use wsGIref to implement a simple WSGI Web framework to understand its workflow:

2.2: wsgi specification 3

In the code above, we use the WSGIRef package to implement a wsGIWeb framework that matches the router dictionary handler with the URL suffix obtained from the env passed in

The Env argument contains information about the client’s request and the server’s environment. You can print it out and see the variables contained in it.

The Start_response function passed into the runServer application as a parameter must respond with Start_response (status,header), a function defined by the gateway interface.

As you can see from the above, WSGI serves as a bridge between the Web server and the Web application. The Web server listens to forward the client request to the interface implementing the WSGI specification, and WSGI then forwards the request to the upper-layer Web application. The Web application processes and generates a response back to the WSGI interface, and the Web server returns the received response to the client.

2.3: a most basic application

The Flask framework is also a web framework implemented in accordance with the above specification. We can look at the Flask source code for the above encapsulation, but it does a higher level of abstraction

You can see that the flask source code encapsulates the above start_respones using wsGI_app and the magic method __call__.

The next step is to run a Hello wordl in flask

2.4: A most basic application analysis

Copy the code
  1. /usr/bin/env python 
  2.  
  3. from Flask import flask 
  4.  
  5. app = Flask(__name__) 
  6.  
  7. @app.route(‘/’) 
  8.  
  9. def index(): 
  10.  
  11. The return of ‘< h1 > Hello World! < / h1 > ‘
  12.  
  13. if __name__ == ‘__main__’: 
  14.  
  15. app.run() 
  16.  
  17. python hello.py  

2.5: Basic application

The app = Flask(__name__) code uses the Flask class to generate an application instance

Copy the code
  1. @app.route(‘/’) 
  2.  
  3. def index(): 
  4.  
  5. Return ‘< h1 > hello world < / h1 >’

The HTTP server (Nginx, Apache) again forwards the request to the flask application instance app. @app.route(‘ /) maps the URL link to a Python function. We call the index function a view function.

For example, access 192.168.1.19

– “app. The route (‘/’)

Visit 192.168.1.19 / blog

– “app. The route (‘/blog)

2.6: Mutable URLS

In flask, we set the variable url like this

Copy the code
  1. @ app. The route (‘/hello / < name > ‘)
  2.  
  3. def hello(name): 
  4.  
  5. Return ‘< h1 > hello {}’. The format (name)

Example:

Visit 192.168.1.19 / hello/jack

Visit 192.168.1.19 / hello/rose

The part of <name> enclosed in Angle brackets represents the mutable part of the URL that corresponds to the Python processing function.

The following three types are commonly used to define mutable types

<string:name>, <int:uid>, <path:prefix>

2.7: Variable URL custom shifter

Flask can also use the BaseConverter class in Werkzeug to customize the flask’s url.

Here is a custom converter

Copy the code
  1. fromwerkzeug.routing import BaseConverter 
  2.  
  3. classListConverter(BaseConverter): 
  4.  
  5. def to_python(self, value): 
  6.  
  7. return value.split(‘+’) 
  8.  
  9. def to_url(self, values): 
  10.  
  11. return’+’.join(BaseConverter.to_url(value) for value in values)  

Add custom converters to urL_map app. When the client enters parameters, it can convert them with delimiters that we set ourselves

Copy the code
  1. app.url_map.converters[‘list’] = ListConverter 
  2.  
  3. @app.route(‘/home/<list:subs>’) 
  4.  
  5. def home(subs): 
  6.  
  7. # Use custom types
  8.  
  9. htm = ” 
  10.  
  11. for sub in subs: 
  12.  
  13. htm += ‘<h1>{}</h1>’.format(sub) 
  14.  
  15. return htm  

In a production environment, client-to-server, the general flow of developing applications using Python looks like this:

Flask requests, requests are one of the most important features in Web development

3.0 Flask Getting started: Requests

Copy the code
  1. from flask import request 
  2.  
  3. @ app. The route (‘ ‘)/hi
  4.  
  5. def hi(): 
  6.  
  7. Name = request. The args. The get (‘ name ‘)
  8.  
  9. Return ‘{} < / h1 > < h1 > hi’. The format (name)

Access:

192.168.1.19 / hi? name=mike

Flask request objects encapsulate the client request parameters

We can try print(request.__dict__) to see the request context variable

The request object is a global object encapsulated within the flask. This object is thread isolated and must be run in the context of the current request. Running it directly will report an error

Common Request client variables

Request. args Gets the query string transmitted from the client URL

Request. form retrieves information submitted from the client form

Request. json Gets the JSON string obtained from the client from the request body

Request. method Obtains the request method used by the client

Request.files Obtains files requested from the client

3.1 Flask Getting started: Responses and sessions

from flask import make_respones

Flask encapsulates make_response as client response, returns HTTP headers, status codes, etc. Resp = make_respone(‘ hello ‘.encode()), resp.set_cookie(‘ name ‘, ‘jack’), Using resP as a return gives you the flexibility to manually add cookies

Sessions are divided into client and server forms. From Flask ImportSession encapsulates client-based cookies, as shown in the following example:

The app.config object holds the default configuration for Flask along with the configuration variables that were written in our project. In general, some of the configuration in Flask is as follows

Read configuration in 4.1 Flask

app = Flask(__name__)

App. Config. From_object (‘ yourapplication. Default_settings’)

App. Config. From_pyfile (‘ config. CFG) ‘

The app.config.from_object() method looks for a configuration whose profile is a class

Write configuration files to app by wrapping them with functions so that configuration files in development and production environments can be distinguished by parameters.

4.2 Factory method to create APP

What is the factory method? The factory method is a design pattern, which can be simply understood as creating a batch of flask APP objects through a function, generating different apps according to different parameters

4.3 Why is the factory method needed to create APP?

When the app needs to be run, parameters can be passed through the factory method to generate different APP objects, so that different apps can be easily tested. In addition, multiple apps can be generated for request processing, traffic load, etc., as illustrated by the following example

5.0 Hook Functions

Flask hook functions register the decorated functions in the APP and execute them in different stages.

App.first_request: Executed before the first request

App.before_request: Executed before each request, it can be used to encapsulate intermediate keys, similar to Django Middleware

App.after_request: Executed after each request

App.teardown_appcontext: Executes after each request, regardless of whether an exception occurs

App. errorHandler: Accepts the status code and returns a custom error handling information page

5.1 Hook Function before_request

5.2 Hook Function ErrorHandler

5.3 the blueprint

Blueprints are modular applications that can easily distinguish different functions and routes and are easy to maintain. Blueprints are differentiated based on the same URL prefix.

View functions with similar functions are combined together as components of blueprints to split applications, greatly simplifying the complexity of large applications. Blueprints are registered in app objects, and blueprints are used in a manner similar to that of apps

Blueprints provide template filters, static files, templates, and other features

5.4 Blueprint Generation

Divide similar functions such as user into a blueprint module. Note that the blueprint file cannot have the same name as the blueprint object; otherwise, an error will be reported

5.5 Blueprint Registration

V When the above users are instantiated, they must be registered in the APP for the blueprint to take effect. Url_prefix indicates the url suffix added by the user

6.0flask for extended use

V Flask develops extensions in the form of plug-ins, many of which can be used directly by third party plug-ins to improve development efficiency. Common plug-ins for project development include Flask_SQLachemy, Flask_Redis, Flask_login, Flask_admin, etc

PIP install < plug-in name > is used to install the plug-in

V The following example is used by Flask_SQLachemy, which is the Flask plugin for SQLAlchemy, a well-known industrial-level ORM framework in python

6.1 flask_sqlalchemy

V instantiate Flask_SQLalchemy to generate db objects for subsequent initialization into app

6.2 Flask plug-in initialization

V Since the DB object needs to read the configuration in the APP and depends on the app context, the app is initialized by the above extension plug-ins such as the DB object, and the binding is completed before each app startup

6.3 Flask_SQLalchemy defines the model

With the above DB object, the model field inherits db. model, which represents the Model layer in MVC, and is used for database table field mapping association and data writing and saving.

6.4 Flask_SQLalchemy performs user authentication

Flask is a simple tutorial on how to start flask development and how to use modules.

Flask is an easy way to develop applications, and each web framework has its own advantages and disadvantages. For modern Web development needs, micro-frameworks are suitable for rapid iterative development. The best way to understand is to practice.


Author of this article: Not moving

Source: 51 cto