Comments (8)
I expected to get nothing here
from starlette-context.
If you got this error, it means one of three things.
- You didn't use the context middleware. My test case for that https://github.com/tomwojcik/starlette-context/blob/master/tests/test_integration/test_context_no_middleware.py In the newest version I added custom exception so it's more verbose (also now it's Runtime instead of LookupError). If you use the middleware you will receive an empty context.
- You use middleware but incorrectly. Middlewares need to be initialized in the proper order, so you can access it after it's created or before it's destroyed, which is directly related to the 3rd thing
- You try to access
context
outside of the request-response cycle. The context is destroyed when the response is created. Here is the exact place where it happens
https://github.com/tomwojcik/starlette-context/blob/master/starlette_context/middleware.py#L52
Anyway, please share the code with me. You said here's a testcase without providing a test case.
from starlette-context.
My case is third: I tried to access context outside of the request-response cycle. During another middleware install.
from starlette-context.
I've also get the third case, but i want to use context optionally, only if it already exists.
Are the any ways to check if context is already available?
from starlette-context.
- If you want to use it in another middleware, it needs to be added after the
ContextMiddleware
is added to the asgi app. For example request/response logger. - If you want to access it in a route, it will always be available as all requests that hit routes are 'past middlewares'.
- If you access it outside of the request-response cycle, it will never be available, as we use this new pythonic
ContextVar
and that's how this thing works.
I think that's the price you need to pay for using asgi apps. You can't rely on threads and that's the beauty/ugly of using async code.
Therefore, even if there is an option to check if it's available, it makes no sense to implement it as you either use it properly or not.
You can handle the exception that is raised - RuntimeError
- if you want to access it only if it's available.
from starlette-context.
Sorry if I've described not enough clearly
I want to use context in the function that may be called outside of any request.
If my function is called inside request, I want to get request-id (using your cool RequestIdPlugin) and use it somehow. However, if there is no request, and no any context - I want just to execute all my another staff, context absence is not a problem for that case.
Now I've used just try-except:
request_id is None
try:
request_id = context.data['X-Request-ID']
except RuntimeError:
pass
but I'll be glad to use any explicit check instead of catching a whole class of RuntimeErrors , like this:
request_id = None
if context_exist():
request_id = ...
from starlette-context.
I still don't understand what is the case when that'd be useful and when one might not know whether context is available or not but I will implement this. Makes sense to have it instead of try/except.
Will do that over the weekend. Thanks for reporting this feature request.
Also, I tried to mimic dict
as much as possible. The only thing you can't do with context, is unpack it with **context
, you would need to do **context.data
(same with serialization). All other dict
operations like context['X-Request-ID']
should work without accessing .data
property directly.
But whatever fits you best : )
from starlette-context.
Thank you for merging!
I'm sorry I've not implemented tests by myself, by some unknown reasons I was not successful in running tests on my machine.
Also, thank you for the package, it is as simple as useful for me:)
from starlette-context.
Related Issues (20)
- Possible to have multiple RawContextMiddlewares? HOT 3
- codecov report not being uploaded HOT 1
- Question: Can I add request-id into uvicorn.access log? HOT 2
- Can't write new plugin - plugin is not iterable HOT 4
- Testing code that relies on context vars without a full test client / app HOT 8
- Consider removing `RawContextMiddleware` and keeping only `ContextMiddleware` after resolving memory usage issue HOT 8
- How to use context in Jinja (or any other template engine)? HOT 1
- No module named '_contextvars' HOT 1
- How to get request.body from starlette-context plugin? HOT 2
- async pytests fail when using logging middleware from the examples HOT 3
- Intended behavior on BackgroundTasks HOT 2
- Improved logging HOT 4
- Can't use http middleware HOT 1
- Improving the __repr__ method of _Context HOT 2
- Properly use pyproject.toml HOT 2
- 0.3.3 does not contain the testing helper request_cycle_context HOT 2
- ContextDoesNotExistError on FastAPI Custom Exception Handler HOT 8
- Docs are outdated HOT 1
- Exceptions should inherit from Exception, not BaseException HOT 2
- bump starlette 0.23.1 -> 0.25 and other deps
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 starlette-context.