You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

marvel.py 4.5 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import abc
  2. import hashlib
  3. import json
  4. import shutil
  5. import time
  6. import urllib.parse
  7. import urllib.request
  8. import textwrap
  9. import sys
  10. class Authorization:
  11. def __init__(self, filename):
  12. with open(filename, "r") as file:
  13. lines = file.readlines()
  14. if len(lines) != 2:
  15. sys.exit("Incorrect api-keys file")
  16. self.public_key = lines[0].strip()
  17. self.private_key = lines[1].strip()
  18. def generate_params(self):
  19. params = dict()
  20. params["apikey"] = self.public_key
  21. ts = str(time.time())
  22. to_hash = ts + self.private_key + self.public_key
  23. hasher = hashlib.md5()
  24. hasher.update(to_hash.encode())
  25. digest = hasher.hexdigest()
  26. params["ts"] = ts
  27. params["hash"] = digest
  28. return params
  29. class Client:
  30. base_url = "http://gateway.marvel.com/v1/public"
  31. def __init__(self, auth):
  32. self.auth = auth
  33. def make_request(self, query):
  34. params = self.auth.generate_params()
  35. params.update(query.params())
  36. url = Client.base_url + query.path()
  37. url_query = urllib.parse.urlencode(params)
  38. full_url = url + "?" + url_query
  39. with urllib.request.urlopen(full_url) as response:
  40. status_code = response.getcode()
  41. if status_code != 200:
  42. sys.exit("got status: " + str(status_code))
  43. body = json.loads(response.read())
  44. attribution = body["attributionText"]
  45. response = query.extract(body)
  46. return (response, attribution)
  47. class Display:
  48. def __init__(self, width=80):
  49. self.width = width
  50. def display(self, text):
  51. print("\n".join(textwrap.wrap(text, width=self.width)))
  52. class Query(metaclass=abc.ABCMeta):
  53. @abc.abstractmethod
  54. def params(self):
  55. pass
  56. @abc.abstractmethod
  57. def path(self):
  58. pass
  59. @abc.abstractmethod
  60. def extract(self, body):
  61. pass
  62. @abc.abstractmethod
  63. def text(self, response):
  64. pass
  65. class CharacterDescription(Query):
  66. def __init__(self, name):
  67. self.name = name
  68. def get_character_description(self, name):
  69. params = {"name": name}
  70. body, attribution = self.make_request("/characters",
  71. params)
  72. first_result = body["data"]["results"][0]
  73. description = first_result["description"]
  74. return (description, attribution)
  75. def params(self):
  76. return {"name": self.name}
  77. def path(self):
  78. return "/characters"
  79. def extract(self, body):
  80. first_result = body["data"]["results"][0]
  81. description = first_result["description"]
  82. return description
  83. def text(self, response):
  84. return response
  85. class CreatorNumberOfSeries(Query):
  86. def __init__(self, first_name, last_name):
  87. self.first_name = first_name
  88. self.last_name = last_name
  89. def get_number_of_series(self, first_name, last_name):
  90. params = {
  91. "firstName": first_name,
  92. "lastName": last_name,
  93. }
  94. body, attribution = self.make_request("/creators",
  95. params)
  96. first_result = body["data"]["results"][0]
  97. return (first_result["series"]["available"], attribution)
  98. def params(self):
  99. return { "firstName": self.first_name, "lastName": self.last_name }
  100. def path(self):
  101. return "/creators"
  102. def extract(self, body):
  103. first_result = body["data"]["results"][0]
  104. return first_result["series"]["available"]
  105. def text(self, response):
  106. return "{} {} worked on {} series".format(
  107. self.first_name,
  108. self.last_name,
  109. response
  110. )
  111. def main():
  112. auth = Authorization("api-keys.txt")
  113. query_type = sys.argv[1]
  114. if query_type == "character-description":
  115. name = sys.argv[2]
  116. query = CharacterDescription(name)
  117. elif query_type == "creator-number-of-series":
  118. first_name = sys.argv[2]
  119. last_name = sys.argv[3]
  120. query = CreatorNumberOfSeries(first_name, last_name)
  121. else:
  122. sys.exit("Unkwnon query type: {}".format(query_type))
  123. client = Client(auth)
  124. response,attribution = client.make_request(query)
  125. text = query.text(response)
  126. terminal_size = shutil.get_terminal_size()
  127. columns = terminal_size.columns
  128. terminal = Display(width=columns)
  129. terminal.display(text)
  130. terminal.display("---")
  131. terminal.display(attribution)
  132. if __name__ == "__main__":
  133. main()