0
我想爲API製作一個Python包裝器。我已經能夠創建工作正常但不使用類的腳本。我想用類來製作一個真正的API包裝器。我是Python中的OOP的新手。使用類創建API的python包裝
以下是我的嘗試,但我堅持如何將其轉換爲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響應。
謝謝!
那麼應該怎麼改寫它,這樣我可以輸入我指定的任何密鑰並獲得響應JSON,因爲它包含必須在其他API中使用的另一個密鑰? –
@AnimeshPandey,我編輯了我需要的解決方案的答案。 –
與此同時,我嘗試了另一件事情,我在'__init__'中實際上將每個鍵指定爲'self.client_id'等。並在一個單獨的功能中完成所有其他工作。我想這跟你做的一樣? –