First Check
Commit to Help
Example Code
from fastapi import Depends, FastAPI,APIRouter,Request, WebSocket
def my_dependency(request: Request):
print("called_my_dependency")
request.state.my_var = "my_var"
app = FastAPI(
dependencies=[Depends(my_dependency)]
)
def get_test(request: Request):
print(request.state.my_var)
return request.state.my_var
async def ws_test(websocket: WebSocket):
print(websocket.state.my_var)
app.add_api_route('/get',get_test)
app.add_api_websocket_route('/ws',ws_test)
Description
Running the code above and sending a get request to /get yields:
$ curl 127.0.0.1:8000/get | jq
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 8 100 8 0 0 4672 0 --:--:-- --:--:-- --:--:-- 8000
"my_var"
It works fine my_dependency function runs
Trying to connect to /ws endpoint on the other hand throws an error:
$ wscat --connect 127.0.0.1:8000/ws
error: Unexpected server response: 500
From the server's output it's visible my_var can't be found because my_dependency doesn't run.
AttributeError: 'State' object has no attribute 'my_var'
I don't know if it's intended or a bug but, I would expect it to run on the websocket connection as well and be able to access the state variables on the request.
I have also tried it with APIRouter and the results are the same.
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.78.0
Python Version
Python 3.10.4
Additional Context
No response
First Check
Commit to Help
Example Code
Description
Running the code above and sending a get request to
/getyields:It works fine
my_dependencyfunction runsTrying to connect to
/wsendpoint on the other hand throws an error:From the server's output it's visible
my_varcan't be found becausemy_dependencydoesn't run.I don't know if it's intended or a bug but, I would expect it to run on the websocket connection as well and be able to access the state variables on the request.
I have also tried it with APIRouter and the results are the same.
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.78.0
Python Version
Python 3.10.4
Additional Context
No response