【问题标题】:How to return a list using router in fastapi如何在fastapi中使用路由器返回列表
【发布时间】:2021-09-10 18:24:04
【问题描述】:

在代码中,如果使用 (@app.post('/...')) 完成,它运行没有任何问题,但如果使用 (@router.post('/... ')),它给出了以下错误;
TypeError:无法实例化打字。联合
代码:

router = APIRouter()

@app.get("/api/accounts/userslist/{domain}",
          response_description="List all users")
async def account_list(
    domain: str,
    credentials: HTTPAuthorizationCredentials = Security(security)):
    token = credentials.credentials
    if (auth_handler.decode_token(token)):
        domain = domains_db.find_one({'domain': domain})
        if domain == None:
            return JSONResponse(
                status_code=status.HTTP_404_NOT_FOUND,
                content='There is no user matching the requested domain.')
        else:
            accounts = users_db.find({'domain': domain['domain_id']})
            list_account = [AuthModel(**account) for account in accounts]
            return list_account

型号:

class AuthModel(BaseModel):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    userid: UUID = Field(default_factory=uuid4)
    firstname: Optional[str]
    lastname: Optional[str]
    domain: UUID = Field(default_factory=uuid4)
    email: EmailStr
    phone: Optional[str]
    plain_secret: Optional[str]
    status: Optional[str]

【问题讨论】:

    标签: python python-3.x fastapi


    【解决方案1】:

    您是否将路由器包含在您的 main.py 文件中的应用程序中,如下所述:https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-the-apirouters-for-users-and-items

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 2020-01-16
      • 2021-03-25
      • 1970-01-01
      • 2020-10-07
      • 2018-03-23
      • 2021-06-08
      相关资源
      最近更新 更多