Last active
March 12, 2022 18:40
-
-
Save vytas7/7224c6d552c6e01992dfd84c01a40063 to your computer and use it in GitHub Desktop.
text/plain media handler for Falcon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cgi | |
import functools | |
import falcon | |
class TextHandler(falcon.media.BaseHandler): | |
DEFAULT_CHARSET = 'utf-8' | |
@classmethod | |
@functools.lru_cache | |
def _get_charset(cls, content_type): | |
_, params = cgi.parse_header(content_type) | |
return params.get('charset') or cls.DEFAULT_CHARSET | |
def deserialize(self, stream, content_type, content_length): | |
data = stream.read() | |
return data.decode(self._get_charset(content_type)) | |
def serialize(self, media, content_type): | |
return media.encode(self._get_charset(content_type)) | |
class MediaEcho: | |
def on_post(self, req, resp): | |
resp.content_type = req.accept | |
resp.media = req.get_media() | |
app = falcon.App() | |
app.req_options.media_handlers['text/plain'] = TextHandler() | |
app.resp_options.media_handlers['text/plain'] = TextHandler() | |
app.add_route('/media', MediaEcho()) |
I think we could also delegate text
to it?
Not sure in the case you mean resp.text
... Currently, setting resp.text
does not imply any media type, it's fairly common to write
resp.text = json.dumps(data) # Or YAML or CSV or whatever
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The idea proposed by @maxking on Gitter
Example usage: