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

docs(recipes): add text/plain media handler recipe #2419

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions examples/recipes/plain_text_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cgi has been removed from CPython 3.13+. You can use our own replacement: falcon.parse_header().

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))
25 changes: 25 additions & 0 deletions tests/test_recipes.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,28 @@ def test_raw_path(self, asgi, app_kind, util):
)
assert result2.status_code == 200
assert result2.json == {'cached': True}


class TestTextPlainHandler:
class MediaEcho:
def on_post(self, req, resp):
resp.content_type = req.content_type
resp.media = req.get_media()

def test_text_plain_basic(self, util):
recipe = util.load_module('examples/recipes/plain_text_main.py')

app = falcon.App()
app.req_options.media_handlers['text/plain'] = recipe.TextHandler()
app.resp_options.media_handlers['text/plain'] = recipe.TextHandler()

app.add_route('/media', self.MediaEcho())

client = falcon.testing.TestClient(app)
payload = 'Hello, Falcon!'
headers = {'Content-Type': 'text/plain'}
response = client.simulate_post('/media', body=payload, headers=headers)

assert response.status_code == 200
assert response.content_type == 'text/plain'
assert response.text == payload