0

In particular, I want to add CORS headers for 4xx and 5xx so my frontend webapp can display error info to the user.

In my application I have a root resource and I use putChild to add leaf resources. E.g.:

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 seems relevant from the Twisted documentation and might allow to set headers in the response, but I'm not sure how to apply it. Do I need to abandon the putChild method, and instead move to having my root resource direct traffic to all my leaf resources or a noresource for a 404 error? What about other error types?

UPDATE:

A commenter requested info on what Root is:

class Root(resource.Resource):
    isLeaf = False

    def render_GET(self, request):

        request.setHeader('Access-Control-Allow-Origin', '*')
        return "arkanoid?".encode()
ankuranurag2
  • 2,300
  • 15
  • 30
davegravy
  • 888
  • 11
  • 28

1 Answers1

0

Twisted Web doesn't offer the ability to define site-wide error handling behavior. It does let you define the 403 and 404 behavior for static, filesystem-based content served using twisted.web.static.File but this doesn't seem to help in your situation.

The easiest solution is probably to use Klein to define your web behavior. Klein does provide the kind of error customization behavior you're interested in. Since Klein is Twisted-based and works well with Twisted Web, you can switch as much or as little of your web application to it as you like will continuing to use Twisted Web for the rest. All of your other Twisted tools and libraries will also continue to work alongside it.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122