httpx.ResponseNotRead: Attempted to access streaming response content, without having called read()
.
#1856
-
Hello. I've found an issue in The issue related to non-streaming responses, if an event hook raised an error the method To reproduce the issue I've created test project
from fastapi import FastAPI, responses
import httpx
import uvicorn
app = FastAPI()
async def hook(response: httpx.Response) -> None:
response.raise_for_status()
@app.get('/endpoint')
async def endpoint() -> responses.JSONResponse:
async with httpx.AsyncClient(event_hooks={'response': [hook]}, timeout=httpx.Timeout(30)) as client:
try:
await client.get('https://api.amazon.com/auth/o2/token')
except httpx.HTTPStatusError as e:
return responses.JSONResponse(status_code=400, content={'status': 'error', 'detail': e.response.text})
return responses.JSONResponse(content={'status': 'ok'})
if __name__ == '__main__':
uvicorn.run('main:app', reload=True)
import httpx
def call() -> None:
res = httpx.get('http://127.0.0.1:8000/endpoint')
print(res.text)
if __name__ == '__main__':
call() run
I've also created an issue in respx repo as I thought it's related to test library, but it is reproducing without mocking responses. Stacktrace:
PS: Thanks @lundberg for the investigation :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
So... reading through the issue you raised against Instead you'd need to change your event hook, so that if it raises an exception, it reads the request body first... async def hook(response: httpx.Response) -> None:
if response.is_error:
await response.aread()
response.raise_for_status() |
Beta Was this translation helpful? Give feedback.
So... reading through the issue you raised against
respx
it looks to me that @lundberg has correctly identified what you need to change in your codebase, except that you can't change it in your endpoint handling (because the response is already closed by that point).Instead you'd need to change your event hook, so that if it raises an exception, it reads the request body first...