如何在 Django Python 中使用 PostgreSQL 为 SQLAlchemy 连接池设置方言?需要启用预 ping 功能
Posted
技术标签:
【中文标题】如何在 Django Python 中使用 PostgreSQL 为 SQLAlchemy 连接池设置方言?需要启用预 ping 功能【英文标题】:How do I set the dialect for a SQLAlchemy connection pool with PostgreSQL in Django Python? Needed for pre-ping feature enabled 【发布时间】:2021-06-15 17:34:46 【问题描述】:我正在努力实现的目标
我需要为 Django Python 中的 SQLAlchemy 数据库池激活 pre-ping 功能。
错误
当我将pre_ping
属性设置为True
时,我收到以下错误,提示我在使用预ping 功能时需要将dialect
传递给连接池:
The ping feature requires that a dialect is passed to the connection pool.
代码
连接池创建者/处理者的代码:
import psycopg2
from sqlalchemy import create_engine
import traceback
from myproject import settings
from dataClasses.EmptyObject import *
import json
import sqlalchemy.pool as pool
from sqlalchemy.pool import QueuePool
dbPool = None
class DbPoolHelper:
def ensurePoolCreated(self):
global dbPool
if dbPool != None:
return
self.createPool()
def dbConnect(self):
dbConfig = self.getDbPoolConfig()
dbConnection = psycopg2.connect(user=dbConfig.user, password=dbConfig.password, dbname=dbConfig.dbName, host=dbConfig.host, port=dbConfig.port)
print("=========== POOL CONNECTED =================")
return dbConnection
def createPool(self):
dbConnection = self.dbConnect
global dbPool
dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5, pre_ping=True)
print("=========== POOL CREATED =================")
def execute(self, sql, sqlParams):
try:
global dbPool
self.ensurePoolCreated()
poolConnection = dbPool.connect()
cursor = poolConnection.cursor()
cursor.execute(sql, sqlParams)
poolConnection.commit()
result = cursor.fetchall()
cursor.close()
poolConnection.close()
return result
except Exception as e:
print(e)
return e
def getDbPoolConfig(self):
settingName = "pool"
dbConfig = EmptyObject()
dbConfig.host = settings.DATABASES[settingName]["HOST"]
dbConfig.port = settings.DATABASES[settingName]["PORT"]
dbConfig.user = settings.DATABASES[settingName]["USER"]
dbConfig.password = settings.DATABASES[settingName]["PASSWORD"]
dbConfig.dbName = settings.DATABASES[settingName]["NAME"]
dbConfig.poolSize = settings.DATABASES[settingName]["POOL_SIZE"]
dbConfig.poolMaxOverflow = settings.DATABASES[settingName]["POOL_MAX_OVERFLOW"]
dbConfig.poolRecycleTime = settings.DATABASES[settingName]["POOL_RECYCLE_TIME"]
return dbConfig
问题
在使用 PostgreSQL 数据库时,如何将这个 dialect
传递到连接池?
其他说明
如果您知道另一种创建连接池并启用了 pre-ping 功能的方法,我们也欢迎您提出这些建议。
谢谢!
【问题讨论】:
【参考方案1】:QueuePool
构造函数将所有关键字参数传递给 Pool
构造函数。此构造函数支持 dialect
参数。所以你应该可以在QueuePool
通话中添加方言:
from sqlalchemy.dialects import postgresql
# redacted
dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5, pre_ping=True, dialect=postgresql.dialect())
# redacted
【讨论】:
以上是关于如何在 Django Python 中使用 PostgreSQL 为 SQLAlchemy 连接池设置方言?需要启用预 ping 功能的主要内容,如果未能解决你的问题,请参考以下文章
巧用python-mysql-replication寻找pos点
巧用python-mysql-replication寻找pos点