2

我在 json 文件中有一个所有类型为字符串的游戏列表,我的目标是过滤这些游戏以向 Gnip API 发出许多请求。但是当我提出请求时出现此错误:

Traceback (most recent call last):
  File "GetRequest.py", line 53, in <module>
    the_page = json.load(response)
NameError: name 'response' is not defined

这是我的代码:

#!/usr/bin/env python

import urllib2
import base64
import json


class RequestWithMethod(urllib2.Request):
    def __init__(self, url, method, headers={}):
        self._method = method
        urllib2.Request.__init__(self, url, headers)

    def get_method(self):
        if self._method:
            return self._method
        else:
            return urllib2.Request.get_method(self)


if __name__ == "__main__":
    data = json.load(open('games.json'))


    url = 'url'
    UN = 'Username'
    PWD = 'Password'
    query = data[1].encode("UTF8")
    fromDate = '201803010000'
    toDate = '201803140000'


    queryString = (url + "?query={}" + "&fromDate=" + fromDate + "&toDate=" + toDate).format(query)

    base64string = base64.encodestring('%s:%s' % (UN, PWD)).replace('\n', '')

    req = RequestWithMethod(queryString, 'GET')
    req.add_header("Authorization", "Basic %s" % base64string)

    try:
        response = urllib2.urlopen(req)
    except urllib2.HTTPError as e:
        print e.read()

    the_page = json.load(response)
    print the_page['results'][1]

为了安全起见,我已经切换了实际的密码、用户名和 url。

4

0 回答 0