- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 fastapi 后端托管一个 pytorch 模型。当我用 python 运行代码时,它工作正常。 depickled 模型可以使用定义的类。当同一个文件以 uvicorn 启动时,它找不到类定义。
源代码如下所示:
import uvicorn
import json
from typing import List
from fastapi import Body, FastAPI
from fastapi.encoders import jsonable_encoder
import requests
from pydantic import BaseModel
#from model_ii import Model_II_b
import dill as pickle
import torch as T
import sys
app = FastAPI()
current_model = 'model_v2b_c2_small_ep15.pkl'
verbose_model = False # for model v2
class Model_II_b(T.nn.Module):
[...]
@app.post('/function')
def API_call(req_json: dict = Body(...)):
try:
# load model...
model = pickle.load(open('models/' + current_model, 'rb'))
result = model.dosomething_with(req_json)
return result
except Exception as e:
raise e
return {"error" : str(e)}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
当我用
python main.py
运行它时它工作正常,我得到了结果。当我用
uvicorn main:app
运行它时并发送请求我收到以下错误:
AttributeError: Can't get attribute 'Model_II_b' on <module '__mp_main__' from '/opt/webapp/env/bin/uvicorn'>
两者都应该使用与我在 env 中使用 uvicorn 相同的 python env。
(model_2) root@machinelearning-01:/opt/apps# uvicorn main:app --env-file /opt/apps/env/pyvenv.cfg --reload
INFO: Loading environment from '/opt/apps/env/pyvenv.cfg'
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [164777] using statreload
INFO: Started server process [164779]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:33872 - "POST /ml/v2/predict HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/opt/apps/env/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/opt/apps/env/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/opt/apps/env/lib/python3.6/site-packages/fastapi/applications.py", line 183, in __call__
await super().__call__(scope, receive, send) # pragma: no cover
File "/opt/apps/env/lib/python3.6/site-packages/starlette/applications.py", line 102, in __call__
await self.middleware_stack(scope, receive, send)
File "/opt/apps/env/lib/python3.6/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/opt/apps/env/lib/python3.6/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/opt/apps/env/lib/python3.6/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/opt/apps/env/lib/python3.6/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/opt/apps/env/lib/python3.6/site-packages/starlette/routing.py", line 550, in __call__
await route.handle(scope, receive, send)
File "/opt/apps/env/lib/python3.6/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/opt/apps/env/lib/python3.6/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/opt/apps/env/lib/python3.6/site-packages/fastapi/routing.py", line 197, in app
dependant=dependant, values=values, is_coroutine=is_coroutine
File "/opt/apps/env/lib/python3.6/site-packages/fastapi/routing.py", line 149, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/opt/apps/env/lib/python3.6/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
return await loop.run_in_executor(None, func, *args)
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "./main.py", line 155, in API_call
raise e
File "./main.py", line 129, in API_call
model = pickle.load(open('models/' + current_model, 'rb'))
File "/opt/apps/env/lib/python3.6/site-packages/dill/_dill.py", line 270, in load
return Unpickler(file, ignore=ignore, **kwds).load()
File "/opt/apps/env/lib/python3.6/site-packages/dill/_dill.py", line 473, in load
obj = StockUnpickler.load(self)
File "/opt/apps/env/lib/python3.6/site-packages/dill/_dill.py", line 463, in find_class
return StockUnpickler.find_class(self, module, name)
AttributeError: Can't get attribute 'Model_II_b' on <module '__mp_main__' from '/opt/apps/env/bin/uvicorn'>
enter code here
最佳答案
在@lsabi 的帮助下,我在这里找到了解决方案 https://stackoverflow.com/a/51397373/13947506
使用自定义 unpickler 解决了我的问题:
class CustomUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if name == 'Model_II_b':
from model_ii_b import Model_II_b
return Model_II_b
return super().find_class(module, name)
current_model = 'model_v2b_c2_small_ep24.pkl'
model = CustomUnpickler(open('models/' + current_model, 'rb')).load()
关于python - 使用 uvicorn 运行时,fastapi 找不到模型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62953477/
我试图让 Uvicorn 在以编程方式启动时检测到文件更改时自动重新启动,就像使用 --debug 开关从命令行启动时一样。以下语句位于我的 api 源代码文件的底部,虽然 Uvicorn 启动并运行
晚上好, 我正在使用 python 3.9 并尝试根据 Internet 上的文档在 Windows 10 Pro 上运行新的 FastAPI 服务 https://www.uvicorn.org/我
我有一台在本地运行的服务器。当我在 AWS EC2 上运行它并在端口 8000 上从外部发送请求时,我收到以下错误: $ uvicorn sql_app.main:app --host="0.0.0.
我将 Django Channels 与 uvicorn 一起使用,我有以下类型的代码: async def connect(self): """Accept connect if user
我有一个 gunicorn + uvicorn + fastApi 堆栈。(基本上,我使用的是 https://hub.docker.com/r/tiangolo/uvicorn-gunicorn-f
有没有办法干净地杀死 uvicorn? 即,如果它在终端的前台运行,我可以在它上面键入 ^C。这会导致 uvivorn 进程终止,并且所有工作进程都将被清理。 (即,它们消失了。) 另一方面,如果 u
我正在尝试将 Django 3.0 与 Uvicorn 一起使用并开始使用: INFO: Started server process [96219] INFO: Waiting fo
我正在使用 uvicorn,我需要使用现有的事件循环。我正在使用以下命令: loop = asyncio.get_event_loop() 但是当我使用这一行时,代码卡住了。但是如果我使用 new_e
我的环境 快速 API Gunicorn 和 Uvicorn worker AWS EC2 c5.2xlarge(8 个 vCPU) 文档 https://fastapi.tiangolo.com/d
我的 FastAPI 应用程序似乎两次记录了很多事情。 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit
给定 main.py : import asyncio async def new_app(): # Await some things. async def app(scope, r
我正在学习 fastapi,我正在本地主机上启动一个 uvicorn 服务器。每当出现错误/异常时,我都没有得到回溯。 我得到的只是:INFO: 127.0.0.1:56914 - "POST /cr
当我使用 uvicorn 运行我的 FastAPI 服务器时: uvicorn main:app --host 0.0.0.0 --port 8000 --log-level info 运行服务器后得
我们正在使用 https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker FastAPI 并且能够使用 gunicorn 日志文件自定义我们
我正在尝试使用 FastAPI + uvicorn 创建一个应用程序。 此应用程序必须能够处理同时连接。我不能保证所有代码都可以以异步/等待方式执行。 然后,我想使用 --workers X来自 uv
我在 Windows 机器上使用 uvicorn 在 Python 中运行 FastAPI 应用程序。当我要么 在我的 Mac 上运行以下代码,或 当我没有为 uvicorn 指定端口时(从 uvic
我尝试了本教程( https://dev.to/rajshirolkar/fastapi-over-https-for-development-on-windows-2p7d ),然后当我进入浏览器但
我有一个使用 uvicorn 执行的 FastAPI api 代码。现在我想添加一个队列系统,我认为 Celery 和 Flower 对我来说是很好的工具,因为我的 api 有一些端点使用大量 CPU
我有一个使用 uvicorn 执行的 FastAPI api 代码。现在我想添加一个队列系统,我认为 Celery 和 Flower 对我来说是很好的工具,因为我的 api 有一些端点使用大量 CPU
我正在使用由 Uvicorn 服务器提供服务的 FastAPI 框架。 我的应用程序应该在给定的端点 (/run) 上运行一些耗时的数值计算。为此,我使用来自 fastAPI 的“background
我是一名优秀的程序员,十分优秀!