Reputation: 6259
I am working on a REST API that reacts to GET and PUT requests.
Due to a number of reasons, this API will be written in Python and Twisted. That said, twisted web seems to be resource based from all the examples I have found.
That means to my understanding, I have to set up separate resources and define handlers for GET and POST for each.
What I want to do is set up GET and POST handlers that are called whatever resource is requested.
In pseudo code:
import *the appropriate modules*
class Callback(resource.Resource):
def render_GET(self,request):
print "GET!"
def render_POST(self,request):
print "POST!"
def main():
*magic*
reactor.listenTCP(settings.port,factory)
reactor.run()
print "Started callback server on port %d" % settings.port
if __name__ == '__main__':
main()
Unfortunately, my online search for examples has turned up no way to do this.
Any input on how to either set a "catch-all" resource or use different reactor types to handle this are most appreciated.
Upvotes: 2
Views: 3640
Reputation: 48335
This question (and probably others you'll have :) are answered in the Twisted Web in 60 Seconds documentation series.
In particular, you're asking about what is called "dynamic URL dispatch" in Twisted Web. It sounds like you already found the Resource.putChild
API that lets you handle static URL dispatch. With dynamic URL dispatch, you don't have to set up handlers for all URLs you want to handle in advance. Instead, you override getChild
to implement your own logic for creating a resource on demand.
See the dynamic dispatch document for more details, but the gist is:
class Calendar(Resource):
def getChild(self, name, request):
return YearPage(int(name))
This is a resource which handles any integer child by creating a YearPage
resource that knows what that integer was. You should be able to do something similar to create your Callback
resources.
Upvotes: 6