-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflask_minijson.py
35 lines (28 loc) · 1.1 KB
/
flask_minijson.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import typing as tp
import minijson
from flask import Flask
from flask_json import JsonRequest
class MiniJSONRequest(JsonRequest):
def get_json(self, force=False, silent=False, cache=True):
"""
Return JSON data, if content type is application/minijson it will be loaded
via minijson, else it will be loaded the normal way.
"""
if self.headers.get('Content-Type') == 'application/minijson':
return minijson.loads(self.get_data())
else:
return super().get_json(force, silent, cache)
class FlaskMiniJSON(object):
"""Flask-MiniJSON extension class."""
def __init__(self, app: tp.Optional[Flask] = None):
self._app = app
self._error_handler_func = None
self._decoder_error_func = None
if app is not None:
self.init_app(app)
def init_app(self, app: Flask):
if 'json' not in app.extensions:
raise RuntimeError('flask-json must be initialized before MiniJSON!')
app.extensions['minijson'] = self
self._app = app
app.request_class = MiniJSONRequest