Flask
Brief introduction
Flask is using Python to write lightweight Web application framework . Based Werkzeug WSGI toolkit and Jinja2 template engine . Flask using the BSD license.
Flask is called "microframework", because it uses simple core, by extension add other functions. Flask no database used by default, form validation tool. However, Flask retained the amplification of flexibility can Flask-extension by adding the following features: ORM, form validation tools, file upload, a variety of open authentication technology.
Glossary:
Werkzeug : practical library of Python WSGI specification. Probably features are: HTTP header parsing the package, request and response objects, browser-based JS debugger compatible WSGI specification, Py2-3 support, Unicode support, support sessions and signature Cookie, URI and IRI support of Unicode tools, compatible WSGI each browser and server utilities, URL request routing system.
Jinja2 : for Python provides a fully functional stand-alone module, Jinja2 provides a full unicode support, and an optional integrated operating environment of the sandbox. Jinja2 does not belong to the Django framework, but Django templates and rendering tools similar to this, Django is not independent of the rendering module, so to JinJa2 to analyze.
microframework : miniature frame
Extension / Extension-the Flask : After supplements
Feature
Advantages: lightweight, extensible, third-party components complete
Cons: Only comes with assembly session, many third-party components result in relatively poor version compatibility.
pycharm steps to create a flask project
https://img2018.cnblogs.com/blog/1614606/201907/1614606-20190710163303172-1516152408.gif
Installation flask will be included with the installation of dependencies:
Jinja2 Template Language
MarkupSafe label language processing, security
Werkzeug German: tool means; role: app.run Werkzeug essence is executed in the run, and similar UWSGI
start up
Py create a file, writes the following:
Primary boot
from flask import Flask
app = Flask (__ name__) # "__ name__" represents the current file
app.run()
Advanced Boot:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello World!"
app.run()
Import Package
from flask import Flask, render_template, redirect, jsonify, send_file,session
Import render_template, the default storage path templates
- Create templates folder in the project root directory
- In this folder, right-Pycharm election is Mark Directory as-Template Folder, and select the template language is Jinja2
- Storing content render_template called in templates folder
Import redirect redirect
@app.route("/index")
def index():
return render_template('index.html')
@app.route("/reback")
def reback():
return redirect ( '/ index') # redirect here is redirected in url, i.e., the content of app.route
Import send_file, send files to the client
Action: Open and returns the file contents, automatically identify the file type, the response header added Content-type: File type
Note: When the browser does not recognize the Content-type, file downloads
Import REQUEST request (weight)
Let support request needs to be added in the methods decorator = () or [] @ app.route ( "/ login", methods = [ 'POST', 'GET'])
Flask in the request are public variables, global, easy to cover.
request.method |
Request method |
request.form --- get Form data in a form |
|
request.form.to_dict() |
All data are output to a dictionary |
request.form.get(‘key’) |
To key values |
request.form[‘键’] |
To key values |
|
|
request.url |
Obtaining access path |
request.args |
Url of acquisition parameters, such as / index? Id = 2 id = 2 in |
request.path |
Obtaining routing address |
request.values |
Get Data Form and in args |
request.environ |
Obtain original information request |
request.base_url |
Get url head, does not contain parameters |
request.headers |
Acquiring data request header |
*** Note: standard red coarse focus will be ***
*** introduced jsonify JSON format conversion (before useful in Flask-1.1.1 version) ***
Was added to the response header Content-type: application / json
In Flask 1.1.1 added version directly returned dictionary, you can no longer use the jsonify
Flask introduced in the session (not tripartite component)
Note: session Flask stored in the Cookies, the client is handed over to the custody mechanism.
Serialization of session
- Session using session need to import from the flask, and the session after all the operations are related to this variable by the
- Use app.secret_key session needs to be set, as used for encryption; and if this app.secret_key changes each time the server starts, then the session before the current can not pass through the decrypting SECRET_KEY
- Internal flask-session dictionary is created {username: pass username } followed by SECRET_KEY + + stamp signature encrypted form
- When the client sends a request to bring -request Cookie
- Flask receive encrypted string Session
- Secret_key decrypted string by encrypting the session, ultimately {username: pass username }
session deserialization
method
添加session:session['username']
Delete: session.pop ( 'username') or del session [username]
Clear all session: session.clear ()
获取session:session.get('username')
Decorator written (Review)
def pd(func):
def inner(*args, **kwargs):
if session.get('username'):
return func()
else:
return redirect('/login')
return inner
Increases with a plurality of views of a function of decorator
When you add a decorator same function as multiple views, there will be an error: Tips defines the function of multiple views of the same name, result in an error when calling, do not know which function to call. So we need to use the following methods to resolve errors
Method One: import functools
Py functools introduced in the file header
Then the interior decorator @ functools.wraps (func)
Example:
def pd(func):
functools.wraps @ ( FUNC ) # write the function name in parentheses
def inner(*args, **kwargs):
if session.get('username'):
return func()
else:
return redirect('/login')
return inner
Method two: endpoint = '*'
Example:
@app.route('/information',endpoint='information')
@pd
def information():
return render_template('information.html')
@app.route('/information2',endpoint='information2')
@pd
def information2():
return render_template('information2.html')
Flask Routing
@app.route(‘/index’)
endpoint mapping route - a view function __name __ = ""
Theory: endpoint Mapping -> "/ index": { "index": index} is the mapping
If the endpoint specified value, the view is a function of the value of endpoint; if not, the view is a function of the current function name; you can find a route through the endpoint.
methods=[“get”,”post”]
Current mode function supports the request, the request method is not allowed 405 error. If there are no methods
defaults={“id”:1}
The default parameters; Once the parameter is present, the view must have a function to receive the parameter, the parameter variable name must be consistent with the default defaults.
strict_slashes=True
Whether or not strictly follow the routes matching rules "/"
redirect_to=”/login”
308 301 or permanent redirection
After addition routing parameters
@app.route("/information/<int:page>/<int:page2>/<int:page3>")
@pd
def information():
print(page,page2,page3)
return “OK”
Dynamic routing parameters
/detail/<folder>/<filename>
FlaskResponse
render_template (.html) # return to the page file
redirect ( "/ login") # redirection route
"" # Returns the text content
jsonify # content-type : application/json
Flask 1.1.1 new features: can return type dict - essentially in jsonify ({key: value})
send_file # automatically opens the file and returns the contents of the file to identify the type of content-type: file type
FlaskRequest
from flask import request # public Object variable LocalProxy
request.POST.get()==request.form.get() -> .to_dict()
request.GET.get()==request.args.get()-> .to_dict()
request.json # request header with a content-type: application / json
request.data # content-type can not be identified or is not Form
request.files.get () Get file
request.method
request.headers
request.cookie
request.path
request.url
request.host
request.host_url
Flask configuration
Initial Configuration
Under app = Flask (__ name__) # current file
template_folder = "templatess" # Change template store directory; default is templates
static_folder = "statics" # static file storage path
static_url_path = "/ static" # static file access path; the default is "/" + static_folder
Config object configuration
app.default_config [ parameters ]
DEBUG-- coding phase, the code restart, log output level is low, the page will display details of the error, easily exploited by hackers.
TESTING-- testing phase , the higher the log output level, infinitely close to the online environment
Type configuration using:
class DebugSetting(object):
DEBUG = True
SECRET_KEY = "123456789"
SESSION_COOKIE_NAME = "I am just Session"
SESSION_TYPE = 'Redis'
app.config.from_object(DebugSetting)
Flask Blueprint Blueprint
Blueprint is a can not run the Flask objects, blueprints need to register on the app instance, the blueprint does not exist Config, and played a certain application isolation, the URL of management .
Examples blueprint py file:
from flask import Blueprint
Blueprint object name = Blueprint ( " blueprint name ", __ name__, template_ folder = " static folder name ", url_prefix = "/ domain name prefix ")
Examples of primary py file:
from Modular. py file name import blueprint blueprint imported object name #
app.register_blueprint ( blueprint object name ) registration #
Flask special decorator (available as intermediate)
app.before_request
Operations performed before entering the view request function.
return None # representation continues
# Other representations blocked
app.after_request
At the end view of the function, in response to a client before the operation, and the reverse execution.
Normal cycle: be1 - be2 - be3 - a view function - af3 - af2 - af1
Abnormal Cycle: be1 - af3 - af2 - af1
errorhandler redefinition error message
There are arguments decorator errorhandler ( listening Int 4xx error status code 5xx )
Example:
app.errorhandler @ ( 404 ) # 404 error status code, there can only monitor 5XX, 4XX
error404 DEF ( error_message ): # pass parameters must error_message
print(error_message)
return send_file("linux.mp4")
CBV
Example:
from flask import views
class Login(views.MethodView):
# 8 kinds of HTTP requests:
# Decorators = [a, b, c, d] # decorator
# Methods = [ 'get', 'post'] # allow request type
def get(self):
pass
def post(self):
pass
app.add_url_rule('/login', endpoint=None, view_func=Login.as_view(name='login'))
Flask third-party components
Flask all third-party components are required app.config, not only to draw configuration items, will increase or change configuration items
Flask-Session
flask-session is a session framework flask assembly, since the original flask signature cookie using the built-in session to save, this component will support the session saved in multiple places, such as:
redis: a tool for saving data, five types. Non-relational databases
memcached
filesystem
mongodb
sqlalchmey: that data to the database table inside
Example:
from flask import Flask, session
from flask_session import Session
from redis import Redis
app = Flask(__name__)
app.config [ 'SESSION_TYPE'] = 'redis' # Set the database session type connection redis
app.config [ 'SESSION_REDIS'] = Redis (host = ' hosts the IP ', Port = port , db = 6) # arrangement for connecting redis
Session (app) # config configuration read, rewrite in APP session_interface
To be added