Comments (2)
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.
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)
- Bug: New `create_static_files_router` automatically adds routes to schema docs HOT 4
- Enhancement: exclude default from reprs of some dataclass types HOT 1
- Enhancement(v3): Replace config objects with plugins
- Bug:AttributeError: module 'pydantic._migration' has no attribute 'JsonValue' HOT 5
- Enhancement: SQLAdmin Support HOT 5
- Bug: Using asyncio.create_subprocess_shell / _exec in lifespan raises NotImplementedError HOT 3
- Bug: Parsing tagged unions HOT 1
- Bug: Exception not handled correctly HOT 1
- bug: CORS middleware not working with mounted applications HOT 1
- refactor: deprecate CORSMiddleware from public interface HOT 1
- Bug: cant upload one file only if type is list[UploadFile] | None HOT 3
- Bug: can't upload multiple files where `data: Optional[List[UploadFile]]` HOT 1
- Bug: `| None` removes the `Upload File` button in OpenAPI schema docs
- Enhancement(Packaging): Add/Maintain Debian package HOT 1
- Bug: minijinja import too early on FlashPlugin HOT 2
- Bug: ResponseHeaders results in invalid OpenAPI schema HOT 3
- NameError when `litestar.types.Guard` is used in the function parameter HOT 2
- Enhancement: Support RSGI Specification (granian) HOT 4
- Bug: StructlogPlugin loggers do not adhere to set log level HOT 2
- Bug: Different behavior for generating openapi schema names HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from litestar.