This is the 18th day of my participation in the August Genwen Challenge.More challenges in August
Part1 background
Routing is often used in app development, for example Flask with Blueprint, Django with urls, etc., for route summary management. FastApi is no exception, with APIRouter. Today we’ll find out how APIRouter is used.
Part2 Project structure
Project directory
Templates are HTML templates, views are views (where each view has its own router), and main is the app entry, where all APIRouter is registered.
Part3 code
1 Definition and use of routers in the view
User.py in the views directory
from fastapi import FastAPI,Depends,Header,HTTPException,APIRouter from starlette.requests import Request from starlette.templating import Jinja2Templates from starlette import status import uvicorn from deta import Deta from Router = APIRouter() templates = Jinja2Templates('templates') # @router.get('/users/') def user_list(): return "this is the user" @router.get('/imgs/') def img_list(): Return "This is the picture"Copy the code
Router registration in 2main
from fastapi import Depends, FastAPI from views import UTm,openstack,user from views.utm import login_required import uvicorn < span style = "box-sizing: border-box; color: RGB (51, 51, 51); line-height: 20px; font-size: 14px! Important; word-break: break-word! Important;" prefix='/um', tags=['um'], responses={520: {"description": "I'm a user description!" }} ) @app.get("/") async def root(): return {"message": "Welcome to Applications APIRouter!" } if __name__ = = "__main__" : uvicorn. The run (= 'main: app' app, host = '127.0.0.1', the port = 8765, reload = True)Copy the code
3 Browser Access
Root routing
Um routes to users
Um Routes to imGS
4 Show the pictures
Sharp-eyed students may have noticed that the images above are displayed with text instead, so how to display the images? The answer is to use the StreamingResponse object in FastApi to respond.
@router.get('/imgs/') def img_list(): File_like = open('templates/ bidum.png ', mode="rb") return StreamingResponse(file_like, media_type="image/jpg")Copy the code
Again: localhost:8765/um/imgs/
As you can see, he has successfully displayed the image.
How about that? Easy, huh? Did you fail?
Thank you for reading, don’t forget to follow, like, comment, forward four consecutive yo!