【发布时间】:2020-05-19 09:00:25
【问题描述】:
我有一个 FastAPI 应用程序,我希望将字典从 POST 方法传递到子目录中的另一个模块。 我的 main.py 是这样的
from fastapi import FastAPI
from pydantic import BaseModel
from app.api import mymodule
from app.api.mymodule import MyClass
app = FastAPI(debug = True, version="0.0.1")
class MyAPIModel(BaseModel):
"""
Required input from frontend for IP Allocation
"""
forename: str
surname: str
age: int
@app.get("/")
async def default():
return {"Default root page"}
@app.get("/home")
async def home():
return {"message": "Homepage for Application"}
@app.post("/ip")
async def ip(request: MyAPIModel):
superhero = request.dict()
superhero_request = MyClass.get_type(superhero)
Mymodule.py 看起来像
import api
class MyClass:
def __init__(self, superhero):
self.mysetup = api(url, token)
self.superhero_info = superhero
"""
Here is where I want to access the dictionary
and use it
"""
def get_type(self):
return self.superhero_info
我的 POST 请求是 BaseModel 的 json 字典
{
"forename": "peter",
"surname": "parker",
"age": 28
}
但是这样做我得到以下错误
File "/usr/local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 550, in __call__
await route.handle(scope, receive, send)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/usr/local/lib/python3.7/site-packages/fastapi/routing.py", line 148, in app
dependant=dependant, values=values, is_coroutine=is_coroutine
File "/usr/local/lib/python3.7/site-packages/fastapi/routing.py", line 101, in run_endpoint_function
return await dependant.call(**values)
File "./app/main.py", line 36, in ip
Allocate.get_type(iprequest)
File "./app/api/mymodule.py", line 21, in get_type
return self.superhero_info
AttributeError: 'dict' object has no attribute 'superhero'
有没有办法将字典传递给方法类,以便我可以在返回之前对其执行其他任务?
【问题讨论】:
-
在我看来您正在调用静态函数,但
get_type()不是静态的。您需要先实例化 MyClass 对象,然后调用get_type()。像这样,MyClass().get_type(myrequest) -
我认为您忘记了回溯中错误名称的行
-
添加了完整的错误@Donatien
-
使用 MyClass().get_type(myrequest) 返回 null @ThuYeinTun
-
但它会再次导致错误吗?返回 null 很可能是因为您的请求没有
forename。
标签: python python-3.x fastapi