Python Flask Cheat Sheet
by amicheletti via cheatography.com/39488/cs/12263/
Routing Flask_jwt
route() decorator is used to bind a function to a URL from flask import Flask
Example: from flask_restful import Api, Resource
@app.route('/') from flask_jwt import JWT, jwt_required,
By default a route only answers to GET requests, but you can provide the current_identity
methods argument.
app = Flask(__name__)
@app.route('/login', methods=['GET', 'POST'])
app.config['SECRET_KEY'] = 'my-secret'
api = Api(app, prefix='/api/v1')
flask-restful
USER_DATA = {
With Flask-Restful you can create RESTful API with your Flask app "amicheletti": "coracaopeludo"
Create an Flask App }
app = Flask(__name__) class User(object):
Then create the Api object passing the App object def __init__(self, id):
api = Api(app)
self.id = id
Then you can create Resources and add them to the API
def __str__(self):
class NewsFinder(Resource): pass
return "User (id={})".format(self.id)
api.add_resouce(NewsFinder, '/', '/news')
def verify(username, password):
You can implement each HTTP verb with functions named like the verb,
if not (username and password):
but in lowercase.
return False
Example:
if (USER_DATA.get(username) == password):
def get(self): pass
def put(self, id): pass return User(id=123)
def identity(payload):
To parse arguments passed by the url use
parser = reqparse.RequestParser() user_id = payload['identity']
You can pass parse_args(strict=True) to throw an error if return { "uid": user_id }
arguments that were not defined by you has been passed jwt = JWT(app, verify, identity)
Add the arguments with parser.add_arguments('limit', class UltimateQuestion(Resource):
type=int, help='Help Text', required=True) @jwt_required()
You can specify the location to look for this argument with def get(self):
add_argument('User-Agent', location='headers') return { "meaningoflife" : 42, "who_asked" :
Example locations: form, args, headers, session, cookies, files dict(current_identity) }
Then inside the function you can args = parser.parse_args() to api.add_resource(UltimateQuestion, '/', '/life')
get the parsed args. This variable args will become a dictionary with the
if __name__ == "__main__":
values, ccess via args['limit']
app.run(debug=True)
Imports You must have an authentication_handler()which takes 2
from flask_restful import Api, Resource, reqparse
arguments and a identity_handler() which takes 1 argument
Authentication handler must return an Object that has an id attribute
Identity handler return what is going to be send to 'identity' key of
the JSON
To get the token, curl POST to the /auth like this:
curl -H "Content-type: application/json" -X POST -d
'{"username":"amicheletti","password":"coracaopeludo"}
' http://127.0.0.1:5000/auth`
By amicheletti Published 11th July, 2017. Sponsored by CrosswordCheats.com
cheatography.com/amicheletti/ Last updated 18th July, 2017. Learn to solve cryptic crosswords!
Page 1 of 3. http://crosswordcheats.com
Python Flask Cheat Sheet
by amicheletti via cheatography.com/39488/cs/12263/
URL Building Blueprint
When routing some function to a URL, you can use function url_for() Blueprints are objects similar to the Flask application object, but are not an
to generate the URL to that function. actual application. They can record operations and endpoints routing and
Example, if you have something like deliver resources, and then they are registered to the application (can be
@app.route('/user/<username>') def profile(username): registered multiple times) under a specific URL.
Create a blueprint:
pass you use url_for('profile', username="Andre") to get the
feed_blueprint = Blueprint('feed', __name__)
URL for that route.
Use blueprint like an Flask app object:
That way you can avoid having to change the hardcoded URL everywhere
@feed_blueprint.route('\')
in the code.
Register the blueprint to the real application
app.register_blueprint(feed_blueprint,
File Uploads
url_prefix='/feed')
To handle file uploads with Flask, the HTML form must be set with
Blueprint root folder
enctype="multipart/form-data"
feed_blueprint.root_path
Then you can use it from a dictionary inrequests.files
To build url for Blueprints, put the name used in the object creation before
Example: the function name:
f = request.files['the_file'] url_for('feed.index')
f.save('/var/www/uploads/uploaded_file.txt')
Also you can use the error handler just like the Flask object
@feed_blueprint.errorhandler(404)
Redirects and Errors
redirect('url') Pass a URL to this function to redirect a user JWT
abort(401) This will abort the request early with an error code JWT stands for JSON Web Token, that are used to securely transmit
To customize the error page use @app.errorhandler(404), but don't JSON information between two parties or authenticate
forget to pass the error code. Example: They consist in three parts: Header, Payload and Signature. These three
return render_template('page_not_found.html'), 404 parts are JSON object which are then Base64URL encoded and
included to
virtualenv the token header.payload.signature
- Header
virtualenv my_project Create environment named
In Header, you generally have two information:
my_project
the type of the token and the algorithm used
-p /usr/bin/python3.5 Pass this argument to define Python {
to be used "alg" : "HS256",
source Start using the environment "typ" : "JWT"
my_project/bin/activate }
deactivate To leave your environment - Payload
In Payload you have "claims" about an Entity (the user for example) and
pip freeze > Freeze your requirements to a file
other metadata.
requirements.txt Example:
pip install -r Install using the requirements file {
requirements.txt "id": "1234567890",
"name": "John Doe",
By amicheletti Published 11th July, 2017. Sponsored by CrosswordCheats.com
cheatography.com/amicheletti/ Last updated 18th July, 2017. Learn to solve cryptic crosswords!
Page 2 of 3. http://crosswordcheats.com
Python Flask Cheat Sheet
by amicheletti via cheatography.com/39488/cs/12263/
JWT (cont) Logging
"admin": true app.logger.debug('A value for debugging')
} app.logger.warning('A warning occurred (%d apples)',
There are Reserved Claims (predefined), Public Claims (defined by users 42)
at IANA JSON Web Token Registry) and Private Claims (custom claims app.logger.error('An error occurred')
agreed by both parties)
- Signature
To generate the signature, take the encoded header and payload, a secret
and encode all that with the algorithm used.
Example: HMACSHA256( base64UrlEncode(header) + "." +
base64UrlEncode(payload), secret)
- Usage
Now when the user wants to access a protected route or resource, the
user agent must send the JWT typically in the Authorization header, using
the Bearer schema, like this:
Authorization: Bearer <token>
Variable Rules
<username> default for <string:>
<string:> accepts any text without slash
<int:> accepts integers
<float:> floating point values
<path:> like <string:> but accept slashes
<any:> matches one of the items provided
<uuid:> 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.
request.method is the HTTP method (POST, GET...)
request.fòrm Use this to access the form data passed
request.args.get('key', '') Use this to access parameters
passed by url ?key=value
from flask import request
By amicheletti Published 11th July, 2017. Sponsored by CrosswordCheats.com
cheatography.com/amicheletti/ Last updated 18th July, 2017. Learn to solve cryptic crosswords!
Page 3 of 3. http://crosswordcheats.com