import flask; create app; run app
from flask import Flask
app = Flask(__name__)
app.run(debug=True, host=”0.0.0.0”, port=5000)
Populate and format a jinja template w/data
from flask import render_template
params = {}
render_template(“template.html”, **params)
Get cookies
from flask import request
request.cookies.get(“cookie”, “default”)
Get headers
from flask import request
request.headers.get(“cookie”, “default”)
Variable route rule
@app.route(“/path/<type:name>
def fun(name):
pass</type:name>
Variable route types
string, int, float, path, uuid
Manually escape html
from markupsafe import escape
def route():
escape(sus_content)
Construct/reverse a URL
from flask import url_for
@app.route(‘/user/<username>')
def profile(username):
return f'{username}\'s profile'</username>
with app.test_request_context():
print(url_for(‘profile’, username=’John Doe’))
TODO: Markup
from markupsafe import Markup
Use session (cookie) state
from flask import session
app.secret_key = b’some_random_bytes’
def route():
session[“varname”] = value
Store data (database connection) on the app context
from flask import g
def get_db():
if ‘db’ not in g:
g.db = connect_to_database()
return g.db
@app.teardown_appcontext
def teardown_db(exception):
db = g.pop(‘db’, None)
if db is not None:
db.close()Return a json response from a route
Return a dict or list object from the route handler
How to receive a file in a route handler
Set enctype=”multipart/form-data” on POSTing form
@app.route(‘/upload’, methods=[‘GET’, ‘POST’])
def upload_file():
if request.method == ‘POST’:
f = request.files[‘the_file’]
f.save(‘/var/www/uploads/uploaded_file.txt’)
How to receive a JSON payload
Client must set Content-Type: application/json
# Use POST/PUT/PATCH
@app.route(‘/api/data’, methods=[‘POST’])
def receive_json():
json_data = request.get_json()
#json_data = request.json #equivalent direct property access
How to perform a redirect
from flask import redirect, url_for
@app.route(‘/’)
def index():
return redirect(url_for(‘login’))
How to return an error from a route
from flask import abort
@app.route(‘/login’)
def login():
abort(404)
Optional - to provide a custom error page
@app.errorhandler(404)
def page_not_found(error):
return render_template(‘page_not_found.html’), 404
How to send messages to the built in logger
app.logger.debug(‘A value for debugging’)
app.logger.warning(‘A warning occurred (%d apples)’, 42)
app.logger.error(‘An error occurred’)