route() decorator is used to bind a function to a URL@app.route('/')methods argument.@app.route('/login', methods=['GET', 'POST'])app = Flask(__name__)api = Api(app)Resources and add them to the APIclass NewsFinder(Resource): passapi.add_resouce(NewsFinder, '/', '/news')def get(self): passdef put(self, id): passparser = reqparse.RequestParser()parse_args(strict=True) to throw an error if arguments that were not defined by you has been passedparser.add_arguments('limit', type=int, help='Help Text', required=True)add_argument('User-Agent', location='headers')args = parser.parse_args() to get the parsed args. This variable args will become a dictionary with the values, ccess via args['limit']from flask_restful import Api, Resource, reqparse
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)
authentication_handler() which takes 2 arguments and a identity_handler() which takes 1 argument'identity' key of the JSON/auth like this:curl -H "Content-type: application/json" -X POST -d '{"username":"amicheletti","password":"coracaopeludo"}' http://127.0.0.1:5000/auth`
url_for() to generate the URL to that function.@app.route('/user/<username>') def profile(username): pass you use url_for('profile', username="Andre") to get the URL for that route. enctype="multipart/form-data"requests.filesf = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt')redirect('url') Pass a URL to this function to redirect a userabort(401) This will abort the request early with an error code@app.errorhandler(404), but don't forget to pass the error code. Example:return render_template('page_not_found.html'), 404
virtualenv my_project |
Create environment named my_project
|
-p /usr/bin/python3.5 |
Pass this argument to define Python to be used
|
source my_project/bin/activate |
Start using the environment
|
deactivate |
To leave your environment
|
pip freeze > requirements.txt |
Freeze your requirements to a file
|
pip install -r requirements.txt |
Install using the requirements file
|
feed_blueprint = Blueprint('feed', __name__)@feed_blueprint.route('\')app.register_blueprint(feed_blueprint, url_prefix='/feed') feed_blueprint.root_pathurl_for('feed.index')@feed_blueprint.errorhandler(404)Base64URL encoded and included toheader.payload.signature{"alg" : "HS256", "typ" : "JWT" }{"id": "1234567890", "name": "John Doe", "admin": true}HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)Authorization: Bearer <token>
<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
|
method argument.request.method is the HTTP method (POST, GET...)request.fòrm Use this to access the form data passedrequest.args.get('key', '') Use this to access parameters passed by url ?key=valuefrom flask import request
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.