Python Flask Cheat
Python Flask Cheat
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']
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)
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
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
Variable Rules
Add variable parts to a URL. You can also specify a converter to the
variable.
Request Object