marshmallow-code / marshmallow-code/flask-smorest
Make serializing to multiple content-type easier
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 717
- Forks
- 77
- Avg merge
- 7h 49m
- Merged PRs (30d)
- 3
Description
All my endpoint support serializing to JSON and CBOR. It is done by overriding the _prepare_response_content like that:
def _prepare_response_content(data):
""" Serialize to JSON or CBOR"""
response_mimetype = request.accept_mimetypes.best_match(
[ MT_JSON, MT_CBOR ],
default=MT_JSON
)
if response_mimetype == MT_JSON:
content = json.dumps(data)
headers = {"Content-Type" : "application/json" }
if response_mimetype == MT_CBOR:
content = cbor2.dumps(data)
print(content.hex())
headers = {"Content-Type" : "application/cbor" }
return (content,headers )
It should work except that the function is inside a call to flask.jsonify() wich doesn't allow for anything but json serailization. So I have to override the entire response function to rewrite just that one line.
https://github.com/marshmallow-code/flask-smorest/blob/5ac7296f98e9829059c4a7835c1ca2ffc1fdbdf8/flask_smorest/response.py#L110-L111
If we replace flask.jsonify()by flask.make_response() it allow for much greater customization, including setting custom headers. That would break the default serialization but that can be fix by doing the equivalent of jsonify inside of _prepare_response_content:
def _prepare_response_content(data):
content = json.dumps(data)
headers = {"Content-Type" : "application/json" }
return (content,headers )
I think this is a small modificatrion that would really make supporting multiple content-type much easier.
Is there any other impact that I have not forseen ? If this modification is acceptable I can do the merge request / documentation.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in flask_smorest/response.py at the referenced lines where flask.jsonify() is used. Check how replacing it with flask.make_response() would affect the existing JSON response behavior and custom headers, then verify that the default serialization remains intact; the issue does not name a test file.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- flask, python
- Domain
- api
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100