4

In Flask, the request is available to any function that's down the call-path, so it doesn't have to be passed explicitly.

Is there anything similar in FastAPI?

Basically, I want to allow, within the same app, a request to be "real" or "dummy", where the dummy will not actually carry out some actions, just emit them (yes, I know that checking it down the stack is not nice, but I don't have control over all the code).

let's say I have

@app.post("/someurl")
def my_response():
  func1()

def func1():
  func2()

def func2():
  # access some part of the request

I.e. where I don't need to pass the request as a param all the way down to func2.

In Flask, I'd just access the request directly, but I don't know how to do it in FastAPI. For example, in Flask I could do

def func2():
 x = request.my_variable
 # do somethinh with x

Request here is local to the specific URL call, so if there are two concurrent execution of the func2 (with whatever URL), they will get the correct request.

vlade
  • 93
  • 1
  • 7

2 Answers2

1

FastAPI uses Starlette for this.

(Code from docs)

from fastapi import FastAPI, Request


app = FastAPI()


@app.get("/items/{item_id}")

def read_root(item_id: str, request: Request):

    client_host = request.client.host

    return {"client_host": client_host, "item_id": item_id}

Reference:

Using Request Directly

Edit:

I do not think this is something FastAPI provides out of the box. Starlette also doesn't seem to, but there is this project which adds context middleware to Starlette which should be easy to integrate into a FastAPI app.

Starlette Context

im_baby
  • 912
  • 1
  • 8
  • 14
  • 2
    I know I can access the request directly, but in Flask I can access it anywhere in the call stack w/o passing it explicitly as a parameter i.e. https://flask.palletsprojects.com/en/1.1.x/reqcontext/ I've updated the question to make this explicit. – vlade Mar 22 '21 at 14:37
0

I provided an answer that may be of help, here. It leverages ContextVars and Starlette middleware (used in FastAPI) to make request object information globally available. It doesn't make the entire request object globally available -- but if you have some specific data you need from the request object, this solution may help!

Klutch27
  • 167
  • 2
  • 9
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/late-answers/32047185) – Mitja Jun 23 '22 at 11:20