跳转到主要内容

在多个工作进程中使用时,同步Sanic连接

项目描述

Sanic-Synchro-Ctx

插件,提供多个工作进程之间共享的App上下文

可以使用原生的Python SyncManager后端,或者如果您想的话使用Redis。(Redis要快得多)。

安装

$ pip3 install sanic-synchro-ctx

或者在python虚拟环境中 (以下命令行示例适用于基于Linux/Unix的操作系统)

$ python3 -m virtualenv --python=python3 --no-site-packages .venv
$ source ./.venv/bin/activate
$ pip3 install sanic sanic-synchro-ctx

退出虚拟环境

$ deactivate

Redis扩展

您可以使用可安装的redis扩展安装此插件的相应Redis库

$ pip3 install sanic-synchro-ctx[redis]

这等同于运行

$ pip3 install "sanic-synchro-ctx" "aioredis>=2.0" "hiredis>=1.0"

兼容性

  • 与Python 3.8及更高版本兼容。
  • 与Sanic v21.9.0及更高版本兼容。
  • 如果您单独安装redis库,请使用aioredis >= 2.0

用法

一个非常简单的示例,它使用原生的Python SyncManager后端,不需要Redis连接。

from sanic_synchro_ctx import SanicSynchroCtx
app = Sanic("sample")
s = SanicSynchroCtx(app)

@app.after_server_start
def handler(app, loop=None):
    # This will only set this value if it doesn't already exist
    # So only the first worker will set this value
    app.ctx.synchro.set_default({"counter": 0})

@app.route("/inc")
def increment(request: Request):
    # atomic increment operation
    counter = request.app.ctx.synchro.increment("counter")
    print("counter: {}".format(counter), flush=True)
    return html("<p>Incremented!</p>")

@app.route("/count")
def increment(request: Request):
    # Get from shared context:
    counter = request.app.ctx.synchro.counter
    print("counter: {}".format(counter), flush=True)
    return html(f"<p>count: {counter}</p>")

app.run("127.0.0.1", port=8000, workers=8)

Redis示例

from sanic_synchro_ctx import SanicSynchroCtx
redis = aioredis.from_url("redis://localhost")
app = Sanic("sample")
s = SanicSynchroCtx(app, backend="redis", redis_client=redis)

@app.after_server_start
async def handler(app, loop=None):
    # This will only set this value if it doesn't already exist
    # So only the first worker will set this value
    await app.ctx.synchro.set_default({"counter": 0})

@app.route("/inc")
async def increment(request: Request):
    # atomic increment operation
    counter = await request.app.ctx.synchro.increment("counter")
    print(f"counter: {counter}", flush=True)
    return html("<p>Incremented!</p>")

@app.route("/count")
async def increment(request: Request):
    # Get from shared context:
    counter = await request.app.ctx.synchro.counter
    print(f"counter: {counter}", flush=True)
    return html(f"<p>count: {counter}</p>")

app.run("127.0.0.1", port=8000, workers=8)

变更日志

完整的变更日志保存在 CHANGELOG文件 中。

基准测试

我已经进行了一些基本的基准测试。SyncManager工作得非常好,但Redis后端要快得多。

许可证

此仓库采用MIT许可证。有关详细信息,请参阅许可证文件

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码发行版

sanic-synchro-ctx-0.1.0.tar.gz (34.4 kB 查看哈希值)

上传时间 源代码

构建发行版

sanic_synchro_ctx-0.1.0-py3-none-any.whl (9.5 kB 查看哈希值)

上传时间 Python 3

由以下支持