模块级的上下文管理资源



我正在寻找一种模式,其中我有多个函数需要访问上下文管理的资源。

特别是,我正在使用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(...)

然而,我将失去自动关闭连接的能力。

我想我错过了一些非常明显的东西,希望有人能指导我如何正确实施。

谢谢!

aiopg提供了一个可以管理连接的Pool类。

只需在模块级别创建一个池实例:

pool = await aiopg.create_pool('<your connection string>')

然后您可以使用Pool.acquire上下文管理器来获得连接:

async with pool.acquire() as conn:
...

如果池中已经存在连接,则会重新使用这些连接。

最新更新