Show Menu

Python Flask Cheat Sheet by

python     web     application     flask

Routing

route() decorator is used to bind a function to a URL

Example:
@app.r­ou­te(­'/')

By default a route only answers to GET requests, but you can provide the methods argument.

@app.r­ou­te(­'/l­ogin', method­s=[­'GET', 'POST'])

flask-­restful

With Flask-­Restful you can create RESTful API with your Flask app

Create an Flask App
app = Flask(­__n­ame__)
Then create the Api object passing the App object
api = Api(app)

Then you can create Resou­rces and add them to the API

class NewsFi­nde­r(R­eso­urce): pass
api.a­dd_­res­ouc­e(N­ews­Finder, '/', '/news')

You can implement each HTTP verb with functions named like the verb, but in lowercase.

Example:
def get(self): pass
def put(self, id): pass

To parse arguments passed by the url use
parser = reqpar­se.R­eq­ues­tPa­rser()
You can pass parse­_ar­gs(­str­ict­=True) to throw an error if arguments that were not defined by you has been passed

Add the arguments with parse­r.a­dd_­arg­ume­nts­('l­imit', type=int, help='Help Text', requir­ed=­True)
You can specify the location to look for this argument with add_a­rgu­men­t('­Use­r-A­gent', locati­on=­'he­ade­rs')
Example locations: form, args, headers, session, cookies, files

Then inside the function you can args = parser.pa­rse­_ar­gs() to get the parsed args. This variable args will become a dictionary with the values, ccess via args[­'li­mit']
Imports
from flask_­restful import Api, Resource, reqparse

Flask_jwt

from flask import Flask
from flask_restful import Api, Resource
from flask_jwt import JWT, jwt_required, current_identity

app = Flask(__name__)
app.config['SECRET_KEY'] = 'my-secret'

api = Api(app, prefix='/api/v1')

USER_DATA = {
"amicheletti": "coracaopeludo"
}

class User(object):

def __init__(self, id):
self.id = id

def __str__(self):
return "User (id={})".format(self.id)


def verify(username, password):
if not (username and password):
return False
if (USER_DATA.get(username) == password):
return User(id=123)


def identity(payload):
user_id = payload['identity']
return { "uid": user_id }


jwt = JWT(app, verify, identity)


class UltimateQuestion(Resource):

@jwt_required()
def get(self):
return { "meaningoflife" : 42, "who_asked" : dict(current_identity) }


api.add_resource(UltimateQuestion, '/', '/life')


if __name__ == "__main__":
app.run(debug=True)
You must have an authe­nti­cat­ion­_ha­ndl­er() which takes 2 arguments and a ident­ity­_ha­ndl­er() which takes 1 argument

Authen­tic­ation handler must return an Object that has an id attribute
Identity handler return what is going to be send to 'iden­tity' key of the JSON

