【发布时间】:2015-07-19 18:51:09
【问题描述】:
我正在尝试为 API 制作 Python Wrapper。我已经能够创建运行良好但不使用类的脚本。我想使用类对该 API 进行真正的包装。我是 Python 中的 OOP 新手。
以下是我的尝试,但我不知道如何将其转换为 OO 类型。
import urllib2
from urllib import urlencode
import json
class apiclient:
def __init__(self,
request_url,
hmh_api_key,
client_id,
grant_type="password",
username="username",
password="password"):
values = {
"client_id": client_id,
"grant_type": grant_type,
"username": username,
"password": password
}
data = urlencode(values)
req = urllib2.Request(request_url, data)
req.add_header("Api-Key", api_key)
response = urllib2.urlopen(req)
response_header = response.info().dict
response_body = response.read()
json_acceptable_string = response_body.replace("'", "\"")
response_body_dict = json.loads(json_acceptable_string)
return response_body_dict ## this is the response
if __name__ == "__main__":
API_KEY = "75b5cc58a5cdc0a583f91301cefedf0c"
CLIENT_ID = "ef5f7a03-58e8-48d7-a38a-abbd2696bdb6.hmhco.com"
REQUEST_URL = "http://some.url"
client = apiclient(request_url=REQUEST_URL,
api_key=API_KEY,
client_id=CLIENT_ID)
print client
没有类,我得到的响应 JSON 为 response_body_dict,但有了类,我得到 TypeError: __init__() should return None。我应该如何开始设计我的程序。
我只展示了整个程序的一部分,还有很多类似的脚本可以向 URL 发送请求并获取 JSON 响应。
谢谢!
【问题讨论】: