In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use python to program private customized Response objects, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
This article is very long, but I'm sure you can do highly customized Response development efficiency after reading it.
In fastapi path operations, the following data types are usually returned directly: dict,list,Pydantic model, database model, and other data types. Fastapi automatically converts the returned data into JSON format through the jsonable_encoder function, and then transmits the JSON-compatible data content to the JSONResponse object and returns it to the end user.
But in some cases, we need to return the Response object directly in the path operation, so that we can have more operational flexibility, such as the custom Cookie information and custom header information we talked about in the previous section.
one
Response model
The Response main class from which all other Response inherits.
It receives the following parameter information:
Content-str or bytes
Status_code-HTTP status code
Headers-string dictionary
Media_type-media type. For example, "text/html"
Fastapi automatically contains Content-Length, as well as header information such as Content-Type,charset.
1.1
Return to Response
We can return Response or any of its subclasses directly. JSONResponse is actually a subclass of Response. At this time, fastapi will not do any data conversion and data verification, but will return the data directly. If we want a lot of flexibility, we can return any data type, rewrite the data declaration or data validation. You can use jsonable_encoder to convert the data into a JSON-compatible format.
# *-encoding: utf-8-*-from datetime import datetimefrom typing import Optionalfrom fastapi import FastAPIfrom fastapi.encoders import jsonable_encoderfrom fastapi.responses import JSONResponsefrom pydantic import BaseModelclass Item (BaseModel): title: str name: str description: Optional [str] = Noneapp = FastAPI () @ app.get ("/ info") def get_item (item: Item): json_compatible_item_data = jsonable_encoder (item) return JSONResponse (content=json_compatible_item_data)
1.2
Return to custom Response
We can also return custom Response
#-*-encoding: utf-8-* from fastapi import FastAPI, Responseapp = FastAPI () @ app.get ("/ get_json_info") def get_json_data (): data = {"name": "haishiniu", "address": "beijing"} return Response (content=data, media_type= "application/json")
two
Advanced Custom Response
We can also customize the return results more flexibly to meet our daily development work.
2.1
Parameter responses
We can pass a parameter responses to the path operation decorator, which receives a dictionary data, the key value is a different HTTP status code, and the content is the returned content in different cases (dictionary format). If the return contains the key value model, then it has the same effect as response_model, pointing to the Pydantic model. For the following example, when the return status code is 404, the corresponding Pydantic model is Message:
#-*-encoding: utf-8-*-from fastapi import FastAPIfrom fastapi.responses import JSONResponsefrom pydantic import BaseModelclass Item (BaseModel): id: str value: strclass Message (BaseModel): message: strapp = FastAPI () @ app.get ("/ get_info/ {item_id}", response_model=Item, responses= {404: {"model": Message}}) async def read_item (item_id: str): if item_id = "666": return {"id": "666" Value: good job! Find haishiniu "} else: return JSONResponse (status_code=404, content= {" message ":" not good! You are not find me "})
Analyzing the above example, the data model returned under normal circumstances is Item,404, and the data model returned is Message.
2.2
Different media type
The parameter responses also supports different media type.
#-*-encoding: utf-8-*-from typing import Optionalfrom fastapi import FastAPIfrom fastapi.responses import FileResponsefrom pydantic import BaseModelclass Item (BaseModel): id: str value: strapp = FastAPI () @ app.get ("/ get_info/ {item_id}", response_model=Item, responses= {200: {"content": {"image/png": {}, "description": "Return the JSON item or an image." },) async def read_item (item_id: str, img: Optional [bool] = None): if img: return FileResponse ("image.png", media_type= "image/png") else: return {"id": "888", "value": "not good to find value image/png"}
As shown above, the default media type is application/json, and image/png is also supported.
2.3
Predefined responses in parallel with custom responses
In this section, we are our custom enhanced version, which can be extended at will
From typing import Optionalfrom fastapi import FastAPIfrom fastapi.responses import FileResponsefrom pydantic import BaseModelclass Item (BaseModel): id: str value: strresponses = {404: {"description": "Item not found"}, 302: {"description": "The item was moved"}, 403: {"description": "Not enough privileges"},} app = FastAPI () @ app.get ("/ get_info/ {item_id}", response_model=Item, responses= {* * responses {"content": {"image/png": {},) async def read_item (item_id: str, img: Optional [bool] = None): if img: return FileResponse ("image.png", media_type= "image/png") else: return {"id": "foo", "value": "not good to find value image/png"} above is how to use python programming to customize private Response objects The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.