Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How get application state in periodic task? #259

Closed
Korolev-Oleg opened this issue Aug 6, 2022 · 2 comments
Closed

How get application state in periodic task? #259

Korolev-Oleg opened this issue Aug 6, 2022 · 2 comments
Labels
question Further information is requested

Comments

@Korolev-Oleg
Copy link

I need to get app.state to retrieve the Postgres pool driver in my periodic task.
Because task repeating every 5 sec.

How can I do this with the fastapi routing case (when app.state is available only in request object)?

In this example, I'm forced to create gspread and asyncpg connections every 5 seconds this is a terrible decision.

@Korolev-Oleg Korolev-Oleg added the question Further information is requested label Aug 6, 2022
@Korolev-Oleg
Copy link
Author

solution for synchronous tasks:
using a lambda fundus, you can pass an application object into a recurring task bypassing the limit of fastapi_utils.tasks.NoArgsNoReturnFuncT

import fastapi_utils.tasks
from fastapi import FastAPI

import main_tasks

app = FastAPI()
app.state.db = 'database pool'
app.on_event('startup')(
    fastapi_utils.tasks.repeat_every(seconds=5)(lambda: main_tasks.task(app))
)

@Korolev-Oleg
Copy link
Author

solution asynchronous tasks:
you need recreate and modify fastapi_utils.tasks.repeat_every.py
https://github.com/dmontagu/fastapi-utils/blob/master/fastapi_utils/tasks.py#L47

def decorator(
        func: Union[NoArgsNoReturnAsyncFuncT, NoArgsNoReturnFuncT],
        *args,
        **kwargs
    ) -> NoArgsNoReturnAsyncFuncT:

https://github.com/dmontagu/fastapi-utils/blob/master/fastapi_utils/tasks.py#L64

await func(*args, **kwargs)  # type: ignore

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant