anekix
anekix

Reputation: 2563

Twisted making a function non-blocking

I am using twisted for making an async webserver (to learn the idea behind even based asynchronous programming). consider this scenario , server when gets a GET request on some endpoint, ex http:localhost:8000/api/v1/calc_fact?num=1000 calculates the factorial of 1000 and return back the result. this part is easy to get. I am also aware of deferred API. how can i define my function calc_factorial() so that it return a deferred and the overall result is non-blocking.

How do I solve the problem?

Upvotes: 0

Views: 348

Answers (1)

lapinkoira
lapinkoira

Reputation: 9008

I have done something similar.

In your resource you need to return a server.NOT_DONE_YET and add the calc_factorial deferred callback like this

def render_GET(self, request):
    d = Deferred()
    reactor.callLater(1, d.callback, None)
    d.addCallback(self.calc_factorial, request)
    d.addErrback(rror_handler, request)
    return server.NOT_DONE_YET

Then inside the calc_factorial you write into the request:

def calc_factorial(self, request):
    # something something
    request.write("factorial calc done")
    request.finish()

Once you write request finish it will trigger the NOT_DONE_YET

Upvotes: 1

Related Questions