fastapi-users / fastapi-users

Ready-to-use and customizable users management for FastAPI
https://fastapi-users.github.io/fastapi-users/
MIT License
4.3k stars 368 forks source link

Add background tasks to register endpoint and on_after_register handler #1288

Closed jankadel closed 9 months ago

jankadel commented 9 months ago

It would be great to have background tasks available in after register handler.

codecov[bot] commented 9 months ago

Codecov Report

Merging #1288 (889ad7f) into master (ff9fae6) will not change coverage. The diff coverage is 100.00%.

@@            Coverage Diff            @@
##            master     #1288   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           35        35           
  Lines          972       972           
=========================================
  Hits           972       972           
Files Changed Coverage Δ
fastapi_users/manager.py 100.00% <100.00%> (ø)
fastapi_users/router/register.py 100.00% <100.00%> (ø)

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more

frankie567 commented 9 months ago

Thank you for the idea and proposal @jankadel! However, you can achieve this by adding background_tasks to the UserManager initializer. For example:

class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
    reset_password_token_secret = SECRET
    verification_token_secret = SECRET

    def __init__(self, user_db: SQLAlchemyUserDatabase, background_tasks: BackgroundTasks):
        super().__init__(user_db)
        self.background_tasks = background_tasks

    async def on_after_register(self, user: User, request: Optional[Request] = None):
        print(f"User {user.id} has registered.")
        self.background_tasks.add_task(my_task, user=user)

async def get_user_manager(background_tasks: BackgroundTasks, user_db=Depends(get_user_db)):
    yield UserManager(user_db, background_tasks)

So, there is no need to add another param to the hooks 🙂

jankadel commented 9 months ago

Ah great! Thanks @frankie567