Python aiohttp 问题

2018-06-17 19:34:32 +08:00
 bestehen

import asyncio

from aiohttp import web

async def index(request): await asyncio.sleep(0.5) return web.Response(body=b'

Index

')

async def hello(request): await asyncio.sleep(0.5) text = '

hello, %s!

' % request.match_info['name'] return web.Response(body=text.encode('utf-8'))

async def init(loop): app = web.Application(loop=loop) app.router.add_route('GET', '/', index) app.router.add_route('GET', '/hello/{name}', hello) srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000) print('Server started at http://127.0.0.1:8000...') return srv

loop = asyncio.get_event_loop() loop.run_until_complete(init(loop)) loop.run_forever()

这里的我感觉 只执行了 init 啊 hello 和 index 函数没有执行把

1673 次点击
所在节点    Python
2 条回复
matsuz
2018-06-17 19:55:32 +08:00
init 是 web 服务器的启动器,程序启动时就执行了; hello 和 index 是被注册到 URL 路由表中,它们是接到相应的 HTTP 请求后才执行。

另外,你的代码排版很差
bestehen
2018-06-18 01:23:52 +08:00
你是怎么看出来的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/463761

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX