New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question] How can I use ujson as a Flask encoder/decoder? #433
Comments
Please see #374 (comment) and 53f85b1:
|
Does this mean it is impossible to use ujson for Flask in this context, as ujson does not provide a |
Is this maybe the reason why ujson / ultrajson seems not to be in any benchmark of https://www.techempower.com/benchmarks/#section=data-r19&hw=ph&test=json ? |
UltraJSON aims to have a similar API to the stdlib I've not seen those benchmarks before, you'd have to ask TechEmpower :) |
You can. You can also do it with simplejson: >>> from json import JSONEncoder
>>> from simplejson import JSONEncoder
>>> from ujson import JSONEncoder
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'JSONEncoder' from 'ujson' (/home/math/.pyenv/versions/3.8.4/lib/python3.8/site-packages/ujson.cpython-38-x86_64-linux-gnu.so) |
In those cases I don't overwrite the |
Looking at simplejson.encode: Does ujson have something similar to "iterencode"? |
That actually makes no sense, if the behaviour of ujson is trying to serialize all objects in any way, if there's no way at least way to do it should be provided by us... I was moving to ujson because it was serializing datetimes and dates and now all the moving has been suddenly stoped because things like this: No UUID No custom encoder. If it aims to provide a similar API this behavour it's doing just the oposite. I think this makes even more confusion to the users. :( |
Didn't check in details how about pure Flask application, but in my project based on Flask-RESTX, which one could use Shortly smth like that works for me: # how it's done in flask_restx library
try:
from ujson import dumps
except ImportError:
from json import dumps
# just call dumps(...) if you need it anywhere in your code
...
# support specific objects serialization here
import datetime
from uuid import UUID
def json_default(obj):
# convert datetime to ISO string representation
if isinstance(obj, datetime.datetime):
return obj.isoformat()
# convert UUID to string
if isinstance(obj, UUID):
return str(obj)
return obj
# just supply your custom object conversion function as a fallback
# to dumps whether it is from standard `json` library or `ujson`
# for Flask-RESTX it is done through configuration
flask_app.config["RESTX_JSON"] = {"default": json_default} |
See Stack Overflow
What did you do?
What did you expect to happen?
When visiting the the page, I expected a dict with a UUID-string
What actually happened?
What versions are you using?
The text was updated successfully, but these errors were encountered: