Pylons / pyramid

Pyramid - A Python web framework
https://trypyramid.com/
Other
3.98k stars 887 forks source link

Support directly returning bytes from a view #3568

Closed wosc closed 4 years ago

wosc commented 4 years ago

For example, when serializing XML, I might already have bytes (and furthermore, lxml.etree.tostring(doc, encoding='unicode', xml_declaration=True) (rightly) refuses to generate an XML declaration, so I'd have to tack that on manually, just to keep everything in text land).

I'm currently declaring support for this explicitly in my application like so,

def bytes_renderer_factory(info):
    def _render(value, system):
        if not isinstance(value, bytes):
            value = value.encode('utf-8')
        return value
    return _render

config.add_renderer('bytes', bytes_renderer_factory)

which of course works just fine. But I think it would make sense for Pyramid to support this out of the box. Or am I missing something here?

luhn commented 4 years ago

I'm not sure how broadly useful that would be. In your example, I wouldn't use a generic "bytes" renderer because I'd want the Content-Type to be text/xml.

mmerickel commented 4 years ago

I agree that returning bytes is not enough. We'd have to define a default content type like application/octet-stream, etc. It's really best to do this with your own adapter because I don't see how we'd apply it generally to everyone at the framework level.

In general if I were ever doing this, my app would be doing return Response(...) from within the view itself because it seems unlikely you'd want to use this pattern across too many views.

wosc commented 4 years ago

OK fair enough. Thanks!