Передать словарь в другой класс
У меня есть приложение 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 - это json-код BaseModel
{
"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'
Есть ли способ передать словарь в класс метода, чтобы я мог выполнять с ним другие задачи перед возвратом?
1 ответ
Комментарии указали в правильном направлении. Полный рабочий код
@app.post("/ip")
async def ip(request: MyAPIModel):
mydata = request.dict()
test = MyClass()
results = test.get_type(mydata)
return results
Необходимо вернуть как в подклассе, так и в main.py