如何在 AioHttp 中添加 运行 嵌套应用程序
How to add Run Nested applications in AioHttp
我正在尝试 AIOhttp 中的嵌套应用程序,但无法将其添加到 运行。
如果我希望我的 url 像 localhost/greet/
和 localhost/greet/abc
,我正在使用以下代码但给了我 404 Not Found
所以我的路由不正确。
我在这里也找不到很多在线资源。
下面是我的代码:
app = web.Application()
greet = web.Application()
app.router.add_get('/', index)
greet.router.add_get('/{name}', handle_name, name='name')
app.add_subapp('/greet/', greet)
web.run_app(app, host='127.0.0.1', port=8080)
async def handle_name(request):
name = request.match_info.get('name', "Anonymous")
txt = "Hello {}".format(name)
return web.Response(text=txt)
任何指导都会有所帮助!
不完全清楚你的问题是什么,但这工作正常:
from aiohttp import web
async def index_view(request):
return web.Response(text='index\n')
async def subapp_view(request):
name = request.match_info.get('name', "Anonymous")
txt = "Hello {}\n".format(name)
return web.Response(text=txt)
app = web.Application()
app.router.add_get('/', index_view)
greet = web.Application()
greet.router.add_get('/{name}', subapp_view)
app.add_subapp('/greet/', greet)
if __name__ == '__main__':
web.run_app(app, host='127.0.0.1', port=8080)
然后用 curl 测试:
~ 0 25ms ➤ curl localhost:8080/
index
~ 0 33ms ➤ curl localhost:8080/greet/world
Hello world
希望这能回答您的问题。
我正在尝试 AIOhttp 中的嵌套应用程序,但无法将其添加到 运行。
如果我希望我的 url 像 localhost/greet/
和 localhost/greet/abc
,我正在使用以下代码但给了我 404 Not Found
所以我的路由不正确。
我在这里也找不到很多在线资源。
下面是我的代码:
app = web.Application()
greet = web.Application()
app.router.add_get('/', index)
greet.router.add_get('/{name}', handle_name, name='name')
app.add_subapp('/greet/', greet)
web.run_app(app, host='127.0.0.1', port=8080)
async def handle_name(request):
name = request.match_info.get('name', "Anonymous")
txt = "Hello {}".format(name)
return web.Response(text=txt)
任何指导都会有所帮助!
不完全清楚你的问题是什么,但这工作正常:
from aiohttp import web
async def index_view(request):
return web.Response(text='index\n')
async def subapp_view(request):
name = request.match_info.get('name', "Anonymous")
txt = "Hello {}\n".format(name)
return web.Response(text=txt)
app = web.Application()
app.router.add_get('/', index_view)
greet = web.Application()
greet.router.add_get('/{name}', subapp_view)
app.add_subapp('/greet/', greet)
if __name__ == '__main__':
web.run_app(app, host='127.0.0.1', port=8080)
然后用 curl 测试:
~ 0 25ms ➤ curl localhost:8080/
index
~ 0 33ms ➤ curl localhost:8080/greet/world
Hello world
希望这能回答您的问题。