coleifer / peewee

a small, expressive orm -- supports postgresql, mysql, sqlite and cockroachdb
http://docs.peewee-orm.com/
MIT License
11.17k stars 1.37k forks source link

Handle connection in Sanic framework #2908

Closed kien5436 closed 4 months ago

kien5436 commented 4 months ago

The docs says:

For web applications, it is common to open a connection when a request is received, and to close the connection when the response is delivered

I followed your instruction to create and close connection on each request. However, sometimes I got error "connection already opened". If I use

db.connect(True)

I get another error "mysql server has gone away".

Here's my config:

db = PooledMySQLDatabase(
  env.DB_NAME,
  host=env.DB_HOST,
  user=env.DB_USER,
  password=env.DB_PASS,
  port=env.DB_PORT,
  autoconnect=False,
  max_connections=100,
  timeout=28800,
  stale_timeout=300
)

Peewee: latest Python: 3.11 OS: Ubuntu 22.04

coleifer commented 4 months ago

You’re using an asyncio framework so you’ll need to do something like context local database connections. The thread local ones peewee uses aren’t compatible. Here’s some old docs for fastapi which describe the process: https://fastapi.tiangolo.com/how-to/sql-databases-peewee/

I suggest using flask instead.

coleifer commented 4 months ago

https://charlesleifer.com/blog/asyncio/ for a little more background.

kien5436 commented 4 months ago

You’re using an asyncio framework so you’ll need to do something like context local database connections. The thread local ones peewee uses aren’t compatible. Here’s some old docs for fastapi which describe the process: https://fastapi.tiangolo.com/how-to/sql-databases-peewee/

I suggest using flask instead.

This is my company's product so change the framework is risk. I'll try your suggestion