priyanshu-panwar / fastapi-utilities

🎨⚡️🔥 Reusable Utilities for FastAPI
https://youtu.be/ZIggeTU8JhQ?si=SO1B0Is0RdXDkbCa
MIT License
40 stars 1 forks source link

[✨Update✨] How to use with Latest FastAPI version #15

Closed priyanshu-panwar closed 8 months ago

priyanshu-panwar commented 8 months ago

[✨Update✨] How to use with Latest FastAPI version

With the latest FastAPI version, on_event lifespan functions are depreceated. Here is the official doc. We need to make use of asynccontextmanager with the latest fastapi.

Here is an example how to use lifespan (Repeated Tasks) functions with latest fastapi:

from fastapi import FastAPI
from contextlib import asynccontextmanager
from fastapi_utilities.repeat import repeat_every, repeat_at

@asynccontextmanager
async def lifespan(app: FastAPI):
    # --- startup ---
    await test()
    test2()
    yield
    # --- shutdown ---

app = FastAPI(lifespan=lifespan)

# Repeat Every Example
@repeat_every(seconds=2)
async def test():
    print("test")

# Repeat At Example
@repeat_at(cron="* * * * *")
def test2():
    print("test2")

Only difference is to call our tasks from lifespan function instead of using on_event function.

codecov[bot] commented 8 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 75.92%. Comparing base (a427dfe) to head (d27cafd).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #15 +/- ## ======================================= Coverage 75.92% 75.92% ======================================= Files 9 9 Lines 162 162 ======================================= Hits 123 123 Misses 39 39 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.