Birmingham-mumbai


Customizing APIRoute and Request



tải về 6.62 Mb.
Chế độ xem pdf
trang269/275
Chuyển đổi dữ liệu09.10.2023
Kích6.62 Mb.
#55278
1   ...   265   266   267   268   269   270   271   272   ...   275
Sherwin John Tragura - Building Python Microservices with FastAPI Build secure, scalable, and structured Python microservices from design concepts to infrastructure-Packt Publishing - ebooks Account

Customizing APIRoute and Request
Middleware can process incoming 
Request
data and outgoing 
Response
objects of all API 
methods in a FastAPI application, except that it cannot manipulate the message body, attach state 
objects from the 
Request
data, or modify the response object before the client consumes it. Only 
APIRoute
and 
Request
customization can give us a full grasp of how to control the request and 
response transaction. The control might include determining whether the incoming data is a byte 
body, form, or JSON and providing an effective logging mechanism, exception handling, content 
transformation, and extraction.
Managing body, form, or JSON data
Unlike in middleware, customizing 
APIRoute
does not apply to all the API endpoints. Implementing 
APIRoute
for some 
APIRouter
will only impose new routing rules to those affected endpoints, 
while the other services can pursue the default request and response process. For instance, the 
following customization is responsible for data extraction that only applies to the endpoints of 
api.
route_extract.router
:
from fastapi.routing import APIRoute
from typing import Callable
from fastapi import Request, Response
class ExtractContentRoute(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = 
super().get_route_handler()
async def custom_route_handler(request: Request) 
-> Response:
request = ExtractionRequest(request.scope, 


Utilizing Other Advanced Features
298
request.receive)
response: Response = 
await 
original_route_handler(request)
return response
return custom_route_handler
Customizing 
APIRoute
requires the creation of a Python 
closure
that will directly manage the 
Request
and 
Response
flow from 
APIRoute
’s 
original_route_handler
. On the other 
hand, our 
ExtractContentRoute
filter uses a custom 
ExtractionRequest
that identifies 
and processes each type of incoming request data separately. The following is the implementation of 
ExtractionRequest
that will replace the default 
Request
object: 

tải về 6.62 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   265   266   267   268   269   270   271   272   ...   275




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương