Skip to content

Instantly share code, notes, and snippets.

@vytas7
Last active March 12, 2022 18:40
Show Gist options
  • Save vytas7/7224c6d552c6e01992dfd84c01a40063 to your computer and use it in GitHub Desktop.
Save vytas7/7224c6d552c6e01992dfd84c01a40063 to your computer and use it in GitHub Desktop.
text/plain media handler for Falcon
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())
@vytas7
Copy link
Author

vytas7 commented Mar 12, 2022

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