I just created a signal to generate a token when the user is created, I use tortoise.signals to generate it in a separate file, my project structure is like this
├── 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
And here is my signal file
# 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)
and I import the module in function 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
My problem is that the signal that I created in the signals.py
file is not read/executed, how do I make the functions that I make executed properly if I make them in a separate file, is there a way to register so that the signal is read in fast API?
Thanks!
You can register the signals.py as a moduel in your register_tortoise configuration. (Works For Me)
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,
)