Giter Club home page Giter Club logo

Comments (2)

peterschutt avatar peterschutt commented on June 11, 2024

Here's an MVCE:

"""Minimal Litestar application."""
from asyncio import sleep
from typing import Any, AsyncGenerator

from litestar import Litestar, get
from litestar.di import Provide


async def dep() -> AsyncGenerator[float, None]:
    yield 0.1


@get("/async", dependencies={"sleep_for": Provide(dep)})
async def async_hello_world(sleep_for: AsyncGenerator[float, None]) -> dict[str, Any]:
    """Route Handler that outputs hello world."""
    await sleep(next(sleep_for))
    return {"hello": "world"}


app = Litestar(route_handlers=[async_hello_world])
(.venv) peter@peter-Inspiron-15-5510:~/PycharmProjects/mypy-test$ litestar run
/home/peter/PycharmProjects/mypy-test/app.py:13: LitestarWarning: Use of a synchronous callable <function dep at 0x7f7b671e5580> without setting sync_to_thread is discouraged since synchronous callables can block the main thread if they perform blocking operations. If the callable is guaranteed to be non-blocking, you can set sync_to_thread=False to skip this warning, or set the environmentvariable LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD=0 to disable warnings of this type entirely.
  @get("/async", dependencies={"sleep_for": Provide(dep)})
Using Litestar app from app:app
┌──────────────────┬──────────────────────┐
│ Litestar version │ 2.0.0                │
│ Debug mode       │ Disabled             │
│ CORS             │ Disabled             │
│ CSRF             │ Disabled             │
│ OpenAPI          │ Enabled path=/schema │
│ Compression      │ Disabled             │
└──────────────────┴──────────────────────┘
Starting server process ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/home/peter/PycharmProjects/mypy-test/app.py:13: LitestarWarning: Use of a synchronous callable <function dep at 0x7f3b3b0e9260> without setting sync_to_thread is discouraged since synchronous callables can block the main thread if they perform blocking operations. If the callable is guaranteed to be non-blocking, you can set sync_to_thread=False to skip this warning, or set the environmentvariable LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD=0 to disable warnings of this type entirely.
  @get("/async", dependencies={"sleep_for": Provide(dep)})
INFO:     Started server process [287567]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

If the dependency doesn't return an async generator, e.g., just returns the float directly, then it is not an issue.

from litestar.

peterschutt avatar peterschutt commented on June 11, 2024

Technically, the framework isn't wrong here.

asyncio REPL 3.8.15 (default, Oct 17 2022, 12:54:29) 
[GCC 9.4.0] on linux
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> async def g():
...   print("in")
...   yield 1
... 
>>> g()  # when called there is no execution
<async_generator object g at 0x7f09cc83da60>
>>> async for _ in g(): ...  # no execution until iterated, which would always be after injection
... 
in
Ellipsis

Notice that when the async generator is instantiated, nothing is executed, and you cannot await g() - it is an error. So litestar has to call this as a sync callable, not an async callable, and so technically the warning holds. As nothing is executed, this dependency should be set sync_to_thread=False, however given that nothing is ever executed when calling a generator function, we should never really need to run that call in a thread anyway, meaning that the warning is a bit redundant. Also, if you set sync_to_thread=True then it will get put into a thread with the current configuration.

from litestar.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.