Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 19, 2021 05:46 am GMT

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

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To