Write asynchronous callback program with tornado

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.