不废话直接上代码
import asyncio
import aiomysql
from aiohttp import web
async def handle(request):
pool = request.app['mysql_pool']
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT id,name FROM users")
(id, name) = await cur.fetchone()
return web.Response(text=f'用户ID:{id} 用户名:{name}')
async def init(loop):
mysql_pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
user='root', password='123456',
db='blog', loop=loop)
async def on_shutdown(application):
"""
接收到关闭信号时,要先关闭连接池,并等待连接池关闭成功.
:param web.Application application:
:return:
"""
application['mysql_pool'].close()
await application['mysql_pool'].wait_closed()
application = web.Application()
application.on_shutdown.append(on_shutdown)
application['mysql_pool'] = mysql_pool
application.add_routes([web.get('/', handle)])
return application
if __name__ == '__main__':
loop = asyncio.get_event_loop()
application = loop.run_until_complete(init(loop))
web.run_app(application, host='127.0.0.1')
loop.close()