Skip to content

Commit fb69443

Browse files
authored
练习python的aiohttp
1 parent e8545dd commit fb69443

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

test56.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr.bin.env python 3
2+
# -*- coding: utf-8 -*-
3+
4+
'''
5+
练习python的aiohttp
6+
练习服务器上的异步操作
7+
'''
8+
9+
__author__ = 'sergiojune'
10+
import asyncio
11+
from aiohttp import web
12+
13+
14+
async def index(request): # 首页返回一个h1标签
15+
await asyncio.sleep(0.5)
16+
return web.Response(body=b'<h1>index</h1>', content_type='text/html')
17+
18+
19+
async def hello(request): # 根据url参数返回信息
20+
await asyncio.sleep(0.5)
21+
return web.Response(body=b'<h1>hello %s</h1>' % request.match_info['name'], content_type='text/html')
22+
23+
24+
# 初始化服务器,也是一个coroutine
25+
async def init(loop): # 接受协程池
26+
app = web.Application(loop=loop)
27+
# 添加反应路径
28+
app.router.add_route('GET', '/', index)
29+
app.router.add_route('GET', '/hello/{name}', hello)
30+
s = loop.create_server(app.make_handler(), '', 80) # 用loop.create_server创建tcp协议
31+
print('sever is start in 127.0.0.1:80')
32+
return s
33+
34+
35+
loop = asyncio.get_event_loop()
36+
loop.run_until_complete(init(loop))
37+
loop.run_forever() # 服务器永远运行
38+

0 commit comments

Comments
 (0)