Search code examples
pythonflaskaiohttp

Aiohttp wsgi handler don't works


I need to wrap my Flask application with aiohttp. When I start it, there is an error:

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.

code:

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')

when I change the route like in this example to

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

it raises ValueError: path should be started with /. What am I doing wrong?


Solution

  • The "add_route" method in aiohttp.router can be worked around with following construction:

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

    But it's not pretty good solution IMHO. It's looks like backwards-incompatible change in aiohttp, and better solution is to use another aiohttp version.

    UPDATE:

    Since aiohttp-wsgi 0.2.5 version you can add routes starts with '/'.