打印 make_request 内容

-1 投票
1 回答
1331 浏览
提问于 2025-04-17 13:42
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 个回答

1

要搞清楚问题是什么,其实很难,特别是没有一个完整的、能正常工作的例子(我连主机 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 返回的对象是你期待的那种吗?内容看起来正常吗?等等。

理想情况下,这样就能解决你的问题。如果没有,至少你会有一个更具体的问题可以问,这样更有可能得到有用的答案。

撰写回答