Created
August 26, 2016 07:21
-
-
Save wisedier/d400b295a2d5aafa754112031bcaf7ec to your computer and use it in GitHub Desktop.
Check json request in 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 functools import wraps | |
from flask import abort, request | |
def is_json_request(): | |
""" | |
Returns True if the request is json request else False. | |
For example:: | |
@blueprint.get('/posts') | |
def post_list_view(): | |
if not is_json_request(): | |
return abort(400) | |
pass | |
:rtype: bool | |
""" | |
best = request.accept_mimetypes.best_match(['application/json', 'text/html']) | |
return best == 'application/json' and \ | |
request.accept_mimetypes[best] > request.accept_mimetypes['text/html'] | |
def accept_json_request(func): | |
""" | |
If you decorate a view with this, it will ensure that the request is json request. | |
For example:: | |
@blueprint.get('/posts') | |
@accept_json_request | |
def post_list_view(): | |
pass | |
:param func: The view function to decorate | |
:type func: function | |
""" | |
@wraps(func) | |
def decorated_view(*args, **kwargs): | |
if not is_json_request(): | |
return abort(400) | |
return func(*args, **kwargs) | |
return decorated_view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment