问题描述
我想要达到的目标
在Django中创建一个数据库连接池。连接池通过使用 SQLAlchemy's connection pooling 和 django-postgrespool2 连接到 Postgresql 数据库。
抛出异常
运行以下代码行'psycopg2.extensions.connection' object is not callable
时会抛出 poolConnection = dbPool.connect()
。打印 dbPool
对象和类型显示 <sqlalchemy.pool.impl.QueuePool object at 0x00000171832A72B0> <class 'sqlalchemy.pool.impl.QueuePool'>
代码
创建与 Postgresql 数据库的连接并创建连接池的数据库助手类:
import psycopg2
from sqlalchemy import pool
import traceback
dbPool = None
class DbPoolHelper:
def ensurePoolCreated(self):
global dbPool
if dbPool != None:
return
self.createPool()
def dbConnect(self):
dbConnection = psycopg2.connect(user="...",password="...",dbname="...",host="...",port="...")
return dbConnection
def createPool(self):
dbConnection = self.dbConnect()
global dbPool
dbPool = pool.QueuePool(dbConnection,max_overflow=10,pool_size=5)
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
使用DbPoolHelper
方法通过execute
方法获取一些数据并提供一些sql和sql参数作为参数的代码:
def pooltest():
sql = "SELECT * FROM sysproductcontainers;"
sqlParams = ()
db = DbPoolHelper()
result = db.execute(sql,sqlParams)
问题
为什么代码会抛出 'psycopg2.extensions.connection' object is not callable
?
请记住,我对 Python 和 Django 还很陌生。因此,对于某些 Python 和/或 Django 开发人员来说,我可能会遗漏一些显而易见的东西。
谢谢!
解决方法
根据 QueuePool
文档,第一个参数应该是“返回 DB-API 连接对象的可调用函数”。
您已将被调用函数的结果作为第一个参数而不是函数本身传递给 QueuePool
对象。去掉括号解决问题:
def createPool(self):
dbConnection = self.dbConnect
global dbPool
dbPool = pool.QueuePool(dbConnection,max_overflow=10,pool_size=5)