标签: uvicorn

Gunicorn uvicorn worker.py 如何遵守 limit_concurrency 设置

FastAPI 使用 Gunicorn 启动 uvicorn 工作程序,如https://www.uvicorn.org/settings/中所述

但是,gunicorn 不允许使用自定义设置启动 uvicorn,如https://github.com/encode/uvicorn/issues/343中所述

该问题建议覆盖源文件中的 config_kwargs,例如https://github.com/encode/uvicorn/blob/master/uvicorn/workers.py

limit_concurrency我们尝试过,但 uvicorn 不遵守源中多个 uvicorn 文件中的设置:

https://github.com/encode/uvicorn/blob/master/uvicorn/workers.py

# fail

        config_kwargs = {
            "app": None,
            "log_config": None,
            "timeout_keep_alive": self.cfg.keepalive,
            "timeout_notify": self.timeout,
            "callback_notify": self.callback_notify,
            "limit_max_requests": self.max_requests, "limit_concurrency": 10000,
            "forwarded_allow_ips": self.cfg.forwarded_allow_ips,
        }

Run Code Online (Sandbox Code Playgroud)

https://github.com/encode/uvicorn/blob/master/uvicorn/main.py

# fail

    kwargs = {
        "app": app,
        "host": host,
        "port": port,
        "uds": uds,
        "fd": fd,
        "loop": loop,
        "http": http,
        "ws": ws,
        "lifespan": lifespan,
        "env_file": env_file,
        "log_config": LOGGING_CONFIG if log_config is None else log_config,
        "log_level": log_level,
        "access_log": …
Run Code Online (Sandbox Code Playgroud)

concurrency gunicorn fastapi uvicorn concurrency-limits

13
推荐指数
1
解决办法
1万
查看次数

用于尾随斜杠的 FastAPI 重定向返回非 ssl 链接

当我们调用端点并且由于缺少尾部斜杠而发生重定向时遇到问题。如下图所示,当向https ://.../notifications发出请求时,FastAPI 服务器响应重定向到http ://...notifications/

我怀疑这是一个应用程序配置问题,而不是服务器配置问题。有没有人知道如何解决这个问题?

重定向示例

python-3.x fastapi uvicorn

12
推荐指数
1
解决办法
2976
查看次数

为什么当我在 FastAPI 服务中启动 uvicorn 时,我的配置方法会运行两次?

我使用 fastapi 和 uvicorn 编写了一个服务。我的服务中有一个启动 uvicorn 的 main (见下文)。主要是,我做的第一件事是加载配置设置。我有一些 INFO 输出,可以在加载配置时输出设置。我注意到当我启动服务时,配置加载方法似乎运行了两次。

# INITIALIZE
if __name__ == "__main__":
    # Load the config once at bootstrap time. This outputs the string "Loading configuration settings..."
    config = CdfAuthConfig()
    print("Loaded Configuration")
    # Create FastAPI object
    app = FastAPI()
    # Start uvicorn
    uvicorn.run(app, host="127.0.0.1", port=5050)
Run Code Online (Sandbox Code Playgroud)

我运行该服务时的输出如下所示:

Loading configuration settings...
Loading configuration settings...
Loaded Configuration
Run Code Online (Sandbox Code Playgroud)

为什么“CdfAuthConfig()”类被实例化两次?它显然与“uvicorn.run”命令有关。

python-3.x fastapi uvicorn

12
推荐指数
1
解决办法
3815
查看次数

FastAPI,uvicorn.run() 总是创建 3 个实例,但我想要 1 个实例

我在 PyCharm IDE 上运行 FastAPI,它总是运行 3 个工作线程。我不知道为什么,但是,每次 API 调用都会访问最后创建的实例。

谁能帮助我如何获得单一运行的工人?

代码:

import uvicorn
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(CORSMiddleware,
                   allow_origins=["*"],
                   allow_methods=["*"],
                   allow_headers=["*"])
print(f"main.py with :{app}")


@app.get('/')
def home():
    return "Hello"


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=False, log_level="debug", debug=True,
                workers=1, limit_concurrency=1, limit_max_requests=1)
Run Code Online (Sandbox Code Playgroud)

控制台输出:

/Users/user/.pyenv/versions/3.7.10/bin/python /Users/user/github/my-project/backend/main.py
main.py with :<fastapi.applications.FastAPI object at 0x102b35d50>
INFO:     Will watch for changes in these directories: ['/Users/user/github/my-project/backend']
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) …
Run Code Online (Sandbox Code Playgroud)

python fastapi uvicorn

12
推荐指数
1
解决办法
3万
查看次数

fastapi/uvicorn 如何并行化请求?

我用 fastapi 和 uvicorn 进行了一项实验,但我不明白其结果。

关于代码

@app.get('/loadtest')
def root():
    time.sleep(1)
    return {'message': 'hello'}
Run Code Online (Sandbox Code Playgroud)

在 docker 中运行

CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"]
Run Code Online (Sandbox Code Playgroud)

我进行了以下测试:

ab -c 100 -n 1000 localhost/loadtest
Run Code Online (Sandbox Code Playgroud)

这给了我结果:

bersling-2:cas bersling$ ab -c 100 -n 1000 localhost/loadtest
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed …
Run Code Online (Sandbox Code Playgroud)

python parallel-processing fastapi uvicorn

12
推荐指数
1
解决办法
1万
查看次数

使用 websockets 正常关闭 uvicorn starlette 应用程序

