With tornado, it is generally used to fetch the asynchttpclient. We can refer to fetch, use the Tornado feature, write the asynchronous callback program
First look at the implementation of fetch, the key is to use the future
defFetch (self, request, callback=none, * *Kwargs):"""executes a request, asynchronously returning an ' HttpResponse '. The request is either a string URL or an ' HttpRequest ' object. If It is a string, we construct an ' HttpRequest ' using any additional Kwargs: ' HttpRequest (Request, **kwargs) ' This method returns a '. The future ' whose result was an ' httpresponse '. The "Future" wil raise an ' httperror ' if the request returned a NON-200 response code. If a ' callback ' is given, it'll be invoked with the ' HttpResponse '. In the callback interface, ' Httperror ' are not automatically raised. Instead, you must check the response's ' error ' attribute or call its ' ~httpresponse.rethrow ' method. """ if notisinstance (Request, HttpRequest): Request= HttpRequest (url=request, * *Kwargs)#We may modify this (to add Host, accept-encoding, etc), #So make sure we don ' t modify the caller ' s object. This is also #where normal dicts get converted to httpheaders objects.Request.headers =Httputil. Httpheaders (request.headers) Request=_requestproxy (Request, self.defaults) future=tracebackfuture ()ifCallback is notNone:callback=Stack_context.wrap (callback)defhandle_future (future): Exc=future.exception ()ifIsinstance (exc, Httperror) andExc.response is notNone:response=Exc.responseelifExc is notNone:response=HttpResponse (Request,599, error=exc, Request_time=time.time ()-request.start_time)Else: Response=Future.result () Self.io_loop.add_callback (callback, response) Future.add_done_callback (hand Le_future)defHandle_response (response):ifresponse.error:future.set_exception (response.error)Else: Future.set_result (response) Self.fetch_impl (request, Handle_response)returnFuture
So, as long as we use the future, we can also write asynchronous code
def Test (Callback=none): Future =< Span style= "color: #000000;" > Tracebackfuture () if callback is not None:callback = Stack_context.wrap (callback) def Handle_future (future): Response = Future.result () Ioloop.curren T (). Add_callback (callback, Response) Future.add_done_callback (handle_future) def handle_response (response=" return future< /pre>
Test_func inside, I put the function handle_response out, as long as the subsequent operation, call the Handle_response, will be the callback function Handle_future, the last callback function callback
Write asynchronous callback program with tornado