Birmingham-mumbai


class ExtractionRequest(Request)



tải về 6.62 Mb.
Chế độ xem pdf
trang270/275
Chuyển đổi dữ liệu09.10.2023
Kích6.62 Mb.
#55278
1   ...   267   268   269   270   271   272   273   274   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

class ExtractionRequest(Request):
async def body(self):
body = await super().body()
data = ast.literal_eval(body.decode('utf-8'))
if isinstance(data, list):
sum = 0
for rate in data:
sum += rate 
average = sum / len(data)
self.state.sum = sum 
self.state.avg = average
return body 
async def form(self):
body = await super().form()
user_details = dict()
user_details['fname'] = body['firstname']
user_details['lname'] = body['lastname']
user_details['age'] = body['age']
user_details['bday'] = body['birthday']
self.session["user_details"] = user_details
return body
async def json(self):
body = await super().json()


Customizing APIRoute and Request
299
if isinstance(body, dict):
sum = 0
for rate in body.values():
sum += rate
average = sum / len(body.values())
self.state.sum = sum 
self.state.avg = average
return body
To activate this 
ExtractionRequest
, we need to set the 
route_class
of the 
APIRouter
of 
the endpoints to 
ExtractContentRoute
, as shown in the following snippet:
router = APIRouter()
router.route_class = ExtractContentRoute
There are three methods of choice to override when managing various request bodies:
• 
body()
: This manages incoming request data that is in bytes
• 
form()
: This processes incoming form data
• 
json()
: This manages incoming parsed JSON data
• 
stream()
: This accesses the body via a chunk of bytes using the 
async for
construct
All of these methods return the original request body in bytes back to the service.
In 
ExtractionRequest
, we have implemented three interface methods from the given choices to 
filter and process all incoming requests of the API endpoints defined in the 
/api/route_extract.
py
module.
The following 
create_profile()
service accepts profile data from the client and implements 
the 
ExtractContentRoute
filter, which will store all of this profile data in the dictionary using 
session handling:

tải về 6.62 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   267   268   269   270   271   272   273   274   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