Birmingham-mumbai


yield 'data: {}\n\n.format(



tải về 6.62 Mb.
Chế độ xem pdf
trang274/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

yield 'data: {}\n\n.format(
json.dumps(jsonable_encoder(q), 
cls=MyJSONEncoder))
await asyncio.sleep(1)
return 
StreamingResponse(print_questions(),
media_type="text/event-stream")
• Services that render images can also use the 
StreamingResponse
type. The following 
logo_upload_png()
service uploads any 
JPEG
or 
PNG
file and renders it in the browser:
@router.post("/restaurant/upload/logo")
async def logo_upload_png(
logo: UploadFile = File(...)
):
original_image = Image.open(logo.file)
original_image = 
original_image.filter(ImageFilter.SHARPEN)
filtered_image = BytesIO()
if logo.content_type == "image/png":
original_image.save(filtered_image, "PNG")
filtered_image.seek(0)
return 
StreamingResponse(filtered_image, 
media_type="image/png")
elif logo.content_type == "image/jpeg":
original_image.save(filtered_image, "JPEG")
filtered_image.seek(0)
return 
StreamingResponse(filtered_image,


Utilizing Other Advanced Features
304
media_type="image/jpeg") 
• The 
StreamingResponse
type is also effective in rendering videos in various formats such 
as 
MP4
. The following service reads a file inside the application named 
sample.mp4
and 
publishes it to the browser:
@router.get("/restaurant/upload/video")
def video_presentation():
file_path = os.getcwd() + '\\files\\sample.mp4'
def load_file():
with open(file_path, mode="rb") as video_file:
yield from video_file
return 
StreamingResponse(load_file(),
media_type="video/mp4")
• If the service wants to publish a simple HTML markup page without making references to static 
CSS or JavaScript files, then 
HTMLResponse
is the right choice. The following service renders 
an HTML page with a Bootstrap framework provided by some CDN libraries:

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