async def before_server_start(app_): if config.setdefault('enable_inherit', True): enable_inherit(app_.loop) inherit_enabled[0] = True await self.set_bind( URL( drivername=config.setdefault('driver', 'asyncpg'), host=config.setdefault('host', 'localhost'), port=config.setdefault('port', 5432), username=config.setdefault('user', 'postgres'), password=config.setdefault('password', ''), database=config.setdefault('database', 'postgres'), ), min_size=config.setdefault('pool_min_size', 5), max_size=config.setdefault('pool_max_size', 10), loop=app_.loop, )
async def before_server_start(_, loop): if app.config.setdefault('DB_USE_CONNECTION_FOR_REQUEST', True): enable_inherit(loop) inherit_enabled[0] = True await self.set_bind( URL( drivername=app.config.setdefault('DB_DRIVER', 'asyncpg'), host=app.config.setdefault('DB_HOST', 'localhost'), port=app.config.setdefault('DB_PORT', 5432), username=app.config.setdefault('DB_USER', 'postgres'), password=app.config.setdefault('DB_PASSWORD', ''), database=app.config.setdefault('DB_DATABASE', 'postgres'), ), min_size=app.config.setdefault('DB_POOL_MIN_SIZE', 5), max_size=app.config.setdefault('DB_POOL_MAX_SIZE', 10), loop=loop, )
async def before_first_request(): if app.config.setdefault('DB_USE_CONNECTION_FOR_REQUEST', True): enable_inherit(asyncio.get_event_loop()) dsn = app.config.get('DB_DSN') if not dsn: dsn = URL( drivername=app.config.setdefault('DB_DRIVER', 'asyncpg'), host=app.config.setdefault('DB_HOST', 'localhost'), port=app.config.setdefault('DB_PORT', 5432), username=app.config.setdefault('DB_USER', 'postgres'), password=app.config.setdefault('DB_PASSWORD', ''), database=app.config.setdefault('DB_DATABASE', 'postgres'), ) await self.set_bind( dsn, echo=app.config.setdefault('DB_ECHO', False), min_size=app.config.setdefault('DB_POOL_MIN_SIZE', 5), max_size=app.config.setdefault('DB_POOL_MAX_SIZE', 10), loop=asyncio.get_event_loop(), )
def inherit(event_loop): with enable_inherit(event_loop): yield
#!/usr/bin/env python3 # encoding: utf-8 import asyncio import aiocontextvars x = aiocontextvars.ContextVar('x') x.set(0) loop = asyncio.get_event_loop() aiocontextvars.enable_inherit(loop) async def a(): print(x.get()) x.set('a') await asyncio.sleep(0) print(x.get()) async def b(): x.set('b') await asyncio.sleep(0) print(x.get()) loop.create_task(a()) loop.run_until_complete(b()) # is the output 0 b a ?