Last active
December 30, 2019 03:53
-
-
Save nZac/6a57c1e584402bdb331e34c302aa64b5 to your computer and use it in GitHub Desktop.
Simple Text Media Handler in 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 falcon | |
import falcon.media | |
import falcon.testing | |
class TextHandler(falcon.media.BaseHandler): | |
def serialize(self, media, content_type): | |
return str(media).encode() | |
def deserialize(self, stream, content_type, content_length): | |
return stream.read().decode() | |
class FooResource(): | |
def on_get(self, req, resp): | |
# Naive content negotiation | |
resp.content_type = req.accept | |
resp.media = {"foo": "bar"} | |
def on_get_simple(self, req, resp): | |
# For simple text/html, you can just set the content_type and body and be done... | |
resp.body = "html" | |
resp.content_type = "text/html" | |
def test_media_type_overriding_attribute(): | |
app = falcon.App() | |
app.add_route('/', FooResource()) | |
app.add_route('/simple', FooResource(), suffix="simple") | |
handlers = falcon.media.Handlers({ | |
'text/html': TextHandler(), | |
'application/json': falcon.media.JSONHandler() | |
}) | |
app.req_options.media_handlers = handlers | |
app.resp_options.media_handlers = handlers | |
client = falcon.testing.TestClient(app) | |
resp = client.simulate_get( | |
"/", | |
headers={'accept': 'application/json'} | |
) | |
assert resp.text == '{"foo": "bar"}' | |
assert resp.headers['content-type'] == 'application/json' | |
resp = client.simulate_get( | |
"/", | |
headers={'accept': 'text/html'} | |
) | |
assert resp.text == "{'foo': 'bar'}" | |
assert resp.headers['content-type'] == 'text/html' | |
resp = client.simulate_get("/simple") | |
assert resp.text == "html" | |
assert resp.headers["content-type"] == "text/html" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment