Python’s web framework is quite similar to each other, thanks to the WSGI standard, so the first time when you learn a new Python web development framework, there are a few essential things you should know, and those will help you to get started fast.
1, Read parameter from Query String:
1 2
from flask import request searchword = request.args.get("key")
2, Read parameter from post body
1 2
from flask import request username = request.form.get("username")
3, Read uploading file content from form body
1 2 3 4 5 6 7
from flask import request f = request.files['the_file'] content = f.read() print(f.content_type) print(f.mimetype) print(f.name) print(f.filename)
# get cookie example defhandler(): username = request.cookies.get('username')
Set Cookie:
1 2 3 4 5 6
from flask import make_response
defhandler(): resp = make_response(render_template("home.html")) resp.set_cookie('username', 'the username') return resp
6, Redirect
301: Move permanently
Use this one if one of url is permanently moved to another location
1 2 3
from flask import redirect defhandler(): return redirect("/some-url", 301)
302: Found
1 2 3
from flask import redirect defhandler(): return redirect("/some-url", 302)
303: See other (most common)
Use this in the scenario that after user posted some data, system wants to redirect this user to get another page url
1 2 3
from flask import redirect defhandler(): return redirect("/some-url", 303)
7, Return response with status code
1 2 3 4
# use an extra returned value as status code defhandler(): page_content = render_template('error.html') return page_content, 404
8, Return response with custom headers
1 2 3 4 5 6 7 8 9
# use an extra returned value (second or third) as header defhandler(): page_content = render_template("home.html") headers = { "x-extra-key": "value" } return page_content, headers # or return page_content, 200, headers
9, Sessions
Flask’s built-in session will save session info into user’s client side (into cookie) after encrypting it, so the app need to specify a secret_key used for encryption. DO NOT give this key to any one! It should only be saved in the server side.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from flask import Flask, session, redirect
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret! # generate a good secret key: # $ python -c 'import os; print(os.urandom(16))' app.secret_key = b'some-secret-key-for-encrypting-session-data'