Development platform:.
OS Platform:ubuntu
Description:ubuntu 16.04.2 LTS
release:16.04
Codename:xenial
1. Virtual Environment Building (why use a virtual environment?)
Using a virtual environment to install flask, you can avoid program expansion package confusion and version conflicts between each project of the package, the virtual environment is a copy of the Python interpreter, and in a virtual environment you can install the corresponding expansion pack for each project, creating a separate virtual environment for each program. You can guarantee that a program can only access packages in a virtual environment. It does not affect the global Python interpreter installed in the system, thus keeping the global interpreter clean and tidy.
Virtual environments are created using VIRTUALENV to see if the system has Virtualenv installed:
$ virtualenv--version
Install the virtual environment (must be in the networked state)
$ sudo pip install virtualenv
$ sudo pip install Virtualenvwrapper
after installing the virtual environment, if you are prompted to not find the mkvirtualenv command, you must configure the environment variable:
# 1. Create a directory to store the virtual environment
mkdir $HOME/.virtualenvs
# 2. Open the ~/.BASHRC file and add the following:
Exportworkon_home= $HOME/.virtualenvs
source/usr/local/bin/virtualenvwrapper.sh
# 3, run
SOURCE ~/.BASHRC
Create a virtual environment (Ubuntu must be in the networked state, "Py2" is based on Python2 development projects)
$ mkvirtualenv Flask_py2
entering a virtual environment
$ Workon Flask_py2
exiting a virtual environment
If your environment is a real environment, you will be prompted deactivate: command not found
$ deactivate Flask_py
2. Installing Flask
Specify Flask Version Installation
$ pip Install flask==0.10.1
Mac System:
$ Easy_install flask==0.10.1
1.2.2 Installing flask Dependency Packages
Install dependent packages (in a virtual environment): Dependencies are a collection of environments that are developed and that the program needs to work. including software, plug-ins and so on.
We will generally use the dependency to be saved in a file, named requirements TXT file.
If you want to run our project in another environment, you can install all dependencies directly through the instructions.
Install the dependent packages (in the virtual environment):
(flask_py2) ... $ pip install-rrequirements.txt
(Note: With the Requirement.txt file, if you create a new project, you can quickly deploy a flask project of the same environment through the above command to run the system, do not need to package a package to install, and automatically configure the good flask, after the completion of the project, It is recommended to generate a final requirement.txt file that can be deployed quickly once disaster recovery is completed.)
Generate a dependent package record file (to be executed in a virtual environment):
(flask_py2) ... $ pip freeze >requirements.txt
test the installation success in Ipython
$ from Flask import flask
flask View (views) Learn
Flask Program Run process Analysis:
All flask programs must have a program instance.
Flask The view function is called, the return value of the view function is returned to the client as the content of the response. In general, the response content is mainly string and status code.
When a client wants to acquire a resource, it typically initiates an HTTP request through a browser. At this point, the Web server uses the WSGI (Web server Gateway Interface) protocol to hand over all requests from the client to the Flask program instance. Wsgi is a simple and common interface between Web servers and Web applications defined for the Python language that encapsulates the underlying code and operations that accept HTTP requests, parse HTTP requests, send HTTP, respond, and so on, enabling developers to write Web applications efficiently.
The program instance uses Werkzeug for routing distribution (the correspondence between URL requests and view functions). Depending on each URL request, find the specific view function. In the Flask program, the implementation of the route is generally implemented by the route adorner of the program instance. The route adorner internally calls the Add_url_route () method to implement the routing registration.
Call the view function, get the response data, the data into the HTML template file, the template engine is responsible for rendering the response data, and then returned by flask response data to the browser, the last browser processing returned results displayed to the client.
Example: New file hello.py:
#coding: Utf-8
# import Flask Class
From Flaskimport Flask
# Flask class receives a parameter __name__
App = Flask (__name__)
# The role of the adorner is to map the route to the View function index
@app. Route ('/')
Defindex ():
Return ' Hello MyWorld '
# The Run method of the Flask application instance starts the Web server
if __name__ = = ' __main__ ':
App.run ()
Example for routing parameters:
Sometimes we need to map the same class of URLs to the same view function,
For example, use the same view function to display the personal information of different users.
# The parameters passed by the route are handled by default as string, where int is specified, the content after the colon in the angle brackets is dynamic, and a numeric value can be specified.
@app. Route ('/user/<int:id> ')
Defhello_baidu (ID):
Return ' Hellobaidu%d '% ID
Abort function:
If an exception error occurs during the execution of the view function, we can use the Abort function to immediately terminate the execution of the view function. The Abort function allows you to return an error status code that is present in an HTTP standard to the front end, indicating the error message that occurred.
Using abort to throw a custom status code that does not exist in the HTTP standard has no practical significance. If the abort function is triggered, the statement following it will not be executed. It is similar to raise in Python.
From Flaskimportflask,abort
@app. Route ('/')
Defhello_baidu ():
Abort (404)
Return ' Hellobaidu ', 999
Catching Exceptions:
In flask, the catch exception is implemented by the adorner, and the ErrorHandler () receives the parameter as an exception status code. The parameter of the view function, which returns an error message.
@app. ErrorHandler (404)
Deferror (E):
Return ' page does not exist, please confirm and visit again. %s '%e
REDIRECT redirect Example
From Flaskimport redirect
@app. Route ('/')
Defhello_baidu ():
Return redirect (' http://www.baidu.com ')
Abort function:
If an exception error occurs during the execution of the view function, we can use the Abort function to immediately terminate the execution of the view function. The Abort function allows you to return an error status code that is present in an HTTP standard to the front end, indicating the error message that occurred.
using abort to throw a custom status code that does not exist in the HTTP standard has no practical significance. If the abort function is triggered, the statement following it will not be executed. It is similar to raise in Python.
From Flaskimportflask,abort
@app. Route ('/')
Defhello_baidu ():
abort (404)
return ' Hellobaidu ', 999
Catching Exceptions:
in flask, the catch exception is implemented by the adorner, and the ErrorHandler () receives the parameter as an exception status code. The parameter of the view function, which returns an error message.
@app. ErrorHandler (404)
Deferror (E):
return ' page does not exist, please confirm and visit again. %s '%e
REDIRECT redirect Example
From Flaskimport redirect
@app. Route ('/')
Defhello_baidu ():
return redirect (' http://www.baidu.com ')
Regular URL Example:
A regular URL is intended to match the specified URL, while matching the specified URL can limit access and optimize access paths.
From Flaskimport Flask
From Werkzeug.routingimport Baseconverter
Classregex_url (Baseconverter):
Def__init__ (Self,url_map,*args):
Super (Regex_url,self) __init__ (Url_map)
Self.regex = Args[0]
App =flask (__name__)
app.url_map.converters[' re '] = Regex_url
@app. Route ('/user/<re ("[A-z]{3}"):id> ')
Defhello_baidu (ID):
Return ' Hello%s '%id
Set up cookies and get cookies
Example one:
From Flaskimport Flask,make_response
@app. Route ('/cookie ')
Defset_cookie ():
RESP = Make_response (' This was to set cookie ')
Resp.set_cookie (' username ', ' Baidu ')
Return RESP
Example two:
From Flaskimport flask,request
#获取cookie
@app. Route ('/request ')
Defresp_cookie ():
resp = request.cookies.get (' username ')
Return resp
2.2 Extensions
Context: the equivalent of a container that holds some of the information in the process of running the Flask program.
There are two contexts in flask, request context, and application contexts.
Request Context
Both the request and the session belong to the requesting context object.
Request: Encapsulates the contents of an HTTP request for an HTTP request. Example: User = Request.args.get (' user '), gets the parameters of the GET request.
Session: Used to record information in a request session, for user information. Example: session[' name ']= user.id, can record user information. You can also get user information through Session.get (' name ').
Application Contexts (application context)
Both Current_app and G belong to the application context object.
Current_app: Represents the program instance that is currently running program files.
We can print out the name of the current application instance through Current_app.name.
G: When processing a request, the object is used for temporary storage, and the variable is reset for each request. For example: We can get some temporary request user information.
· When the app = Flask (_name_) is called, a program App object app is created ;
· Request WSGI Server calls Flask.call () when each HTTP request occurs, and then creates a request object within flask;
· The app's life cycle is larger than request and g, and when an app is alive, multiple HTTP requests may occur, so there will be more than one request and G.
· The final incoming view function, generated response object by return, redirect, or Render_template, is returned to the client.
Difference: Request context: Saves data for client and server interactions. Application context: During the Flask program run, some of the configuration information saved, such as the program file name, database connection, user information and so on.
Request Hooks
In the process of client and server interaction, some preparation or cleanup work needs to be handled, such as establishing a database connection at the beginning of the request, and specifying the interactive format of the data at the end of the request. In order for each view function to avoid writing repetitive code, Flask provides the functionality of a common facility, the request hook.
The request hooks are implemented in the form of adorners, and flask supports the following four request hooks:
Before_first_request: Runs before the first request is processed.
Before_request: Run before each request.
After_request: If no unhandled exception is thrown, run after each request.
Teardown_request: Runs after each request, even if an unhandled exception is thrown.
flask The implementation of the adorner route:
Flask has two major cores: Werkzeug and JINJA2. Werkzeug implements routing, debugging, and Web server gateway interfaces. JINJA2 implements the template.
Werkzeug is a Python library of functions that follows the WSGI protocol. It internally implements many of the underlying elements of the web framework, such as request and response objects, compatibility with the WSGI specification, support for Unicode, support for basic session management and signature cookies, integrated URL request routing, and so on.
The routing module of the Werkzeug Library is responsible for URL parsing. Different URLs correspond to different view functions, and the routing module parses the URL of the request information and matches it to the view function corresponding to the URL to generate a response message.
The routing module has the rule class (the object used to construct the different URL schemas), the map class (which stores all the URL rules), and the Mapadapter class (which is responsible for the specific URL matching work);
flask-script extension command line
By using the flask-script extension, we can pass in the parameters through the command line when the flask server is started. And not only through the App.run () method, for example, we can use the Python hello.pyrunserver--host IP address to tell the server on which network interface to listen for connections from the client. By default, the server listens only to connections originating from the computer on which the server is located, which is the localhost connection.
We can view the parameters by pythonhello.py Runserver--help.
From Flaskimport Flask
From Flask_scriptimport Manager
App = Flask (__name__)
Manager = Manager (APP)
@app. Route ('/')
Defindex ():
Return ' Twinkle stars in the sky '
if __name__ = = "__main__": Manager.run ()