简体   繁体   English

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

[英]convert requests response json into python class object

Hi i'm writing a python API wrapper for Pexels API, I have API response as follow:嗨,我正在为 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"
}

I wanted each of the things in the response to be accessed as class object so tried to make separate custom object, my types.py我希望响应中的每一件事都作为类对象进行访问,因此尝试制作单独的自定义对象,即我的types.py

but i can't access objects like photos 1 .alt但我无法访问像照片1 .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)

In your SearchResponse code, photos is a list of dictionary and not a list of Photo instance.在您的 SearchResponse 代码中,照片是字典列表而不是照片实例列表。 Try using a list comp to instantiate multiple Photo instance尝试使用列表组合来实例化多个照片实例

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

you can then access the alt of an instance like this然后,您可以像这样访问实例的 alt

photo[0].alt

The full class definition完整的类定义

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

The only change is self.photos唯一的变化是 self.photos

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM