An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
August 19, 2021 05:46 am GMT
Original Link: https://dev.to/nelsoncode/how-to-create-middlewares-with-fastapi-1pn8
How to create Middlewares with FastAPI
how do i add custom middleware?
from fastapi import FastAPI, Requestfrom starlette.responses import JSONResponse, Responseapp = 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
- CORShttps://fastapi.tiangolo.com/tutorial/cors/
- GZIPhttps://fastapi.tiangolo.com/advanced/middleware/#gzipmiddleware
- HTTPSREDIRECT https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
- TRUSTEDHOSThttps://fastapi.tiangolo.com/advanced/middleware/#trustedhostmiddleware
How to add CORS with FastAPI ?
from fastapi import FastAPI, Requestfrom starlette.responses import Responsefrom fastapi.middleware.wsgi import CORSMiddlewareapp = FastAPI()app.add_middleware( CORSMiddleware, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)@app.get('/')def index(request: Request, response: Response): return {'message': 'ok'}
Original Link: https://dev.to/nelsoncode/how-to-create-middlewares-with-fastapi-1pn8
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To