Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: orjson instead of json module for decoding

I'm using flask and have a lot of requests. The json module, which is used by flask, is quite slow. I automatically can use simplejson, but thats a bit slower, not faster. According to the documentation I can define a decoder (flask.json_decoder), but orjson doesn't have this class. I only have the function loads and dumps. Can somebody explain me, how I can exchange the json module with orjson? In the end I just want to use the loads and dumps function, but I can't connect my loose ends.

like image 258
Stefan Berger Avatar asked Feb 19 '20 08:02

Stefan Berger


1 Answers

a very basic implementation could look like this:

class ORJSONDecoder:

    def __init__(self, **kwargs):
        # eventually take into consideration when deserializing
        self.options = kwargs

    def decode(self, obj):
        return orjson.loads(obj)


class ORJSONEncoder:

    def __init__(self, **kwargs):
        # eventually take into consideration when serializing
        self.options = kwargs

    def encode(self, obj):
        # decode back to str, as orjson returns bytes
        return orjson.dumps(obj).decode('utf-8')


app = Flask(__name__)
app.json_encoder = ORJSONEncoder
app.json_decoder = ORJSONDecoder
like image 156
yedpodtrzitko Avatar answered Oct 13 '22 11:10

yedpodtrzitko