This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.

The middleware

Sometimes we need to perform the same operations on multiple routes, such as checking whether we have access or not, and we can do this through middleware, which is a function similar to the Flask request hooks. Called before the request is processed and before the response is returned.

Middleware processing logic:

  • Receive client requests
  • Perform some custom actions on the request
  • The routes passed to the application continue to process the business logic
  • Receives the response returned by the application view function
  • Customize the response
  • Returns a response

Custom middleware

Middleware can be created using the App.Middleware (” HTTP “) decorator provided with FastAPI.

Create a middleware that returns the processing time of the application:

@app.middleware("http")
async def add_process_time_header(request: Request, call_next) :
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response
Copy the code

As you can see, the middleware function needs to receive the request object and the call_next function as parameters, and then the call_NEXT function takes the request as parameters and passes it to the application to continue processing and receive the response. Response, we can operate on response, Finally return.

We can customize middleware for other functions, such as request interceptors, verifying user access rights, etc.

Use existing middleware

In addition to custom middleware, we can also use FastAPI middleware directly. We can import the defined middleware through the app.add_Middleware () operation, which takes two parameters: the first parameter is the middleware class, and the second parameter is the one to be passed to the middleware.

The following uses the HTTPSRedirectMiddleware middleware and TrustedHostMiddleware middleware as examples, where HTTPSRedirectMiddleware enforces the request protocol to be HTTPS or WSS. TrustedHostMiddleware forces requests to have the Host option set in the Header information to avoid HTTP Host Header attacks.

app.add_middleware(HTTPSRedirectMiddleware)
app.add_middleware(
    TrustedHostMiddleware, allowed_hosts=["tigeriaf.com"."*.tigeriaf.com"])Copy the code

In addition, there are several other Middleware features available in the documentation: Starlette’s Middleware Docs

Use CORSMiddleware middleware to solve cross-domain problems

Development of interface services, cross-domain problem is also a very common problem, usually our API is generally to the front end to call, but the front end and the back end may often belong to different sources, so need to do cross-domain request support, FastAPI through CORSMiddleware middleware to achieve.

origins = [
    "http://localhost"."http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],)Copy the code

CORSMiddleware middleware supports the following parameters:

  • Allow_origins: list of domain names that allow cross-domain requests
  • Allow_methods: a list of HTTP methods that allow cross-domain requests. By default, only GET is supported.[" \ * "]Indicates that all HTTP methods are allowed
  • Allow_headers: list of HTTP headers supported by cross-domain requests.[' * ']Indicates that all headers are allowed
  • Allow_credentials: Indicates whether cookies are supported in cross-domain requests. The default value is False
  • Expose_headers: Indicates the returned result headers visible to the browser. The default is[]
  • Max_age: specifies the maximum length of time for the browser to cache CORS results. The default value is 600 seconds

In short, we can achieve interceptor, permission verification and other functions flexibly and quickly through FastAPI middleware.

Original is not easy, if small partners feel helpful, please click a “like” and then go ~

Finally, thank my girlfriend for her tolerance, understanding and support in work and life!