Flask: The Cheat Sheet

Installation
$ pip install Flask
Hello World
# myapp.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World'

if __name__ == '__main__':
    app.run(debug=True)
URL Routing
@app.route('/foo/<name>/<int:age>')
def view(name, age):
    return '%s is %d years old' % (name, age)
Template Rendering
from flask import render_template
...
    return render_template('foo.html', var1=value1)
Flask for Django Users
Action Django Flask
Retrieve Query Params ("GET data") request.GET
request.GET['name']
request.args
request.args['name']
Retrieve form params ("POST data") request.POST
request.POST['name']
request.form
request.form['name']
Checking request type request.method request.method
Retrieve cookie value request.COOKIES request.cookies
Set a cookie response.set_cookie(key, value) response.set_cookie(key, value)
Sessions request.session['foo'] session['foo']
Access settings from django.conf import settings
settings.my_name
app.config
app.config['my_name']
Useful Functionality
from flask import ... This is a... usage
Flask Flask application object app = Flask(__name__)
request Thread-local request object request.args['test']
request.form['name']
session Thread-local session object session['name'] = 'value'
url_for URL Builder based on route names url_for('blog', 'id=45')
redirect Generates a redirect response return redirect('/hello')
Basic App Layout
my_app.py
static/
    logo.png
    base.css
templates/
   blog_post.html
   index.html
Packaged Application Layout
my_app/
    __init__.py
    application.py
    models.py
    static/
        logo.png
        base.css
    templates/
        blog_post.html
        index.html

Made with ♥ by Peter Baumgartner, using milligram.css.
Literally just a copy of this PDF.