aiomysql connect pool && uvicorn

该博客展示了如何在Python中利用aiomysql库创建连接池,并进行异步数据库查询操作。代码示例包括获取数据库连接池、执行查询、事务处理以及在FastAPI应用启动时初始化连接池。主要涉及异步编程、数据库连接管理和FastAPI集成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Pool — aiomysql 0.0.22 documentation

# import aiomysql
# import asyncio

# g_pool = None

# async def fetch_user():
#     global g_pool
#     with (await g_pool) as conn:
#         cursor = await conn.cursor()
#         await cursor.execute("SELECT * FROM models")
#         return await cursor.fetchall()
#         # print(rows)

# async def fetch_blog():
#     global g_pool
#     with (await g_pool) as conn:
#         cursor = await conn.cursor()
#         await cursor.execute("SELECT * FROM models")
#         return await cursor.fetchall()
        
# async def run(loop):
#     global g_pool
#     g_pool = await aiomysql.create_pool(
#         host='10.142.145.185', 
#         port=3306, 
#         user='root', 
#         password='dccadmin@#', 
#         db='mpp', 
#         autocommit=True,
#         minsize=1,
#         maxsize=10, 
#         loop=loop)

#     rows= await fetch_user()
#     print(rows)
#     rows = await fetch_blog()
#     print(3333333333,rows)

#     g_pool.close()
#     await g_pool.wait_closed()

# loop = asyncio.get_event_loop()
# loop.run_until_complete(run(loop))


from fastapi import FastAPI
import aiomysql
import secret
import asyncio

app = FastAPI()





MYSQL_HOST = "10.142.145.185"
MYSQL_PORT = 3306
MYSQL_USER = 'root'
MYSQL_DB = 'mpp'
MYSQL_PASSWD = 'dccadmin@#'
MYSQL_CONNECTION_MAXSIZE = 2
MYSQL_POOL_RECYCLE = 60
'''
eÞ¥`
'''

async def get_mysql_pool():
    return await aiomysql.create_pool(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER,
                                      password=MYSQL_PASSWD,
                                      db=MYSQL_DB,
                                      loop=asyncio.get_event_loop(), autocommit=False,
                                      maxsize=MYSQL_CONNECTION_MAXSIZE,
                                      pool_recycle=MYSQL_POOL_RECYCLE)

task = [asyncio.ensure_future(get_mysql_pool())]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(task))
pool = [t.result() for t in task]
pool = pool[0]




# (Þ¥`eÍ\mysql
async def execute(sql: str, args: list = None) -> any:
    conn: aiomysql.Connection
    cursor: aiomysql.DictCursor
    rows: int
    res: list

    async with pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cursor:
            try:
                rows = await cursor.execute(sql, args)
                res = await cursor.fetchall()
                return await rows, res
            except Exception as e:
                await conn.ping()
                rows = await cursor.execute(sql, args)
                res = await cursor.fetchall()
                # print(22222222222222,rows,res)
                return  rows, res
            

async def execute_with_commit(sql: str, args: list = None) -> int:
    conn: aiomysql.Connection
    cursor: aiomysql.Cursor
    rows: int
    print(sql)

    async with pool.acquire() as conn:
        async with conn.cursor(aiomysql.Cursor) as cursor:
            try:
                rows = await cursor.execute(sql, args)
                await conn.commit()
                return rows
            except Exception as e:
                await conn.ping()
                await cursor.execute(sql, args)
                await conn.commit()
                return conn.affected_rows()        

@app.on_event("startup")
async def _startup():
    app.state.pool = await aiomysql.create_pool(host='10.142.145.185', port=3306, user='root', password='dccadmin@#', db='mpp')
    print("startup done")

async def _get_query_with_pool(pool):
    async with  pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cur:
            await cur.execute("SELECT 1")
            return await cur.fetchall()

@app.get("/v1/get_data")
async def _get_data():
    rows,res=await execute('select * from models;')
    print(3333333333333,rows,res)
    return await _get_query_with_pool(app.state.pool)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=814)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值