Flask 1: The core WerkZeug and Jinja2
Use Werkzeug for route distribution (mapping between URL requests and view functions) and Jinja2 to render templatesCopy the code
2. The Flask expansion pack
Flask-sqlalchemy: operation database; Flask-migrate: manage migration databases; Flask E-mail: email; Flask-wtf: forms; Flask-script: insert script; Flask-login: indicates the authentication user status. Flask-restful: a tool for developing REST apis; Flask-bootstrap: Integrated front End Twitter Bootstrap framework; Flask-moment: Localize the date and timeCopy the code
Flask 3. The application runs in the Flask
The client sends HTTP requests, and the Web server passes all requests from the client to the Flask application instance using the WSGI protocol (WSGI is a simple and generic interface between a Web server and a Web application defined for the Python language, It encapsulates the low-level code and operations of accepting HTTP requests, parsing HTTP requests, sending HTTP, responding and so on, so that developers can write Web applications efficiently.) Program instances use Werkzeug to do routing distribution (the corresponding relationship between URL requests and view functions). Based on each URL request, find the specific view function. In Flask programs, routing is generally implemented through the route decorator of the program instance. The add_url_route() method is called inside the Route decorator to implement route registration and call the view function. After obtaining the response data, the data is passed into the HTML template file. The template engine is responsible for rendering the response data, and then the Flask returns the response data to the browser, and the browser processes the returned results and displays them to the client.Copy the code
4. Status code, Redirect, render_template(), URl_for, flash
A. Customize the status code that follows the returned response @app.route('/')
def hello_itcast():
return 'hello itcast',500 b. Redirect @app.route('/')
def hello_itcast():
return redirect("http://www.baidu.com"1. Url_for () takes a view function name and returns the corresponding URL 2. Load static parameter <link rel='stylesheet' href="{{ url_for('static',filename='css/index.css')}}">
<li>{{ book.name }} <a href="{{ url_for('delete_book',book_id=book.id) }}"> delete < / a > < / li >Copy the code
5. Error page customization and template context handling functions
A. Customize 404 page (catch exceptions) @app.errorHandler (404)Pass in the error code to handle
def page_not_found(e): Accept an exception object as a parameter
user = User.query.first()
return render_template('404.html', user=user), 404 # return template and status code@app.context_processor def inject_user(): @app.context_processor def inject_user(): @app.context_processor def inject_user():The function name can be changed at will
user = User.query.first()
return dict(user=user) Return {'user': user}
Copy the code
6. Url customization
from flask import Flask
from werkzeug.routing import BaseConverter
class Regex_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>')
def hello_itcast(id):
return 'hello %s' %id
Copy the code
7. Use of abort function
From flask import flask,abort @app.route()'/')
def hello_itcast():
abort(404)
return 'hello itcast'999 The abort status code must be the HTTP status code. Common status codes are as follows: The status code consists of three digits. The first digit defines the category of the response, which can be divided into five categories: 1XX: indicating information -- the request has been received and processing continues 2XX: success -- the request has been received, understood, accepted successfully 3XX: Redirection -- Further action must be taken to complete the request 4XX: Client error -- The request has a syntax error or the request cannot be implemented 5XX: Server side error -- the server failed to implement a valid request common status code:Copy the code
8. Request hooks
Flask’s request hooks refer to functions that are executed before and after a view function is executed, in which we can perform operations. Flask uses the decorator to give us four hook functions.
Before_first_request: Executed before the first request is processed. Such as linked database operations before_REQUEST: executed before each request. For example, permission verification after_REQUEST: invoked after each request if no unhandled exception is thrown teardown_request: invoked after each request even if any unhandled exception is thrown
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
print('View function execution')
return 'index page'
Run before the first request.
@app.before_first_request
def before_first_request():
print('before_first_request')
# execute before each request
@app.before_request
def before_request():
print('before_request')
# run after request
@app.after_request
def after_request(response):
# Response: The response data returned after the previous request is processed, provided that the view function does not fail
If you need to do additional processing on the response, you can do it here
Dumps configures the request hook
# response.headers["Content-Type"] = "application/json"
print('after_request')
return response
The view function is called after every request, regardless of whether the view function is abnormal or not, and takes an argument that is an error message from the server
@app.teardown_request
def teardown_request(error):
print('teardown_request: error %s' % error)
if __name__ == '__main__':
app.run(debug=True)
Copy the code
9. Common attributes of the request object
10. Upload files
Upload file is also a function we often use, the front-end upload a file, and then back-end processing save to the server. A file is a multimedia resource. Enctype =”multipart/form-data”. Create a template named upload.html and write the following code in the template:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
Copy the code
The upload.py file will look like this:
from flask import Flask, request,render_template,redirect,url_for
from werkzeug.utils import secure_filename
import os
from flask import send_from_directory
app = Flask(__name__)
UPLOAD_FOLDER = 'media'
ALLOWED_EXTENSIONS = set(['txt'.'pdf'.'png'.'jpg'.'jpeg'.'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# check whether the uploaded file is an acceptable suffix
def allowed_file(filename):
return "." in filename and filename.rsplit('. ', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload',methods=['GET'.'POST'])
def upload():
' ''File upload'' '
if request.method == 'GET':
return render_template('upload.html')
else:
print(request.files)
print(type(request.files))
if "file" not in request.files:
return redirect(request.url)
file = request.files.get('file') # fetch file
print(type(file))
if file.filename == ' ':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename) # use this function to determine if the file name is safe.
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # save file
return redirect(url_for('show',filename=filename))
# Show pictures
@app.route('/show/<filename>')
def show(filename):
# send_from_directory can load files from directories
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
Copy the code
Flask framework context
Reference: https://juejin.cn/post/6844903834750287879Copy the code
12.Response
After receiving and processing an HttpRequest, the view must return an HttpResponse object. You can use the make_response() function and then modify this code:
from flask import Flask, render_template, make_response
app = Flask(__name__)
@app.route('/setcookie', methods=['GET'.'POST']) # Support get and POST requests
def setcookie(): View function
resp = make_response(render_template('cookie.html')) Explicitly convert to an HttpResponse object
return resp
app.config['DEBUG'] = True
if __name__ == '__main__':
# 0.0.0.0 means that any address that represents the machine is accessible
app.run(host='0.0.0.0', port=5000) # run the program
Copy the code
13. Customize response information
Customize the response information, using the make_response function. Make_response (), the equivalent of HttpResponse in Django, has the same effect.
from flask import Flask, abort, Response, make_response
app = Flask(__name__)
@app.route('/')
def index():
# return (' custom response information, 502, {" name ":" xiaosong ", "age" : 12})
# Tuples can be assembled automatically without parentheses
{"name": "xiaosong", "age": 12} # return 'custom response information ', 502, {"name": "xiaosong", "age": 12}
# Custom status code can add description information
# return 'custom response information ', '520 love error', {"name": "xiaosong", "age": 12}
resp = make_response()
resp.headers['name'] = 'xiaosong'
resp.status = '520 love error'
return resp
if __name__ == '__main__':
# 0.0.0.0 means that any address that represents the machine is accessible
app.run(host='0.0.0.0', port=5000, debug=True) # run the program
Copy the code
The response returned with jsonfy is different from the response returned with json.dumps(data), which is shown in the Content-Type field in the response header
jsonify:
Content-Type: application/json
json.dumps(data):
Content-Type: text/html; charset=utf-8