Closed
Description
Long story short
I am trying to check ContextVar integration with aiohttp. https://docs.python.org/3/library/contextvars.html#asyncio-support
ContextVar seems not deals well with aiohttp server... Am I doing something wrong?
Expected behaviour
ContextVar should be different for each request.
Actual behaviour
ContextVar has the same value between requests, but seems to be cleared on failure.
Steps to reproduce
server.py
from contextvars import ContextVar
from aiohttp import web
ctx = ContextVar("test")
async def handle(request):
try:
ctx.get()
assert False, "Shouldn't ever be called. ContextVar has value"
except LookupError:
pass
ctx.set("Test")
return web.Response(text="Hello, " + ctx.get())
app = web.Application()
app.add_routes([web.get('/', handle)])
web.run_app(app, port=8000)Other process client.py
Client is working fine, just for example
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
while True:
async with session.get("http://127.0.0.1:8000/") as response:
html = await response.text()
print(html)
asyncio.run(main())Response
Server is constantly being failed on each even request.
Hello, Test
<html><head><title>500 Internal Server Error</title></head><body><h1>500 Internal Server Error</h1>Server got itself in trouble</body></html>
Hello, Test
<html><head><title>500 Internal Server Error</title></head><body><h1>500 Internal Server Error</h1>Server got itself in trouble</body></html>
Hello, Test
...
Extra example
I tried almost the same for sanic, and seems that it works fine.
from contextvars import ContextVar
from sanic import Sanic
from sanic.response import text
app = Sanic()
ctx = ContextVar("test")
@app.route('/')
async def test(request):
try:
ctx.get()
assert False, "Shouldn't ever be called. ContextVar has value"
except LookupError:
pass
ctx.set("Test")
return text('hello, ' + ctx.get())
app.run(host='0.0.0.0', port=8000)Response
hello, Test
hello, Test
hello, Test
hello, Test
hello, Test
hello, Test
hello, Test
Your environment
macOs Mojave
Python 3.7.0 (default, Jun 29 2018, 20:13:13) \n[Clang 9.1.0 (clang-902.0.39.2)]
aiohttp 3.4.4, also tried 3.5.0a1 from master branch