aio-libs / aiomysql

aiomysql is a library for accessing a MySQL database from the asyncio
https://aiomysql.rtfd.io
MIT License
1.72k stars 254 forks source link

How to initialize a database connection only once when deploying services using FastAPI #986

Open TheHonestBob opened 1 month ago

TheHonestBob commented 1 month ago

Describe the bug

The simplest way is to define conn and cursor in the initialization method, but it fails because the init method cannot be asynchronous

To Reproduce

Expected behavior

I only want to connect to the database once for a FastAPI service, rather than having to connect to the database every time a request is made

Logs/tracebacks

Python Version

$ python --version
python = 3.9

aiomysql Version

$ python -m pip show aiomysql
0.2.0

PyMySQL Version

$ python -m pip show PyMySQL
1.1.0

SQLAlchemy Version

$ python -m pip show sqlalchemy

OS

linux

Database type and version

SELECT VERSION();
无

Additional context

No response

Code of Conduct