Skip to content
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

Make serializing to multiple content-type easier #424

Open
TheBigRoomXXL opened this issue Nov 29, 2022 · 0 comments
Open

Make serializing to multiple content-type easier #424

TheBigRoomXXL opened this issue Nov 29, 2022 · 0 comments

Comments

@TheBigRoomXXL
Copy link

TheBigRoomXXL commented Nov 29, 2022

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.

# Build response
resp = jsonify(self._prepare_response_content(result_dump))

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants