我刚刚创建了一个信号来在创建用户时生成令牌,我使用 tortoise.signals 在单独的文件中生成它,我的项目结构是这样的
├── Makefile
├── README.md
├── core
│ ├── __init__.py
│ ├── authentication.py
│ ├── email.py
│ ├── models.py
│ ├── router.py
│ ├── schema.py
│ ├── signals.py
│ └── views.py
├── main.py
├── requirements.txt
├── static
└── templates
└── verification.html
这是我的信号文件
# signals.py
from tortoise.signals import post_save
from tortoise import BaseDBAsyncClient
from typing import Type, List, Optional
from .models import UserModel, business_pydantic
from .email import send_email
@post_save(sender=UserModel)
async def create_business(
sender: "Type[UserModel]",
instance: UserModel,
created: bool,
using_db: Optional[BaseDBAsyncClient],
update_fields: List[str],
) -> None:
if created:
business_objects: UserModel = await UserModel.create(
business_name = instance.username, owner_id = instance
)
await business_pydantic.from_tortoise_orm(business_objects)
# send email
await send_email([instance.email], instance)
我在函数中导入模块
create_app
from dotenv import dotenv_values
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from fastapi.staticfiles import StaticFiles
from .router import router
def create_app():
app = FastAPI()
# mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")
import signals # <- import my signal file here
register_tortoise(
app=app,
db_url="postgres://postgres:1234@localhost:5432/ecommerce_db",
modules={"models": ["core.models"]},
generate_schemas=True,
add_exception_handlers=True,
)
# add routes
app.include_router(router)
return app
我的问题是,我在
signals.py
文件中创建的信号未读取/执行,如果我将它们放在单独的文件中,如何使我制作的函数正确执行,有没有办法注册以便信号是在快速 API 中读取的吗?
谢谢!
您可以在您的register_tortoise配置中将signals.py注册为模块。 (适合我)
register_tortoise(
app=app,
db_url="postgres://postgres:1234@localhost:5432/ecommerce_db",
modules={"models": ["core.models", "core.signals"]},
generate_schemas=True,
add_exception_handlers=True,
)