2015-07-19 51 views
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响应。

谢谢!

回答

0

你不应该从__init__函数返回的东西。

编辑:

如果你需要的价值,你应该使用response_body_dict作为一个类的成员,并从其他方法得到他:

import urllib2 
from urllib import urlencode 
import json 

class apiclient: 
    def __init__(self, 
       request_url, 
       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("'", "\"") 
     self.response_body_dict = json.loads(json_acceptable_string) 

    def get_response_body(self): 
     return self.response_body_dict 

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) 
    response = client.get_response_body() 

    print client 
+0

那么应该怎么改写它,这样我可以输入我指定的任何密钥并获得响应JSON,因为它包含必须在其他API中使用的另一个密钥? –

+0

@AnimeshPandey,我编辑了我需要的解决方案的答案。 –

+0

与此同时,我尝试了另一件事情,我在'__init__'中实际上将每个键指定为'self.client_id'等。并在一个单独的功能中完成所有其他工作。我想这跟你做的一样? –