¿how do i add custom middleware?
from fastapi import FastAPI, Request
from starlette.responses import JSONResponse, Response
app = FastAPI()
@app.middleware("http")
async def verify_user_agent(request: Request, call_next):
if request.headers['User-Agent'].find("Mobile") == -1:
response = await call_next(request)
return response
else:
return JSONResponse(content={
"message": "we do not allow mobiles"
}, status_code=401)
@app.get('/')
def index(request: Request, response: Response):
return {'message': 'ok'}
Default middlewares in FastAPI
- CORS https://fastapi.tiangolo.com/tutorial/cors/
- GZIP https://fastapi.tiangolo.com/advanced/middleware/#gzipmiddleware
- HTTPS REDIRECT https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
- TRUSTED HOST https://fastapi.tiangolo.com/advanced/middleware/#trustedhostmiddleware
¿How to add CORS with FastAPI ?
from fastapi import FastAPI, Request
from starlette.responses import Response
from fastapi.middleware.wsgi import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/')
def index(request: Request, response: Response):
return {'message': 'ok'}
Top comments (0)