starlette

Merge dict header to request.headers.raw

Merge dict header to request.headers.raw Question: headers.raw is typing.List[typing.Tuple[bytes, bytes]] I want to merge it into another dict, like the one below: client.build_request(headers=dict(request.headers.raw) | {"foo": "bar"}), However I got the error expected "Union[Headers, Dict[str, str], Dict[bytes, bytes], Sequence[Tuple[str, str]], Sequence[Tuple[bytes, bytes]], None]" Is there some way to do this? I am using Python 3.10, and …

Total answers: 1

Starlette catch all routes and http methods

Starlette catch all routes and http methods Question: I want to make my function proxy accepts ALL paths and all HTTP methods, everything that hits the Starlette app I want to proxy function handles it. async def proxy(request: Request): pass routes = [ Route("/", endpoint=proxy), ] app = Starlette(routes=routes) I tried the code above, but …

Total answers: 1

FastAPI – How can I modify request from inside dependency?

FastAPI – How can I modify request from inside dependency? Question: How can I modify request from inside a dependency? Basically I would like to add some information (test_value) to the request and later be able to get it from the view function (in my case root() function). Below is a simple example: from fastapi …

Total answers: 1

How to create a FastAPI endpoint that can accept either Form or JSON body?

How to create a FastAPI endpoint that can accept either Form or JSON body? Question: I would like to create an endpoint in FastAPI that might receive (multipart) Form data or JSON body. Is there a way I can make such an endpoint accept either, or detect which type of data is receiving? Asked By: …

Total answers: 1

How to render CSS/JS/Images along with HTML file in FastAPI?

How to render CSS/JS/Images along with HTML file in FastAPI? Question: I am facing an issue while rendering the HTMl file in FastAPI. main.py file static_dir = os.path.join(os.path.dirname(__file__), "static") app.mount("/",StaticFiles(directory=static_dir, html=True),name="static") @app.get("/") async def index(): return FileResponse(‘index.html’, media_type=’text/html’) While running the above file using uvicorn I am able to render the HTML file at http://127.0.0.1:8765/, …

Total answers: 1

Can't get variable from session using SessionMiddleware in FastAPI

Can't get variable from session using SessionMiddleware in FastAPI Question: I am trying to make a primitive authorization by session, here is a sample code import uvicorn from fastapi import FastAPI, Request from starlette.middleware.sessions import SessionMiddleware app = FastAPI() app.add_middleware(SessionMiddleware, secret_key="some-random-string", max_age=0) @app.get("/a") async def session_set(request: Request): request.session["my_var"] = "1234" return ‘ok’ @app.get("/b") async def …

Total answers: 1

How to replace hyperlinks in StreamingResponse?

How to replace hyperlinks in StreamingResponse? Question: Is that possible to replace hyperlinks in StreamingResponse? I’m using below code to stream HTML content. from starlette.requests import Request from starlette.responses import StreamingResponse from starlette.background import BackgroundTask import httpx client = httpx.AsyncClient(base_url="http://containername:7800/") async def _reverse_proxy(request: Request): url = httpx.URL(path=request.url.path, query=request.url.query.encode("utf-8")) rp_req = client.build_request( request.method, url, headers=request.headers.raw, content=await …

Total answers: 1

How to stream HTML content with static files using FastAPI?

How to stream HTML content with static files using FastAPI? Question: Question How to stream an HTML page with static files and hyperlinks from another service using FastAPI? Additional Context A common architecture in micro-services is to have a gateway layer that implements a public API that passes requests to micro-services. =============== Docker Network ============= …

Total answers: 1

How to download a large file using FastAPI?

How to download a large file using FastAPI? Question: I am trying to download a large file (.tar.gz) from FastAPI backend. On server side, I simply validate the filepath, and I then use Starlette.FileResponse to return the whole fileā€”just like what I’ve seen in many related questions on StackOverflow. Server side: return FileResponse(path=file_name, media_type=’application/octet-stream’, filename=file_name) …

Total answers: 1

How to add background tasks when request fails and HTTPException is raised in FastAPI?

How to add background tasks when request fails and HTTPException is raised in FastAPI? Question: I was trying to generate logs when an exception occurs in my FastAPI endpoint using a Background task as: from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(message=""): with open("log.txt", mode="w") as email_file: content = f"{message}" email_file.write(content) @app.post("/send-notification/{email}") async …

Total answers: 1