Skip to content

Instantly share code, notes, and snippets.

@wisedier
Created August 26, 2016 07:21
Show Gist options
  • Save wisedier/d400b295a2d5aafa754112031bcaf7ec to your computer and use it in GitHub Desktop.
Save wisedier/d400b295a2d5aafa754112031bcaf7ec to your computer and use it in GitHub Desktop.
Check json request in Flask
# -*- 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