Build a basic flask process
- Install virtual environment
python -m venv venv
Then run activate and enter the virtual environment;
- Install flask in a virtual environment
(venv) pip install flask
- Write basic helloworld program
# main.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "hello world!"
- Set FLASK_APP environment variable (windows) and run
(venv) set FLASK_APP=main.py
python -m flask run # 或flask run
After visiting localhost:5000, you can see the returned content.
Basic operation
Bind method to URL
- Direct binding
@app.route('/test')
def func():
return 1
- With parameters
@app.route('/test/<variable>')
def func():
return variable
Processing form data
First introduce the request object (see the concept section)
- Manipulate URL parameters, use the args attribute
request.args.get('key')
- Operate form-data, use form attribute
request.form['username']
Redirects and errors
Use redirect to redirect requests
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
Use errorhandler() decorator to decorate the error page
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
Operation response (response)
The return value of the view function will be automatically converted into a response object according to certain rules.
Example: The html page (string) returned by not_found will generate a response object with a 404 status code.
@app.errorhandler(404)
def not_found(error):
return render_template('error.html'), 404
If a dict is returned, it will be automatically converted to a JSON response
@app.route("/me")
def me_api():
user = get_current_user()
return {
"username": user.username,
"theme": user.theme,
"image": url_for("user_image", filename=user.image),
}
session与cookies
from flask import Flask,request,session
app = Flask(__name__)
app.secret_key = b'sdafdddd\x]\x'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
Concepts and issues
What is WSGI
- WSGI stands for Python Web Server Gateway Interface, which specifies a standard interface between a web server and Python web applications or web frameworks to improve the portability of web applications among a series of web servers
- The WSGI standard is that a Web program needs to have a callable object (function) that can accept two parameters. The first parameter is the environ dictionary, and the second parameter is the function called by the callable object to initiate a response.
- All the information of the http request can be obtained through environ, and the data of the http response can be used as the body through start_response plus the return value of the function.
def hello(environ, start_response):
status = "200 OK"
response_headers = [('Content-Type', 'text/html')]
start_response(status, response_headers)
path = environ['PATH_INFO'][1:] or 'hello'
return [b'<h1> %s </h1>' % path.encode()]
How to handle request
Flask uses the global object request to process client requests.