使用类为API创建python包装器

时间:2015-07-19 18:51:10

标签: python json api wrapper

我正在尝试为API创建一个Python包装器。我已经能够创建工作正常但不使用类的脚本。我想使用类来创建该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响应。

谢谢!

1 个答案:

答案 0 :(得分: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