将请求响应json转换为python类对象



嗨,我正在为Pexels API编写python API包装器,我有API响应如下:

{
"total_results": 10000,
"page": 1,
"per_page": 1,
"photos": [
{
"id": 3573351,
"width": 3066,
"height": 3968,
"url": "https://www.pexels.com/photo/trees-during-day-3573351/",
"photographer": "Lukas Rodriguez",
"photographer_url": "https://www.pexels.com/@lukas-rodriguez-1845331",
"photographer_id": 1845331,
"avg_color": "#374824",
"src": {
"original": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png",
"large2x": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"large": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&h=650&w=940",
"medium": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&h=350",
"small": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&h=130",
"portrait": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800",
"landscape": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200",
"tiny": "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=200&w=280"
},
"liked": false,
"alt": "Brown Rocks During Golden Hour"
}
],
"next_page": "https://api.pexels.com/v1/search/?page=2&per_page=1&query=nature"
}

我希望响应中的每个东西都可以作为类对象访问,因此尝试创建单独的自定义对象,my types.py

但是不能访问像photos1。alt这样的对象

my client function:

def _make_request(
self,
path: str,
method: str = "get",
**kwargs: Dict[Any, Any]
) -> Tuple[Union[Dict, str], requests.Response]:

header = {'Authorization': self._token}
req = self.session.request(method, f'{self._host}/{path}', headers=header,**kwargs)

if req.status_code in [200, 201]:
try:
return req.json(), req
except JSONDecodeError:
return req.text, req
elif req.status_code == 400:
raise PexelsError("Bad Request Caught")
else:
raise PexelsError(f"{req.status_code} : {req.reason}")

def search_photos(
self, 
query: str, 
orientation: str = "", 
size:str = "",
color: str = "",
locale: str = "",
page: int = 1,
per_page: int = 15,
**kwargs
) -> SearchResponse:

data, req = self._make_request(f"search?query={query}")
return SearchResponse(**data)

在你的SearchResponse代码中,photos是一个字典列表,而不是一个Photo实例列表。尝试使用列表比较实例化多个Photo实例

self.photo = [Photo(**p) for p in photos]

你可以像这样访问实例的Alt

photo[0].alt
完整的类定义
class SearchResponse(PexelsType):
photos = List[Photo]
"A list of `Photo` object"
page = int
"The current page number"
per_page = int
"The number of results returned with each page"
total_results = int
"The total number of results for the request"
prev_page = str
"URL for the previous page of results, if applicable"
next_page = str
"URL for the next page of results, if applicable"
def __init__(
self,
photos: List[Photo],
page: int,
per_page: int,
total_results: int,
prev_page: str = "",
next_page: str = "",
**kwargs
):
self.photos = [Photo(**photo) for photo in photos ]
self.page = page
self.per_page = per_page
self.total_results = total_results
self.prev_page = prev_page
self.next_page = next_page

唯一的变化是self.photos

最新更新