fastapi初始化乌龟orm的问题 [英] issues with initializing tortoise orm with fastapi
问题描述
我遇到乌龟orm和fastapi
i am having issue with tortoise orm and fastapi
我有来自 app.py
的以下代码;我略过了几行以使内容简洁化
i have the following code from app.py
; i have skipped some lines to make this concise
app.py
from fastapi import FastAPI, HTTPException
from app.models import User_Pydantic, UserIn_Pydantic, Users
from app.utils import cryptoUtil
from app.auth import auth as auth_router
from tortoise.contrib.fastapi import HTTPNotFoundError, register_tortoise
app = FastAPI()
@app.post("/users", response_model=User_Pydantic)
async def create_user(user: UserIn_Pydantic):
user.password = cryptoUtil.hash_password(user.password)
user_obj = Users(email=user.email, password=user.password, fullname=user.fullname, status=user.status)
await user_obj.save()
return await User_Pydantic.from_tortoise_orm(user_obj)
register_tortoise(
app,
db_url=config.DATABASE_URL,
modules={"models": ["app.models"]},
generate_schemas=True,
add_exception_handlers=True,
)
app.include_router(auth_router.router, tags=["Auth"])
if __name__ == '__main__':
app.run()
这很好并且可以创建用户
this works fine and able to create users
但是现在我正尝试从另一个文件中执行同样的操作
but now i am trying to do the same from another file
auth.py
from fastapi import APIRouter, Depends, HTTPException
from app.auth import crud
from app.utils import cryptoUtil
from app.models import User_Pydantic, UserIn_Pydantic, Users
router = APIRouter()
@router.post("/auth/register", response_model=User_Pydantic)
async def register(user: UserIn_Pydantic):
result = await crud.find_exist_user(user.email)
if result:
raise HTTPException(status_code=404, detail="user already exists!")
user.password = cryptoUtil.hash_password(user.password)
user_obj = Users(email=user.email, password=user.password, fullname=user.fullname, status=user.status)
await user_obj.save()
return await User_Pydantic.from_tortoise_orm(user_obj)
但是这不起作用,我在404错误响应中得到了
but this does not work and i get this in 404 error response
{
"detail": "Object does not exist"
}
我认为问题在于
return await User_Pydantic.from_tortoise_orm(user_obj)
无法在 auth.py
文件中工作,因为出于某些原因,我无法在初始化了乌龟的 app.py
文件之外运行该文件
is not able to work in auth.py
file because for some reason i cant run it outside of app.py
file which is where tortoise is initialized
我该怎么做才能解决此问题?问题的一部分是如何从存在 register_tortoise
的 app.py
外部调用乌龟初始化
what do i do to fix this?
part of the issue am having is how to be able to call tortoise initialization from outside app.py
where register_tortoise
exists
更新:
文件夹结构
├── app
│ ├── app.py
│ ├── models.py
│ ├── config.py
│ │
│ ├── auth
│ │ ├── auth.py
│ │ ├── crud.py
│ │
│ └── utils
│ ├── cryptoUtil.py
│
推荐答案
正如我在评论中所说,您需要插入
As I said in the comments, you need to insert
Tortoise.init_models(models_list, "models")
在下一行之前
register_tortoise(
app,
db_url=config.DATABASE_URL,
modules={"models": ["app.models"]},
generate_schemas=True,
add_exception_handlers=True,
)
当然,您必须更改模型"文件夹和名称,具体取决于您的配置.
Of course you'll have to change the "models" folder and name according to your configuration.
一开始我也是一个问题,但是下面的github问题解决了这个问题
At the beginning it was also a problem for me as well, but the following github issue solved the problem
https://github.com/tortoise/tortoise-orm/issues/444
文档也提供了解释
https://tortoise-orm.readthedocs.io/en/latest/search.html?q = early + init
更新
Tortoise.init_models(models_list, "models")
models_list是要考虑的模型路径的列表(字符串).在您的情况下,它将是 app.models
.
models_list is the list (strings) of paths of the models that are to be considered. In your case, it'll be app.models
.
这个想法是在连接数据库之前初始化并开始准备模型.这是使关系在式模型中可用的必需步骤.
The idea is to initialize and start preparing the models, before connecting to the database. This is a step required in order to make relations available in the pydantic models.
此处是API文档
这篇关于fastapi初始化乌龟orm的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!