【问题标题】:Using asyncpg connection pool with Sanic将 asyncpg 连接池与 Sanic 一起使用
【发布时间】:2018-10-03 08:19:54
【问题描述】:

我在网上整理了几个例子并想出了这个。此代码有效,但我想知道是否有更好的方法来做到这一点?

user.py:


from asyncpg import create_pool
from sanic import Blueprint

bp = Blueprint('dp')

class pg:
    def __init__(self, pg_pool):
        self.pg_pool = pg_pool

    async def fetch(self, sql, *args, **kwargs):
        async with self.pg_pool.acquire() as connection:
            return await connection.fetch(sql, *args, **kwargs)

    async def execute(self, sql, *args, **kwargs):
        async with self.pg_pool.acquire() as connection:
            return await connection.execute(sql, *args, **kwargs)

@bp.listener('before_server_start')
async def init_pg(app, loop):
    """
    Init Postgresql DB.
    """
    bp.pg_pool = await create_pool(
        **app.config.PG_CFG,
        max_inactive_connection_lifetime=60,
        min_size=1,
        max_size=3,
        loop=loop,
    )
    bp.pg = pg(bp.pg_pool)
    print('-------- setup connection pool --------')

现在在 webapp.py 中使用 pg 类

webapp.py:


@app.route("/")
async def root(req):
    result = await app.pg.fetch('SELECT * FROM foo')

【问题讨论】:

    标签: python sanic asyncpg


    【解决方案1】:

    我自己并没有使用 postgres 完成它,但是我使用 Redis 做了类似的事情。另外,我知道其他人使用before_server_start 使用类似的设置来创建池。

    另一种选择是

    看看:https://github.com/Skyscanner/aiotask-contexthttps://github.com/MagicStack/contextvars。也许他们可以提供帮助,将诸如连接之类的东西附加到循环中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      相关资源
      最近更新 更多