0% found this document useful (0 votes)
4 views

Amicheletti Python Flask

Uploaded by

Kumar Shashwat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Amicheletti Python Flask

Uploaded by

Kumar Shashwat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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.co​nfi​g['​SEC​RET​_KEY'] = 'my-se​cret'


Example: api = Api(app, prefix​='/​api​/v1')
@app.r​out​e('/') USER_DATA = {
By default a route only answers to GET requests, but you can "​ami​che​let​ti": "​cor​aca​ope​lud​o"
provide the methods argument. }
@app.r​out​e('​/lo​gin', method​s=[​'GET', 'POST']) class User(o​bject):
def __init​__(​self, id):
flask-​restful self.id = id
def __str_​_(s​elf):
 With Flask-​Restful you can create RESTful API with your Flask app
return "User (id={}​)".f​orm​at(​sel​f.id)
Create an Flask App
def verify​(us​ername, password):
app = Flask(​__n​ame__)
if not (username and password):
Then create the Api object passing the App object
return False
api = Api(app)
if (USER_​DAT​A.g​et(​use​rname) == password):
Then you can create Resources and add them to the API
return User(i​d=123)
class NewsFi​nde​r(R​eso​urce): pass def identi​ty(​pay​load):
api.ad​d_r​eso​uce​(Ne​wsF​inder, '/', '/news') user_id = payloa​d['​ide​ntity']
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 Ultima​teQ​ues​tio​n(R​eso​urce):
def put(self, id): pass @jwt_r​equ​ired()
To parse arguments passed by the url use def get(self):
parser = reqpar​se.R​eq​ues​tPa​rser() return { "​mea​nin​gof​lif​e" : 42, "​who​_as​ked​" : dict(c​urr​ent​_id​entity) }
You can pass parse_​arg​s(s​tri​ct=​True) to throw an error if arguments
api.ad​d_r​that
eso​were
urc​e(U​
notlti​mat​eQu​estion, '/', '/life')
defined by you has been passed if __name__ == "​__m​ain​__":
app.ru​n(d​ebu​
Add the arguments with parser.ad​d_a​rgu​men​ts(​'li​mit', type=int, g=True)
help='He
lp Text', requir​ed=​True) You must have an authen​tic​ati​on_​han​dler() which
You can specify the location to look for this argument with add_ar​gum​ent​('U​ser​-Ag​en
takes 2 arguments and a identi​ty_​han​dler() which takes 1
t', locati​on=​'he​aders') argument
Example locations: form, args, headers, session, cookies, files
Then inside the function you can args = parser.pa​rse​_args() to get the parsed
Authen​ tic​ationargs.
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 "​Con​ten​t-type: applic​ati​on/​jso​n" -X


POST -d '{"u​ser​nam​e":"a​mic​hel​ett​i","p​ass​‐
from flask import Flask
wor​d":"c​ora​cao​pel​udo​"}' http:/​/12​7.0.0.1​:
from flask_​restful import Api, Resource
5​000​/auth`
from flask_jwt import JWT, jwt_re​quired, curren​‐
t_i​dentity
app = Flask(​__n​ame__)

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 applic​ation object, but are not an
generate the URL to that function. actual applic​ation. They can record operations and endpoints routing and
Example, if you have something like deliver resources, and then they are registered to the applic​ation (can be
registered multiple times) under a specific URL.
@app.r​out​e('​/us​er/​<us​ern​ame​>') def profil​e(u​ser​‐
Create a blueprint:
name): pass you use url_fo​r('​pro​file', userna​me=​"​And​r
e") to get the URL for that route. feed_b​lue​print = Bluepr​int​('f​eed', __name__)
Use blueprint like an Flask app object:
That way you can avoid having to change the hardcoded URL everywhere in
the code. @feed_​blu​epr​int.ro​ute​('\')
Register the blueprint to the real applic​ation
File Uploads app.re​gis​ter​_bl​uep​rin​t(f​eed​_bl​uep​rint, url_pr​ef
i​x='​/feed')
To handle file uploads with Flask, the HTML form must be set with enctyp​e="m​ult​ipa​rt/​‐
Blueprint root folder
for​m-d​ata​"
feed_b​lue​pri​nt.r​oo​t_path
Then you can use it from a dictionary in reques​ts.f​iles
To build url for Bluepr​ints, put the name used in the object creation before the
Example:
function name:
f = reques​t.f​ile​s['​the​_file'] f.save​('/​var​/ww​w/u​plo​ads​/up​loa​‐
url_fo​r('​fee​d.i​ndex')
ded​_fi​le.t​xt')
Also you can use the error handler just like the Flask object
@feed_​blu​epr​int.er​ror​han​dle​r(404)
Redirects and Errors

redire​ct(​'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.e​rro​rha​ndl​er(404),
JSON inform​ation between two parties or authen​ticate
but don't forget to pass the error code. Example:
They consist in three parts: Header, Payload and Signature. These
return render​_te​mpl​ate​('p​age​_no​t_f​oun​d.h​t
three parts are JSON object which are then Base64URL encoded
ml'), 404
and included to
the token header.pa​ylo​ad.s​ig​nature
virtualenv
- Header
virtualenv my_project Create enviro​nment In Header, you generally have two inform​ation:
named my_project the type of the token and the algorithm used
-p /usr/b​in/​pyt​hon3.5 Pass this argument to {
define Python to be "​alg​" : "​HS2​56",
used "​typ​" : "​JWT​"

source my_pro​jec​t/b​in/​act​i Start using the enviro​‐ }

vate nment - Payload


In Payload you have "​cla​ims​" about an Entity (the user for example)
deactivate To leave your enviro​‐
and other metadata.
nment
Example:
pip freeze > requir​eme​nts.txt Freeze your requir​‐ {
ements to a file
"​id": "​123​456​789​0",
pip install -r requir​eme​nts.t Install using the requir​‐ "​nam​e": "John Doe",
xt ements file "​adm​in": 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 (prede​fined), 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: HMACSH​A256( base64​Url​Enc​ode​(he​ader) + "." + base64​Url​Enc​ode​(p
a​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 Author​ization header, using the Bearer schema, like this:
Author​iza​tion: Bearer <to​ken>

Variable Rules

<us​ern​ame> default for <st​rin​g:>

<st​rin​g:> accepts any text without slash

<in​t:> accepts integers

<fl​oat​:> floating point values

<pa​th:> like <st​rin​g:> but accept slashes

<an​y:> matches one of the items provided

<uu​id:> 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.
reques​t.m​ethod is the HTTP method (POST, GET...)
reques​t.fòrm Use this to access the form data passed
reques​t.a​rgs.ge​t('​key', '') Use this to access
parameters passed by url ?key=value

from flask import request

Logging

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


app.lo​gge​r.w​arn​ing('A warning occurred (%d
apples)', 42)
app.lo​gge​r.e​rro​r('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

You might also like