Tornado Series IV: Web Requests

Source: Internet
Author: User
Tags urlencode

1. Synchronous request

Import Tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webImport Tornado.httpclientImport urllibimport jsonimport datetimeimport timefrom tornado.options Import define, Optionsdefine ("Port", default= 8000, help= "run on the given port", Type=int) class Indexhandler (Tornado.web.RequestHandler): Def get (self): Quer y = self.get_argument (' q ')client = tornado.httpclient.HTTPClient ()        response = Client.fetch ("Http://search.twitter.com/search.json?" + Urllib.urlencode ({"Q": Query, "ResU Lt_type ":" Recent "," RPP ": +)) BODY = Json.loads (response.body)        Result_count = Len (body[' results ')) now = Datetime.datetime.utcnow () raw_oldest_tweet_at = body[' res Ults '][-1][' created_at '] oldest_tweet_at = Datetime.datetime.strptime (Raw_oldest_tweet_at, "%a,%d% b%Y%h:%m:%s +0000 ") Seconds_diff = Time.mktime (Now.timetuple ())-Time.mktime (Oldest_tweet_at.tim Etuple ()) Tweets_per_second = float (result_count)/Seconds_diff Self.write ("" "<div style=" Text-align:ce    Nter "> <div style=" font-size:72px ">%s</div> <div style=" font-size:144px ">%.02f</div> <div style= "font-size:24px" >tweets per second</div></div> "" "% (query, Tweets_per_second)) if __name __ = = "__main__": Tornado.options.parse_command_line () app = Tornado.web.Application (handlers=[(r "/", Indexhandler)] ) Http_server = Tornado.httpserver.HTTPServer (APP) Http_server.listen (Options.port) Tornado.ioloop.IOLoop.instanc E (). Start ()
2. Asynchronous request with callback function

Import Tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webImport Tornado.httpclientImport urllibimport jsonimport datetimeimport timefrom tornado.options Import define, Optionsdefine ("Port", default= 8000, help= "run on the given port", Type=int) class Indexhandler (Tornado.web.RequestHandler):@tornado. web.asynchronous #保证在函数返回后, the connection does not close immediately, and the connection is closed manually after the asynchronous processing is completeddef get (self): query = self.get_argument (' q ')client = Tornado.httpclient.AsyncHTTPClient () client.fetch ("Http://search.twitter.com/search.json?" +    Urllib.urlencode ({"Q": Query, "result_type": "Recent", "RPP": +}), Callback=self.on_response) #设置response返回后的回调函数def on_response (self, response): BODY = json.loads (response.body) Result_count = Len (body[' results ']) now = Datetime.datetime.utcnow () Raw_oldest_tweet_at = body[' results '][-1][' created_at '] oldest_tweet_at = Datetime.datetime.strptime (Raw_oldest_tweet_at, "%a,%d%b%Y%h:%m:%s +0000") Seconds_diff = TIME.M Ktime (Now.timetuple ())-Time.mktime (Oldest_tweet_at.timetuple ()) Tweets_per_second = float (result_ count)/Seconds_diff Self.write ("" "<div style=" Text-align:center "> <div style=" font-size:72px ">%s </div> <div style= "font-size:144px" >%.02f</div> <div style= "font-size:24px" >tweets per sec Ond</div></div> "" "% (self.get_argument (' Q '), Tweets_per_second))self.finish () #手动关闭连接if __name__ = = "__main__": Tornado.options.parse_command_line () app = Tornado.web.Application (handlers=[(r "/", Index Handler)]) Http_server = tornado.httpserver.HTTPServer (APP) Http_server.listen (Options.port) Tornado.ioloop.IOLoo P.instance (). Start ()
3. Asynchronous request with asynchronous generator method

Import Tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webImport Tornado.httpclientimport Tornado.genImport urllibimport jsonimport datetimeimport timefrom tornado.options Import define, Optionsdefine ("Port", default= 8000, help= "run on the given port", Type=int) class Indexhandler (Tornado.web.RequestHandler):@tornado. web.asynchronous @tornado. Gen.enginedef get (self): query = self.get_argument (' q ')client = tornado.httpclient.AsyncHTTPClient () response = yield Tornado.gen.Task (client. Fetch, "Http://search.twitter.com/search.json" + urllib.urlencode ({"Q": Query, "Result_typ E ":" Recent "," RPP ":)) BODY = json.loads (response.body) Result_count = Len (body[' results ']) now = Datetime.datetime.utcnow () Raw_oldest_tweet_at = body[' results '][-1][' created_at '] oldest_tweet_at = Datetime.datetime.strptime (raw_oldest_tw                 Eet_at, "%a,%d%b%Y%h:%m:%s +0000") Seconds_diff = Time.mktime (Now.timetuple ())- Time.mktime (Oldest_tweet_at.timetuple ()) Tweets_per_second = float (result_count)/Seconds_diff Self.write ( "" "<div style=" Text-align:center "> <div style=" font-size:72px ">%s</div> <div style=" font-size : 144px ">%.02f</div> <div style=" font-size:24px ">tweets per second</div></div>" ""% (query , Tweets_per_second))self.finish ()if __name__ = = "__main__": Tornado.options.parse_command_line () app = Tornado.web.Application (handlers=[(r "/", Index Handler)]) Http_server = tornado.httpserver.HTTPServer (APP) Http_server.listen (Options.port) Tornado.ioloop.IOLoo P.instance (). Start ()

Tornado Series IV: Web Requests

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.