打印make_request内容

时间:2013-01-25 21:27:09

标签: python python-2.x

import urllib, urllib2, json
def make_request(method, base, path, params):
    if method == 'GET':
        return json.loads(urllib2.urlopen(base+path+"?"+urllib.urlencode(params)).read())
    elif method == 'POST':
        return json.loads(urllib2.urlopen(base+path, urllib.urlencode(params)).read())
api_key = "5f1d5cb35cac44d3b"
print make_request("GET", "https://indit.ca/api/", "v1/version", {"api_key": api_key})

这组代码返回应返回版本和状态,如{status:'ok',version:'1.1.0'}

我需要添加哪些代码才能打印该响应?

1 个答案:

答案 0 :(得分:1)

如果没有complete, otherwise-working example(我甚至无法解析主机indit.ca),很难说出问题是什么,但我可以解释一下如何自行调试。逐步分解:

import urllib, urllib2, json
def make_request(method, base, path, params):
    if method == 'GET':
        url = base+path+"?"+urllib.urlencode(params)
        print 'url={}'.format(url)
        req = urllib2.urlopen(url)
        print 'req={}'.format(req)
        body = req.read()
        print 'body={}'.format(body)
        obj = json.loads(body)
        print 'obj={}'.format(obj)
        return obj
    elif method == 'POST':
        # You could do the same here, but your test only uses "GET"
        return json.loads(urllib2.urlopen(base+path, urllib.urlencode(params)).read())

api_key = "5f1d5cb35cac44d3b"
print make_request("GET", "https://indit.ca/api/", "v1/version", {"api_key": api_key})

现在你可以看到它出错了。它生成了正确的URL吗? (如果将该URL粘贴到浏览器地址栏或wgetcurl命令行会怎样?)urlopen是否会返回您期望的对象类型?身体看起来正确吗?等等。

理想情况下,这将为您解决问题。如果没有,至少你会有一个更具体的问题要问,并且更有可能得到一个有用的答案。