Created
August 27, 2015 18:44
-
-
Save masom/a6ad4b731ba819dc6443 to your computer and use it in GitHub Desktop.
net/http style middlewares for Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from flask import Blueprint, request | |
from .middlewares import (m, validate) | |
posts = Blueprint('posts', __name__, url_prefix='/posts') | |
def index(): | |
posts = dict() | |
return dict(posts=posts) | |
def view(id): | |
post = dict() | |
if not post: | |
return dict(), 404 | |
return dict(post=post) | |
def create(): | |
post = Post() | |
post.title = request.data.title | |
# here be save operation | |
return dict(post=post), 201 | |
posts.add_url_rule( | |
'', 'index', m(index), methods=['GET'] | |
) | |
posts.add_url_rule( | |
'', 'create', | |
m(validate('posts_create'), create), | |
methods=['POST'] | |
) | |
posts.add_url_rule( | |
'/<int:id>', 'view', | |
m(view), | |
methods=['GET'] | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import jsonschema | |
from flask import jsonify, request, current_app | |
def validate(name): | |
"""Validate the request data with the given JSON schema name | |
:param name: Name of the json schema | |
:type name: string | |
""" | |
def wrapped(*args, **kwargs): | |
schema = current_app.extensions['jsonschema'].get_schema(name) | |
try: | |
jsonschema.validate(request.json, schema) | |
except jsonschema.ValidationError as e: | |
log.info("schema validation error", error=e) | |
# TODO let the Flask error handler pickup this error. | |
return {}, 422 | |
return wrapped | |
def handle_response(rv): | |
"""Handle rending the proper response | |
:param rv: The return value from a view / middleware. Can be a tuple. | |
""" | |
# Determine the best response type from the request. | |
# Will be used to port response to JSONAPI | |
best = request.accept_mimetypes.best_match([ | |
'application/json', 'application/vnd.json+api' | |
]) | |
if best == 'application/json': | |
if isinstance(rv, tuple): | |
rv, rc = rv | |
return jsonify(rv), rc | |
if isinstance(rv, dict): | |
return jsonify(rv) | |
else: | |
return jsonify({}), 406 | |
def m(*mw): | |
'''m defines a list of route middlewares that will be applied in order. | |
''' | |
def wrapped(*args, **kwargs): | |
for item in mw: | |
rv = item(*args, **kwargs) | |
if rv: | |
return handle_response(rv) | |
return wrapped |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment