resp_get.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. """Github utils get HTTP response."""
  18. import copy
  19. import json
  20. from typing import Dict, List, Optional
  21. import requests
  22. class RespGet:
  23. """Get response from GitHub restful API.
  24. :param url: URL to requests GET method.
  25. :param headers: headers for HTTP requests.
  26. :param param: param for HTTP requests.
  27. """
  28. def __init__(self, url: str, headers: dict, param: Optional[dict] = None):
  29. self.url = url
  30. self.headers = headers
  31. self.param = param
  32. @staticmethod
  33. def get(url: str, headers: dict, params: Optional[dict] = None) -> Dict:
  34. """Get single response dict from HTTP requests by given condition."""
  35. resp = requests.get(url=url, headers=headers, params=params)
  36. if not resp.ok:
  37. raise ValueError("Requests error with", resp.reason)
  38. return json.loads(resp.content)
  39. def get_single(self) -> Dict:
  40. """Get single response dict from HTTP requests by given condition."""
  41. return self.get(url=self.url, headers=self.headers, params=self.param)
  42. def get_total(self) -> List[Dict]:
  43. """Get all response dict from HTTP requests by given condition.
  44. Will change page number until no data return.
  45. """
  46. total = []
  47. curr_param = copy.deepcopy(self.param)
  48. while True:
  49. curr_param["page"] = curr_param.setdefault("page", 0) + 1
  50. content_dict = self.get(
  51. url=self.url, headers=self.headers, params=curr_param
  52. )
  53. data = content_dict.get("items")
  54. if not data:
  55. return total
  56. total.extend(data)