본문 바로가기

Fastapi

내맘대로 Fastapi Document summary[7]

 

A "middleware" is a function that works with every request before it is processed by 
any specific path operation. And also with every response before returning it.

If you have dependencies with yield, the exit code will run after the middleware.

If there were any background tasks (documented later), they will run after all the middleware.

 

 

from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response
    
# A function call_next that will receive the request as a parameter.
# This function will pass the request to the corresponding path operation.
# Then it returns the response generated by the corresponding path operation.
# You can then modify further the response before returning it.
# Have in mind that custom proprietary headers can be added using the 'X-' prefix

 

 

CORS or "Cross-Origin Resource Sharing" refers to the situations when a frontend
running in a browser has JavaScript code that communicates with a backend, and the backend 
is in a different "origin" than the frontend.

An origin is the combination of protocol (http, https), domain (myapp.com, localhost, 
localhost.tiangolo.com), and port (80, 443, 8080).

So, all these are different origins:
-http://localhost
-https://localhost
-http://localhost:8080

backend는 list "allowed origins"를 가지고 있어야한다.
*(wildcards)는 모든 origin을 허용하지만 bearer token을 가지는 Cookies, Authorization header
통신은 제한.

 

 

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins, # ['*'] to allow any origin
    allow_origin_regex=['https://.*\.example\.org']
    allow_credentials=True, # cookies should be supported for cross-origin requests. Defaults to False
    allow_methods=["*"], # default ['GET']
    allow_headers=["*"], # Defaults to [], Accept, Accept-Language, Content-Language and
                         # Content-Type headers are always allowed for CORS requests.
)

@app.get("/")
async def main():
    return {"message": "Hello World"}