This content originally appeared on DEV Community and was authored by Nelson Adonis Hernandez
¿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
- HTTPSREDIRECT https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
- TRUSTEDHOST 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'}
This content originally appeared on DEV Community and was authored by Nelson Adonis Hernandez
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
APA
MLA
Nelson Adonis Hernandez | Sciencx (2021-08-19T05:46:36+00:00) How to create Middlewares with FastAPI. Retrieved from https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/
" » How to create Middlewares with FastAPI." Nelson Adonis Hernandez | Sciencx - Thursday August 19, 2021, https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/
HARVARDNelson Adonis Hernandez | Sciencx Thursday August 19, 2021 » How to create Middlewares with FastAPI., viewed ,<https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/>
VANCOUVERNelson Adonis Hernandez | Sciencx - » How to create Middlewares with FastAPI. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/
CHICAGO" » How to create Middlewares with FastAPI." Nelson Adonis Hernandez | Sciencx - Accessed . https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/
IEEE" » How to create Middlewares with FastAPI." Nelson Adonis Hernandez | Sciencx [Online]. Available: https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/. [Accessed: ]
rf:citation » How to create Middlewares with FastAPI | Nelson Adonis Hernandez | Sciencx | https://www.scien.cx/2021/08/19/how-to-create-middlewares-with-fastapi/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.