Using custom state class does not update state? #1156
Replies: 5 comments
-
from starlite import Starlite, State, get, TestClient
class MyState(State):
count: int = 0
def increment(self) -> None:
self.count += 1
@get("/")
def handler(state: MyState) -> dict:
state.increment()
return state.dict()
app = Starlite(route_handlers=[handler])
with TestClient(app=app) as client:
print(client.get("/").json()) For me, this prints |
Beta Was this translation helpful? Give feedback.
-
I get also |
Beta Was this translation helpful? Give feedback.
-
Okay so, first of all: The example is wrong and your assumption is correct. That's what should happen, but it can't, since this isn't how Subclassing from starlite import Starlite, State, get, TestClient
class MyState(State):
count: int
def increment(self) -> None:
self.count += 1
@get("/")
def handler(state: MyState) -> dict:
state.increment()
return state.dict()
app = Starlite(route_handlers=[handler])
with TestClient(app=app) as client:
print(client.get("/").json()) # {'status_code': 500, 'detail': 'AttributeError()'} This will return an error. from starlite import Starlite, State, TestClient, get
class MyState(State):
count: int
def increment(self) -> None:
if not hasattr(self, "count"):
self.count = 0
self.count += 1
@get("/")
def handler(state: MyState) -> dict:
state.increment()
return state.dict()
app = Starlite(route_handlers=[handler])
with TestClient(app=app) as client:
client.get("/")
print(client.get("/").json()) # {'count': 2} or implement it the way it's intended, using from starlite import Starlite, State, get, TestClient
class MyState(State):
count: int
def increment(self) -> None:
self.count += 1
@get("/")
def handler(state: MyState) -> dict:
state.increment()
return state.dict()
app = Starlite(route_handlers=[handler], initial_state={"count": 0})
with TestClient(app=app) as client:
client.get("/")
print(client.get("/").json()) # {'count': 2} Conclusion
Open questions Should we maybe support setting default values in such a way? We could maybe combine this with the generic state we added to |
Beta Was this translation helpful? Give feedback.
-
Thanks for your help! It works now. I think it would be nice to be able to set your custom State in the class. |
Beta Was this translation helpful? Give feedback.
-
So, I don't think we can actually do this. The state injected in the above examples is not the request state but rather the application state. We cannot set defaults without affecting the shared state. |
Beta Was this translation helpful? Give feedback.
-
Hi, using the example from the docs on how to use custom state does not increment the value:
What am I missing?
Beta Was this translation helpful? Give feedback.
All reactions