我有一个提供许多类似方法的类:
class Helper:
BASE_URL = "xxx:xxx"
@staticmethod
def get_A():
url = BASE_URL + "/a?"
resp = requests.get(url)
ret_json = json.loads(resp.content)
return [r["id"] for r in ret_json["people"]]
@staticmethod
def get_B():
url = BASE_URL + "/b/list"
resp = requests.get(url)
ret_json = json.loads(resp.content)
return {r["name"]: r["gender"] for r in ret_json["people"]}
@staticmethod
def post_C():
url = BASE_URL + "/admin/c"
resp = requests.post(url)
ret_json = json.loads(resp.content)
return ret_json["date"]
......
@staticmethod
def get_Z():
.......
如何在这些方法中重复使用url = BASE_URL + diff_url; resp = requests.get(url); ret_json = json.loads(resp.content)
部分,并让它们返回ret_json
的不同部分?或者仅保留它们原样?
如何将这些方法合并为一个,如下所示:
def get_something(*arg, **kwargs):
url = BASE_URL + ...
resp = requests.get/post(url)
ret_json = json.loads(resp.content)
return "different part of ret_json"
答案 0 :(得分:2)
使用助手功能来执行这些功能的常用功能。并使用requests.request
允许通过不同的HTTP方法进行请求。
class Helper:
BASE_URL = "xxx:xxx"
@staticmethod
def request(method, path):
url = BASE_URL + path
resp = requests.request(method, url)
return json.loads(resp.content)
@staticmethod
def get_A():
ret_json = Helper.request('GET', "/a?")
return [r["id"] for r in ret_json["people"]]
@staticmethod
def get_B():
ret_json = Helper.request('GET', "/b/list")
return {r["name"]: r["gender"] for r in ret_json["people"]}
@staticmethod
def post_C():
ret_json = Helper.request('POST', "/admin/c")
return ret_json["date"]
答案 1 :(得分:1)
您要在包含公共部分的类上创建一个方法。像这样:
class Helper:
BASE_URL = "xxx:xxx"
@staticmethod
def _base_get(suffix):
url = BASE_URL + suffix
resp = requests.get(url)
return json.loads(resp.content)
@staticmethod
def get_A():
ret_json = Helper._base_get('/a?')
return [r["id"] for r in ret_json["people"]]