Skip to content

Instantly share code, notes, and snippets.

@vytas7
Last active March 12, 2022 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

The idea proposed by @maxking on Gitter

Example usage:

$ echo -e 'Hello, World!\n(A µprototype)' | http POST http://localhost:8000/media 'Accept:text/plain; charset=ISO-8859-1' Content-Type:text/plain
HTTP/1.1 200 OK
Connection: close
Date: Sat, 12 Mar 2022 10:55:52 GMT
Server: gunicorn
content-length: 29
content-type: text/plain; charset=ISO-8859-1

Hello, World!
(A µprototype)

@CaselIT
Copy link

CaselIT commented Mar 12, 2022

I think we could also delegate text to it?

@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