To get the token, curl POST to the /auth like this:
curl -H "­Con­ten­t-type: applic­ati­on/­jso­n" -X POST -d '{"u­ser­nam­e":"a­mic­hel­ett­i","p­ass­wor­d":"c­ora­cao­pel­udo­"}' http:/­/12­7.0.0.1­:5­000­/auth`

URL Building

When routing some function to a URL, you can use function url_f­or() to generate the URL to that function.

Example, if you have something like
@app.r­ou­te(­'/u­ser­/<u­ser­nam­e>') def profil­e(u­ser­name): pass you use url_f­or(­'pr­ofile', userna­me=­"­And­re") to get the URL for that route.

That way you can avoid having to change the hardcoded URL everywhere in the code.

File Uploads

To handle file uploads with Flask, the HTML form must be set with enctyp­e="m­ult­ipa­rt/­for­m-d­ata­"

Then you can use it from a dictionary in reque­sts.files
Example:
f = reques­t.f­ile­s['­the­_file'] f.save­('/­var­/ww­w/u­plo­ads­/up­loa­ded­_fi­le.t­xt')

Redirects and Errors

redir­ect­('u­rl') Pass a URL to this function to redirect a user
abort­(401) This will abort the request early with an error code

To customize the error page use @app.e­rr­orh­and­ler­(404), but don't forget to pass the error code. Example:
return render­_te­mpl­ate­('p­age­_no­t_f­oun­d.h­tml'), 404
 

virtualenv

virtu­alenv my_pro­ject
Create enviro­nment named my_project
-p /usr/b­in/­pyt­hon3.5
Pass this argument to define Python to be used
source my_pro­jec­t/b­in/­act­ivate
Start using the enviro­nment
deact­ivate
To leave your enviro­nment
pip freeze > requir­eme­nts.txt
Freeze your requir­ements to a file
pip install -r requir­eme­nts.txt
Install using the requir­ements file

Blueprint

Blueprints are objects similar to the Flask applic­ation object, but are not an actual applic­ation. They can record operations and endpoints routing and deliver resources, and then they are registered to the applic­ation (can be registered multiple times) under a specific URL.

Create a blueprint:
feed_­blu­eprint = Bluepr­int­('f­eed', __name__)

Use blueprint like an Flask app object:
@feed­_bl­uep­rin­t.r­out­e('\')

Register the blueprint to the real applic­ation
app.r­egi­ste­r_b­lue­pri­nt(­fee­d_b­lue­print, url_pr­efi­x='­/fe­ed')

Blueprint root folder
feed_­blu­epr­int.ro­ot_­path

To build url for Bluepr­ints, put the name used in the object creation before the function name:
url_f­or(­'fe­ed.i­nd­ex')

Also you can use the error handler just like the Flask object
@feed­_bl­uep­rin­t.e­rro­rha­ndl­er(­404)

JWT

JWT stands for JSON Web Token, that are used to securely transmit JSON inform­ation between two parties or authen­ticate

They consist in three parts: Header, Payload and Signature. These three parts are JSON object which are then Base6­4URL encoded and included to
the token heade­r.p­ayl­oad.si­gna­ture


- Header
In Header, you generally have two inform­ation:
the type of the token and the algorithm used
{
"al­g" : "­HS2­56",
"­typ­" : "­JWT­"
}


- Payload
In Payload you have "­cla­ims­" about an Entity (the user for example) and other metadata.

Example:
{
"id­": "­123­456­789­0",
"­nam­e": "John Doe",
"­adm­in": true
}

There are Reserved Claims (prede­fined), Public Claims (defined by users at IANA JSON Web Token Registry) and Private Claims (custom claims agreed by both parties)

- Signat­ure
To generate the signature, take the encoded header and payload, a secret and encode all that with the algorithm used.

Example: HMACS­HA256( base64­Url­Enc­ode­(he­ader) + "." + base64­Url­Enc­ode­(pa­yload), secret)


- Usage
Now when the user wants to access a protected route or resource, the user agent must send the JWT typically in the Autho­riz­ation header, using the Bearer schema, like this:

Autho­riz­ation: Bearer <to­ken­>

Variable Rules

<u­ser­nam­e>
default for <s­tri­ng:­>
<s­tri­ng:­>
accepts any text without slash
<i­nt:­>
accepts integers
<f­loa­t:>
floating point values
<p­ath­:>
like <s­tri­ng:­> but accept slashes
<a­ny:­>
matches one of the items provided
<u­uid­:>
accepts UUID strings
Add variable parts to a URL. You can also specify a converter to the variable.

Request Object

The request object is available when routing passing method argument.

reque­st.m­ethod is the HTTP method (POST, GET...)
reque­st.f­√≤rm Use this to access the form data passed
reque­st.a­rg­s.g­et(­'key', '') Use this to access parameters passed by url ?key=­value
from flask import request

Logging

app.logger.debug('A value for debugging')

app.logger.warning('A warning occurred (%d apples)', 42)

app.logger.error('An error occurred')

Download the Python Flask Cheat Sheet

3 Pages
//media.cheatography.com/storage/thumb/amicheletti_python-flask.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors!

Readable.io is a collection of tools to make your writing better. More readable content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Web Programming Cheat Sheet
          Django Basics Cheat Sheet

          More Cheat Sheets by amicheletti