鉴于此示例 Starlette 应用程序具有开放的 websocket 连接,您如何关闭 Starlette 应用程序?我在 uvicorn 上运行。每当我按下Ctrl+C输出时,Waiting for background tasks to complete.它就会永远挂起。

from starlette.applications import Starlette

app = Starlette()

@app.websocket_route('/ws')
async def ws(websocket):
    await websocket.accept()

    while True:
        # How to interrupt this while loop on the shutdown event?
        await asyncio.sleep(0.1)

    await websocket.close()
Run Code Online (Sandbox Code Playgroud)

我尝试在关闭事件上切换 bool 变量,但该变量永远不会更新。它总是False

例如。

app.state.is_shutting_down = False


@app.on_event('shutdown')
async def shutdown():
    app.state.is_shutting_down = True


@app.websocket_route('/ws')
async def ws(websocket):
    await websocket.accept()

    while app.state.is_shutting_down is False:
Run Code Online (Sandbox Code Playgroud)

python python-asyncio asgi starlette uvicorn

11
推荐指数
1
解决办法
4246
查看次数

从 dockerfile 和 pythonfile 中的 uvicorn 命令运行 fastapi 有区别吗?

我正在运行一个快速的 api,当我在开发时,我的 app.py 文件中有以下一段代码

app.py 中的代码:

import uvicorn


if __name__=="__main__":
    uvicorn.run("app.app:app",host='0.0.0.0', port=4557, reload=True, debug=True, workers=3)
Run Code Online (Sandbox Code Playgroud)

所以我正要CMD ["python3","app.py"]在我的 Dockerfile 中运行。

在 fastapi 示例中,他们做了这样的事情:

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
Run Code Online (Sandbox Code Playgroud)

我想知道这两种方法有什么区别,因为我认为它们都可以工作。

python docker fastapi uvicorn

11
推荐指数
2
解决办法
8956
查看次数

Fastapi python 代码执行速度受 uvicorn 与 gunicorn 部署的影响

我写了一个 fastapi 应用程序。现在我正在考虑部署它,但是我似乎遇到了奇怪的意外性能问题,这似乎取决于我使用 uvicorn 还是 gunicorn。特别是如果我使用 gunicorn,所有代码(甚至标准库纯 python 代码)似乎都会变慢。对于性能调试,我编写了一个小应用程序来演示这一点:

import asyncio, time
from fastapi import FastAPI, Path
from datetime import datetime

app = FastAPI()

@app.get("/delay/{delay1}/{delay2}")
async def get_delay(
    delay1: float = Path(..., title="Nonblocking time taken to respond"),
    delay2: float = Path(..., title="Blocking time taken to respond"),
):
    total_start_time = datetime.now()
    times = []
    for i in range(100):
        start_time = datetime.now()
        await asyncio.sleep(delay1)
        time.sleep(delay2)
        times.append(str(datetime.now()-start_time))
    return {"delays":[delay1,delay2],"total_time_taken":str(datetime.now()-total_start_time),"times":times}
Run Code Online (Sandbox Code Playgroud)

使用以下命令运行 fastapi appi:

gunicorn api.performance_test:app -b localhost:8001 -k uvicorn.workers.UvicornWorker --workers 1
Run Code Online (Sandbox Code Playgroud)

get to 的响应体 …

python gunicorn fastapi uvicorn

11
推荐指数
2
解决办法
744
查看次数

FastAPI websocket ping/pong 超时

我正在使用 FastAPI 来@app.websocket监听传入的 websocket。FastAPI(或下面的 Starlette 或 Uvicorn)如何进行 ping/pong 心跳?这是可配置的吗?我根本无法在文档中找到它。

from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/")
def ws(websocket: WebSocket):
    pass
Run Code Online (Sandbox Code Playgroud)

fastapi使用starlette,并且在幕后似乎使用websocketswebsockets.connect默认情况下使用 20 秒的 aping_intervalping_timeout,但我不知道 FastAPI 中是否使用了它。

websocket starlette fastapi uvicorn

10
推荐指数
1
解决办法
8587
查看次数

Uvicorn 异步工作线程仍在同步工作

问题简述

我已将我的项目从 Django 2.2 迁移到 Django 3.2,现在我想开始使用异步视图的可能性。我创建了一个异步视图,设置了 asgi 配置,并使用 Uvicorn 工作程序运行 Gunicorn。当该服务器同时有 10 个用户时,他们会被同步服务。我需要配置什么才能为 10 个并发用户提供异步视图?

详细问题

这是我到目前为止在本地环境中所做的:

  • 我正在使用 Django 3.2.10 和 Python 3.9。
  • 我已经安装gunicornuvicorn通过 pip
  • 我创建了一个asgi.py包含以下内容的文件
    import os
    from django.core.asgi import get_asgi_application
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyService.settings.local')
    application = get_asgi_application()
Run Code Online (Sandbox Code Playgroud)
  • 我创建了一个具有以下实现的视图,并将其连接到urlpatterns
    import asyncio
    import json
    from django.http import HttpResponse
    
    async def async_sleep(request):
        await asyncio.sleep(1)
        return HttpResponse(json.dumps({'mode': 'async', 'time': 1).encode())
Run Code Online (Sandbox Code Playgroud)
  • 我在本地运行一个带有 Uvicorn 工作程序的 Gunicorn 服务器:
gunicorn MyService.asgi:application -k uvicorn.workers.UvicornWorker
[2022-01-26 14:37:14 +0100] [8732] [INFO] Starting …
Run Code Online (Sandbox Code Playgroud)

python django daphne asgi uvicorn

10
推荐指数
1
解决办法
4432
查看次数