Skip to content

Best practice when a single handler calls both async and sync functions #1066

@Toad2186

Description

@Toad2186

First check

  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.

Description

Consider something like this:

@api.get('/handler')
async def handler():
    ...
    # Slow async function
    await my_async_function()
    ....
    # Slow running sync function
    sync_function()

As written above, it'll work, but the sync function will block the async event loop. Is there any way to avoid this? If the handler is sync instead, then there's no async loop with which I can use to run the my_async_function. Is it possible to get the underlying event loop so I can run my own async function within a synchronous handler? I found a related question--is this my best bet or should I just stick with the above?
#825

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions