Can two aiohttp.web.Application()
objects be running in the same process, e.g. on different ports?
I see a bunch of examples of aiohttp code like:
from aiohttp import web
app = web.Application()
app.router.add_get('/foo', foo_view, name='foo')
web.run_app(app, host='0.0.0.0', port=10000)
I'm wondering if there's some equivalent where multiple web.Applications()
can be configured to run at the same time. Something like:
from aiohttp import web
app1 = web.Application()
app1.router.add_get('/foo', foo_view, name='foo')
app2 = web.Application()
app2.router.add_get('/bar', bar_view, name='bar')
# This is the wishful thinking code:
web.configure_app(app1, host='0.0.0.0', port=10000)
web.configure_app(app2, host='0.0.0.0', port=10001)
web.run_apps()
My use case is that I have an existing python web framework that does this kind of thing, and I'm building a prototype that's analogous in python 3.6 with aiohttp.
I understand that multiple python servers can run behind e.g. nginx (see also http://aiohttp.readthedocs.io/en/stable/deployment.html); that's not what I'm after. I want to explore the possibility of two aiohttp web servers with the same asyncio event loop, running in the same python process, serving on two different ports.
Yes, you can - just write some wrapper with re-implementation of
run_app
.Here is a simple example. All app-specific parts of
run_app
are moved to the dedicated classAppWrapper
. TheMultiApp
is responsible only for initialize all configured apps, keep running the loop and clean up.Note: be aware of the use of internal
aiohttp
's method, that may be subject of change.Now let's use it:
As a side note, think again why you need this. In almost all cases the decoupling is the better choice. Setting many endpoints in the same process make them depend on each other. There's one case that comes to my mind and has "good" reasoning, the internal stats / debug endpoint.
Though the above answer has been accepted, here is an another approach:
Create test.py:
At terminal, open two tabs. In one tab, run
In other tab, run
You will get response