Python Flask Cheat Sheet
by amicheletti via cheatography.com/39488/cs/12263/
Routing Flask_jwt (cont)
route() decorator is used to bind a function to a URL > app.config['SECRET_KEY'] = 'my-secret'
Example: api = Api(app, prefix='/api/v1')
@app.route('/') USER_DATA = {
By default a route only answers to GET requests, but you can "amicheletti": "coracaopeludo"
provide the methods argument. }
@app.route('/login', methods=['GET', 'POST']) class User(object):
def __init__(self, id):
flask-restful self.id = id
def __str__(self):
With Flask-Restful you can create RESTful API with your Flask app
return "User (id={})".format(self.id)
Create an Flask App
def verify(username, password):
app = Flask(__name__)
if not (username and password):
Then create the Api object passing the App object
return False
api = Api(app)
if (USER_DATA.get(username) == password):
Then you can create Resources and add them to the API
return User(id=123)
class NewsFinder(Resource): pass def identity(payload):
api.add_resouce(NewsFinder, '/', '/news') user_id = payload['identity']
You can implement each HTTP verb with functions named like the verb, butreturn
in lowercase.
{ "uid": user_id }
Example: jwt = JWT(app, verify, identity)
def get(self): pass class UltimateQuestion(Resource):
def put(self, id): pass @jwt_required()
To parse arguments passed by the url use def get(self):
parser = reqparse.RequestParser() return { "meaningoflife" : 42, "who_asked" : dict(current_identity) }
You can pass parse_args(strict=True) to throw an error if arguments
api.add_rthat
esowere
urce(U
notltimateQuestion, '/', '/life')
defined by you has been passed if __name__ == "__main__":
app.run(debu
Add the arguments with parser.add_arguments('limit', type=int, g=True)
help='He
lp Text', required=True) You must have an authentication_handler() which
You can specify the location to look for this argument with add_argument('User-Agen
takes 2 arguments and a identity_handler() which takes 1
t', location='headers') argument
Example locations: form, args, headers, session, cookies, files
Then inside the function you can args = parser.parse_args() to get the parsed
Authen ticationargs.
handler must return an Object that has an id attribute
This variable args will become a dictionary with the values, ccess via args['limit']
Identity handler return what is going to be send to 'identity' key
Imports of the JSON
from flask_restful import Api, Resource, reqparse
To get the token, curl POST to the /auth like this:
Flask_jwt curl -H "Content-type: application/json" -X
POST -d '{"username":"amicheletti","pass‐
from flask import Flask
word":"coracaopeludo"}' http://127.0.0.1:
from flask_restful import Api, Resource
5000/auth`
from flask_jwt import JWT, jwt_required, curren‐
t_identity
app = Flask(__name__)
By amicheletti Published 11th July, 2017. Sponsored by Readable.com
cheatography.com/amicheletti/ Last updated 18th July, 2017. Measure your website readability!
Page 1 of 3. https://readable.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() to Blueprints are objects similar to the Flask application object, but are not an
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
registered multiple times) under a specific URL.
@app.route('/user/<username>') def profile(user‐
Create a blueprint:
name): pass you use url_for('profile', username="Andr
e") to get the URL for that route. feed_blueprint = Blueprint('feed', __name__)
Use blueprint like an Flask app object:
That way you can avoid having to change the hardcoded URL everywhere in
the code. @feed_blueprint.route('\')
Register the blueprint to the real application
File Uploads app.register_blueprint(feed_blueprint, url_pref
ix='/feed')
To handle file uploads with Flask, the HTML form must be set with enctype="multipart/‐
Blueprint root folder
form-data"
feed_blueprint.root_path
Then you can use it from a dictionary in requests.files
To build url for Blueprints, put the name used in the object creation before the
Example:
function name:
f = request.files['the_file'] f.save('/var/www/uploads/uploa‐
url_for('feed.index')
ded_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),
JSON information between two parties or authenticate
but don't forget to pass the error code. Example:
They consist in three parts: Header, Payload and Signature. These
return render_template('page_not_found.ht
three parts are JSON object which are then Base64URL encoded
ml'), 404
and included to
the token header.payload.signature
virtualenv
- Header
virtualenv my_project Create environment In Header, you generally have two information:
named my_project the type of the token and the algorithm used
-p /usr/bin/python3.5 Pass this argument to {
define Python to be "alg" : "HS256",
used "typ" : "JWT"
source my_project/bin/acti Start using the enviro‐ }
vate nment - Payload
In Payload you have "claims" about an Entity (the user for example)
deactivate To leave your enviro‐
and other metadata.
nment
Example:
pip freeze > requirements.txt Freeze your requir‐ {
ements to a file
"id": "1234567890",
pip install -r requirements.t Install using the requir‐ "name": "John Doe",
xt ements file "admin": true
By amicheletti Published 11th July, 2017. Sponsored by Readable.com
cheatography.com/amicheletti/ Last updated 18th July, 2017. Measure your website readability!
Page 2 of 3. https://readable.com
Python Flask Cheat Sheet
by amicheletti via cheatography.com/39488/cs/12263/
JWT (cont)
}
There are Reserved Claims (predefined), Public Claims (defined by users at IANA JSON Web Token
Registry) and Private Claims (custom claims 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(p
ayload), 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
Logging
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d
apples)', 42)
app.logger.error('An error occurred')
By amicheletti Published 11th July, 2017. Sponsored by Readable.com
cheatography.com/amicheletti/ Last updated 18th July, 2017. Measure your website readability!
Page 3 of 3. https://readable.com