3

我需要用 aiohttp 包装我的 Flask 应用程序。当我启动它时,出现错误:

This webpage has a redirect loop

ERR_TOO_MANY_REDIRECTS
ReloadHide details
The webpage at http://localhost:5000/ has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
Learn more about this problem.

代码:

import asyncio
from flask import Flask
from aiohttp import web
from aiohttp_wsgi import WSGIHandler

app = Flask(__name__)

@app.route('/')
def login():
    return 'Hello World'

@asyncio.coroutine
def init(loop):
    wsgi_flask_app = WSGIHandler(app)
    aio_app = web.Application(loop=loop)
    aio_app.router.add_route('*', '/{path_info:.*}', wsgi_flask_app)

    srv = yield from loop.create_server(
        aio_app.make_handler(), '127.0.0.1', 5000)
    return srv

if __name__ == '__main__':
    io_loop = asyncio.get_event_loop()
    io_loop.run_until_complete(init(io_loop))

    try:
        io_loop.run_forever()
    except KeyboardInterrupt:
        print('Interrupted')

当我将例中的路线更改为

aio_app.router.add_route('*', '{path_info:.*}', wsgi_flask_app)

它引发 ValueError:路径应以 / 开头。我究竟做错了什么?

4

1 回答 1

1

aiohttp.router 中的“add_route”方法可以通过以下构造来解决:

wsgi_route = DynamicRoute('*', wsgi_flask_app, 'wsgi_flask_app',
                          re.compile('^(?P<path_info>.*)$'), '{path_info}')
app.router.register_route(wsgi_route)

但恕我直言,这不是一个很好的解决方案。这看起来像是 aiohttp 中向后不兼容的更改,更好的解决方案是使用另一个 aiohttp 版本。

更新:

aiohttp-wsgi 0.2.5 版本开始,您可以添加以 '/' 开头的路由。

于 2015-09-01T17:07:59.210 回答