响应头名称大写

Falcon选择始终以小写形式呈现WSGI响应头名称;另请参阅: 为什么Falcon要把我的标题名改成小写?

对于符合标准的HTTP客户端来说,这通常不会成为问题,但是可以使用 generic WSGI middleware

class CustomHeadersMiddleware:

    def __init__(self, app, title_case=True, custom_capitalization=None):
        self._app = app
        self._title_case = title_case
        self._capitalization = custom_capitalization or {}

    def __call__(self, environ, start_response):
        def start_response_wrapper(status, response_headers, exc_info=None):
            if self._title_case:
                headers = [
                    (self._capitalization.get(name, name.title()), value)
                    for name, value in response_headers]
            else:
                headers = [
                    (self._capitalization.get(name, name), value)
                    for name, value in response_headers]
            start_response(status, headers, exc_info)

        return self._app(environ, start_response_wrapper)

我们现在可以使用此中间件包装Falcon应用程序:

import falcon

# Import or define CustomHeadersMiddleware from the above snippet...


class FunkyResource:

    def on_get(self, req, resp):
        resp.set_header('X-Funky-Header', 'test')
        resp.media = {'message': 'Hello'}


app = falcon.App()
app.add_route('/test', FunkyResource())

app = CustomHeadersMiddleware(
    app,
    custom_capitalization={'x-funky-header': 'X-FuNkY-HeADeR'},
)

作为一个额外的好处,这个配方也适用于非FalconWSGi应用程序。