zmievsa / cadwyn

Production-ready community-driven modern Stripe-like API versioning in FastAPI
https://docs.cadwyn.dev/
MIT License
207 stars 27 forks source link

BackgroundTasks don't run #212

Open jfeaver opened 19 hours ago

jfeaver commented 19 hours ago

Describe the bug BackgroundTasks don't run.

To Reproduce Use this Cadwyn app:

from cadwyn import Cadwyn, VersionBundle, HeadVersion, Version, VersionedAPIRouter
from fastapi import BackgroundTasks

def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)

router = VersionedAPIRouter()

@router.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}

app = Cadwyn(versions=VersionBundle(HeadVersion(), Version("2000-01-01")))
app.generate_and_include_versioned_routers(router)
  1. Send a POST to the /send-notification/{email} route.
  2. See that the expected message is returned ("Notification sent in the background").
  3. Look for a log file from the background task. It isn't there.

Expected behavior A log file should be created with the provided email param logged.

This vanilla FastAPI App has the expected behaviour:

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}

Operating system MacOS 14.3.1 (23D60)

Additional context cadwyn v4.2.3 fastapi v0.115.0

> poetry env info
Virtualenv
Python:         3.12.3
Implementation: CPython
Path:           /Users/nathan/Library/Caches/pypoetry/virtualenvs/example_background_task_bug--VJlo0R1-py3.12
Executable:     /Users/nathan/Library/Caches/pypoetry/virtualenvs/example_background_task_bug--VJlo0R1-py3.12/bin/python
Valid:          True

Base
Platform:   darwin
OS:         posix
Python:     3.12.3
Path:       /opt/homebrew/opt/python@3.12/Frameworks/Python.framework/Versions/3.12
Executable: /opt/homebrew/opt/python@3.12/Frameworks/Python.framework/Versions/3.12/bin/python3.12
zmievsa commented 18 hours ago

Thanks! I'll try to provide the fixes tomorrow!