【问题标题】:How can I set custom headers for error responses from Twisted server?如何为来自 Twisted 服务器的错误响应设置自定义标头?
【发布时间】:2019-01-29 20:40:18
【问题描述】:

特别是,我想为 4xx 和 5xx 添加 CORS 标头,以便我的前端 web 应用程序可以向用户显示错误信息。

在我的应用程序中,我有一个 root 资源,我使用 putChild 添加叶资源。例如:

root = Root()
proxy = Proxy()
root.putChild("".encode('utf-8'), Root())
root.putChild("proxy".encode('utf-8'), proxy)
proxy.putChild("listMonitors".encode('utf-8'), ListMonitors())
proxy.putChild("getMonitorValues".encode('utf-8'), GetMonitorValues())
proxy.putChild("setStartInstrument".encode('utf-8'), SetStartInstrument())
proxy.putChild("setStopInstrument".encode('utf-8'), SetStopInstrument())
proxy.putChild("setPowerOnInstrument".encode('utf-8'), SetPowerOnInstrument())
proxy.putChild("setPowerOffInstrument".encode('utf-8'), SetPowerOffInstrument())

site = server.Site(root)

This 似乎与 Twisted 文档相关,并且可能允许在响应中设置标题,但我不确定如何应用它。我是否需要放弃 putChild 方法,转而让我的 root 资源直接流量到我的所有叶子资源或 noresource 用于 404 错误?其他错误类型呢?

更新:

一位评论者要求了解Root 是什么:

class Root(resource.Resource):
    isLeaf = False

    def render_GET(self, request):

        request.setHeader('Access-Control-Allow-Origin', '*')
        return "arkanoid?".encode()

【问题讨论】:

  • 什么是Root

标签: cors twisted twisted.web


【解决方案1】:

Twisted Web 不提供定义站点范围的错误处理行为的能力。它确实允许您为使用 twisted.web.static.File 提供的基于文件系统的静态内容定义 403 和 404 行为,但这似乎对您的情况没有帮助。

最简单的解决方案可能是使用Klein 来定义您的网络行为。 Klein 确实提供了您感兴趣的那种error customization behavior。由于 Klein 是基于 Twisted 的并且与 Twisted Web 配合得很好,因此您可以根据需要将 Web 应用程序切换到它,继续使用 Twisted其余的网络。您的所有其他 Twisted 工具和库也将继续与它一起工作。

【讨论】:

    猜你喜欢
    • 2015-03-14
    • 2016-01-04
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2016-06-04
    • 2017-09-01
    相关资源
    最近更新 更多