我在 2.2 中有一个现有的 django 项目,但现在我想开始使用通道,所以我必须更改为 3.0 和 asgi 而不是 wsgi。
如何生成运行应用程序所需的 asgi.py?
我部署的应用程序是K8s下的FastAPI with Uvicorn。在尝试了解如何对应用程序进行 Docker 化时,我明白我想在没有 Gunicorn 的情况下实现 Uvicorn,并添加一个根据应用程序收到的请求负载进行扩展/缩减的系统。我做了很多负载测试,发现默认情况下有 1 个 Uvicorn 工作人员,我可以获得 3.5 RPS,而将工作人员更改为 8 个时,我可以轻松获得 22 RPS(没有检查更多,因为这对我来说效果很好) 。
现在,我对资源的期望是,我必须提供的 CPU 限制为 8(我假设每个工作人员在一个进程和线程上工作),但我只看到内存使用量增加,但大麦在CPU中。也许是因为应用程序不使用那么多的 CPU,但它确实有可能使用超过 1 个 CPU?到目前为止,它没有使用超过一个CPU。
Uvicorn 工人如何工作?我应该如何计算该应用程序需要多少工作人员?我没有找到任何有用的信息。
我读到 fastapi“如果需要可以与 WSGI 一起使用”。我就想知道怎么办?
我用 fastapi 做了一个完整的项目,并尝试将其部署在 cpanel 共享主机上(我目前的选择),
在 wsgi.py 文件中我使用了 a2sg 库
from main import app
from a2wsgi import ASGIMiddleware
application = ASGIMiddleware(app)
Run Code Online (Sandbox Code Playgroud)
但我得到 503 暂时繁忙,当我浏览该页面时重试
那么,我如何部署我的应用程序,我轻松部署了 django,但 fasapi 是一个问题,因为它主要使用 ASGI。也可以吗?
我已经部署了一个 django 应用程序(使用 uvicorn 在 ASGI 上)并获得了很多 OperationalError FATAL: sorry, too many clients already
这似乎是 django 4.x 和 ASGI 的一个已知问题 #33497,但到目前为止我找不到任何内容(除了承认它)
有没有办法解决这个问题,或者我应该切换到 WSGI(或降级到 3.2)?
在我看来,这对于使用 ASGI 来说是一个阻碍问题。难道不应该更好地记录下来吗?(除非我错过了)
我正在集成 django 通道以实现异步功能。我正在尝试使用函数上的等待来获取用户模型的多个对象。
class TeamConsumer(AsyncConsumer):
async def websocket_connect(self, event):
await self.send({
"type":"websocket.accept"
})
async def websocket_receive(self, event):
o_user = await self.users()
print(o_user)
@database_sync_to_async
def users(self):
return UserModel.objects.all()
Run Code Online (Sandbox Code Playgroud)
尝试从上述代码中获取用户会导致错误“您无法从异步上下文中调用它 - 使用线程或sync_to_async。”
但是,如果我使用“UserModel.objects.all().first()”获取单个对象,则一切正常。
尝试使用 uvicorn 测试我的第一个 FastAPI 应用程序。
在Jupyter Notebook上编写以下代码并保存'main.py'在目录中:/home/user
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Run Code Online (Sandbox Code Playgroud)
从我正在运行的同一目录:
$uvicorn main --reload
Run Code Online (Sandbox Code Playgroud)
它抛出以下错误:
错误:加载 ASGI 应用程序时出错。导入字符串“main”必须采用“:”格式。
我已按照 Channel 2 教程进行操作,但运行后出现此错误py manage.py runserver
File "C:\Users\Mach2\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\routing.py", line 35, in get_default_application
raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'channels_test.routing'
Run Code Online (Sandbox Code Playgroud) 我的 ASGI 应用程序将事件发送到curl,然后发送到我的手机。然而,即使服务器正在发送事件,并且标头看起来正确,但在连接关闭之前,我的 Windows 计算机上的 Firefox 和 Chrome 都不会收到事件。
无论我将服务器托管在 WSL、Powershell 终端还是单独的 Linux 机器上,都会发生这种情况。
然而,如果我将服务器托管在 repl.it 上,这些相同的浏览器可以正常工作(请分叉并尝试一下)。
我尝试修改 Windows 防火墙设置,但无济于事。
这是应用程序代码:
import asyncio
import datetime
async def app(scope, receive, send):
headers = [(b"content-type", b"text/html")]
if scope["path"] == "/":
body = (
"<html>"
"<body>"
"</body>"
"<script>"
" let eventSource = new EventSource('/sse');"
" eventSource.addEventListener('message', (e) => {"
" document.body.innerHTML += e.data + '<br>';"
" });"
"</script>"
"</html>"
).encode()
await send({"type": "http.response.start", "status": 200, "headers": headers})
await send({"type": "http.response.body", "body": …Run Code Online (Sandbox Code Playgroud) 目前,我有一个简单的 API,在某个内部 IIS 站点的子目录下与 Flask 一起运行。现在我认为使用 FastAPI 重写该 API 可能是个好主意。在 IIS 上运行 API 并不是一件难事,您必须web.config在 IIS 配置中创建一些内容。我知道这是使用 WSGI,但是也有可能使用 ASGI(也许与 uvicorn 和 Gunicorn 结合使用)?
重要的一件事是它必须在某个子目录下运行,称之为<iis_internal_company_server>/myapi。在 Flask 中,我包含了一个众所周知的前缀中间件,它可以按预期工作。我正在寻找类似的 FastAPI,这是否可以使用app.include_router(router, prefix='/myapi')?
做了一些研究但没有找到解决方案。也许你们中的一个人对此有一些经验。如果有,请分享。提前谢谢了。
问候,托马斯
鉴于main.py:
import asyncio
async def new_app():
# Await some things.
async def app(scope, receive, send):
...
return app
app = asyncio.run(new_app())
Run Code Online (Sandbox Code Playgroud)
其次是:
uvicorn main.app
Run Code Online (Sandbox Code Playgroud)
给出:
RuntimeError: asyncio.run() cannot be called from a running event loop
Run Code Online (Sandbox Code Playgroud)
这是因为uvicorn在导入我的应用程序之前已经启动了一个事件循环。如何在 下异步构建应用程序uvicorn?
在基于 FastAPI 的 Web 应用程序中,我有一个 WebSocket 端点,仅当满足某些条件时才应允许连接,否则它应返回答复HTTP 404而不是升级与HTTP 101.
据我了解,协议完全支持这一点,但我找不到任何方法可以使用 FastAPI 或 Starlette 来做到这一点。
如果我有类似的东西:
@router.websocket("/foo")
async def ws_foo(request: WebSocket):
if _user_is_allowed(request):
await request.accept()
_handle_ws_connection(request)
else:
raise HTTPException(status_code=404)
Run Code Online (Sandbox Code Playgroud)
该异常不会转换为 404 响应,因为 FastAPIExceptionMiddleware似乎无法处理此类情况。
是否有任何本机/内置方式支持这种“拒绝”流程?
我尝试通过 pip3 在系统上安装 uvicorn ,但我无法从命令行运行它。有关如何解决此问题的任何指示?
Requirement already satisfied: uvicorn in /home/vhawk19/.local/lib/python3.7/site-packages (0.10.8)
Requirement already satisfied: uvloop>=0.14.0; sys_platform != "win32" and sys_platform != "cygwin" and platform_py
thon_implementation != "pypy" in /home/vhawk19/.local/lib/python3.7/site-packages (from uvicorn) (0.14.0)
Requirement already satisfied: websockets==8.* in /home/vhawk19/.local/lib/python3.7/site-packages (from uvicorn)
(8.1)
Requirement already satisfied: click==7.* in /home/vhawk19/.local/lib/python3.7/site-packages (from uvicorn) (7.0
)
Requirement already satisfied: h11==0.8.* in /home/vhawk19/.local/lib/python3.7/site-packages (from uvicorn) (0.8
.1)
Requirement already satisfied: httptools==0.0.13; sys_platform != "win32" and sys_platform != "cygwin" and platform
_python_implementation != "pypy" in /home/vhawk19/.local/lib/python3.7/site-packages …Run Code Online (Sandbox Code Playgroud) python manage.py runserver使用通道 asgi 开发服务器运行我的项目可以完美地启动它,但是当使用 Daphne ( daphne project.routing:application)运行项目时,我收到错误AppRegistryNotReady: Apps aren't loaded yet。
settings.py
INSTALLED_APPS = [
'channels',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
# ...
# ... installed apps and custom apps
]
WSGI_APPLICATION = 'project.wsgi.application'
ASGI_APPLICATION = 'project.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [REDIS_URL],
}
},
}
Run Code Online (Sandbox Code Playgroud)
routing.py
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.conf.urls import url …Run Code Online (Sandbox Code Playgroud) asgi ×13
python ×9
django ×5
fastapi ×5
uvicorn ×5
wsgi ×2
antivirus ×1
async-await ×1
channel ×1
cpanel ×1
daphne ×1
django-3.0 ×1
django-4.0 ×1
django-4.1 ×1
iis ×1
passenger ×1
python-3.x ×1
starlette ×1
websocket ×1
worker ×1