我正在寻找一种模式,在这种模式中,我有多个函数需要访问上下文管理的资源。
特别是,我正在使用fastAPI,并且希望重用aiopg (异步psycopg2)连接。
这是基本布局:
@app.get("/hello")
def hello():
async with aiopg.connect(...) as conn:
async with conn.cursor(...):
return cursor.execute(...)现在,我希望避免每个路由都有一个连接。我可以在外部考虑一个对象,在此过程中,我要么访问conn属性,要么等待创建(并存储回来),然后在cursor()方法上使用with。
class Pg():
async def conn(self):
if not self._conn:
self._conn = await aiopg.connect(...)
return self._conn
myPg = Pg()
@app.get("/hello")
def hello():
conn = await myPg.conn()
async with conn.cursor(...):
return cursor.execute(...)但是,我将失去自动关闭连接的能力。
我认为我在这里遗漏了一些非常明显的东西,希望有人能指导我如何正确地实现它。
谢谢!
发布于 2020-08-27 17:30:42
aiopg提供了一个可以管理连接的Pool class。
只需在模块级别创建一个池实例:
pool = await aiopg.create_pool('<your connection string>')然后,您可以使用Pool.acquire上下文管理器来获取连接:
async with pool.acquire() as conn:
...如果池中已存在连接,则将重用这些连接。
https://stackoverflow.com/questions/63612066
复制相似问题