百度请求测试
import tornado.web
import tornado.ioloop
import tornado.httpclient
class IndexHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
wd = self.get_argument('wd')
# 请求百度地址
url = 'https://www.baidu.com/s?wd={}'.format(wd)
# 获取客户端,fetch(rul)获取源码
client = tornado.httpclient.HTTPClient()
print('同步测试')
response = client.fetch(url)
print(response)
self.write('index')
def make_app():
return tornado.web.Application(handlers=[
(r'/index/', IndexHandler),
])
if __name__ == '__main__':
app = make_app()
app.listen(8000)
tornado.ioloop.IOLoop.current().start()
async1
import tornado.web
import tornado.web
import tornado.ioloop
import tornado.httpclient
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous # 让io不主动关闭
def get(self, *args, **kwargs):
wd = self.get_argument('wd')
url = 'https//www.baidu.com/s?wd={name}'.format(name=wd)
# 获取异步客户端,fetch(url, callback回调)
clicent = tornado.httpclient.AsyncHTTPClient()
print('异步请求开始')
clicent.fetch(url, callback=self.on_response)
self.write('请求成功')
def on_response(self, response):
print(response)
# 关闭io
self.finish()
def make_app():
return tornado.web.Application(handlers=[
(r'/index/', IndexHandler),
])
if __name__ == '__main__':
app = make_app()
app.listen(8000)
tornado.ioloop.IOLoop.current().start()
aysnc2
import tornado.web
import tornado.ioloop
import tornado.httpclient
import tornado.gen
class IndexHandler(tornado.web.RequestHandler):
# @tornado.gen.coroutine # 让io不主动关闭
# def get(self, *args, **kwargs):
# wd = self.get_argument('wd')
# url = 'https//www.baidu.com/s?wd={name}'.format(name=wd)
# # 获取异步客户端,fetch(url, callback回调)
# clicent = tornado.httpclient.AsyncHTTPClient()
# print('携程是程序')
# response = yield clicent.fetch(url)
# print(response)
async def get(self, *args, **kwargs):
wd = self.get_argument('wd')
url = 'https//www.baidu.com/s?wd={name}'.format(name=wd)
# 获取异步客户端,fetch(url, callback回调)
clicent = tornado.httpclient.AsyncHTTPClient()
print('携程是程序')
response = await clicent.fetch(url)
print(response)
def on_response(self, response):
print(response)
# 关闭io
self.finish()
def make_app():
return tornado.web.Application(handlers=[
(r'/index/', IndexHandler),
])
if __name__ == '__main__':
app = make_app()
app.listen(8000)
tornado.ioloop.IOLoop.current().start()