Skip to content

Discussion: Async support for the client sdk #4

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

Closed
dbkegley opened this issue Jan 24, 2024 · 1 comment
Closed

Discussion: Async support for the client sdk #4

dbkegley opened this issue Jan 24, 2024 · 1 comment

Comments

@dbkegley
Copy link
Collaborator

Continuing the discussion from this thread

This comment in the fastapi project describes the problem pretty succinctly.

It sounds like calling any blocking code from an async endpoint will block the main thread.

@tdstein
Copy link
Collaborator

tdstein commented Jan 25, 2024

I've been experimenting...

If you invoke a synchronous method within a ThreadPoolExecutor, it doesn't block the main thread.

import asyncio

from concurrent.futures import ThreadPoolExecutor
from posit.client import Client

async def my_async_method():
    # Your asynchronous code here
    print("Async method started")
    await asyncio.sleep(1)
    print("Async method completed")


def sync_method():
    # Your synchronous code here
    print("Sync method started")
    client = Client()
    res = client.users.get_current_user()
    print(res.json())
    print("Sync method completed")


async def main():
    loop = asyncio.get_event_loop()

    # Create a ThreadPoolExecutor
    executor = ThreadPoolExecutor()

    # Run the synchronous method outside a thread pool
    # This blocks...
    sync_method()

    # Run the synchronous method in the thread pool
    # Don't await yet
    fn = loop.run_in_executor(executor, sync_method)

    # Run the asynchronous method
    await my_async_method()
    await fn


if __name__ == "__main__":
    asyncio.run(main())
Sync method started
{'email': '[email protected]', ...
Sync method completed
Sync method started
Async method started
{'email': '[email protected]', ...
Sync method completed
Async method completed

@tdstein tdstein modified the milestone: 0.1.0 Feb 20, 2024
@tdstein tdstein closed this as not planned Won't fix, can't repro, duplicate, stale Feb 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants