如何为来自 Twisted 服务器的错误响应设置自定义标头?

问题描述 投票:0回答:2

特别是,我想为 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
资源将流量定向到我的所有叶资源,或者针对 404 错误使用
noresource
?其他错误类型呢?

更新:

评论者请求了解

Root
是什么:

class Root(resource.Resource):
    isLeaf = False

    def render_GET(self, request):

        request.setHeader('Access-Control-Allow-Origin', '*')
        return "arkanoid?".encode()
cors twisted twisted.web
2个回答
0
投票

Twisted Web 不提供定义站点范围的错误处理行为的能力。 它确实允许您使用

twisted.web.static.File
为基于文件系统的静态内容定义 403 和 404 行为,但这似乎对您的情况没有帮助。

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


0
投票

在底层,请求最初由

Resource
render
方法处理。因此,覆盖
render
是为任何子资源自定义标题的好方法:

from twisted.web.resource import Resource

class ResourceWithMyHeaders(Resource):
    def render(self, request):
        # add a custom header
        request.setHeader("HeaderName", "HeaderValue")
        return super().render(request)

现在您可以使用此类创建一个具有所需标头的子类

Root

class Root(ResourceWithMyHeaders):
    isLeaf = False

    def render_GET(self, request):
        # all headers already here
        print(request.responseHeaders)
        ...
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.