Python 未定义响应?获取对Gnip(Twitter企业)的请求

Python 未定义响应?获取对Gnip(Twitter企业)的请求,python,json,get,urllib2,gnip,Python,Json,Get,Urllib2,Gnip,我在json文件中有一个字符串类型的游戏列表,我的目标是过滤这些游戏,向GNIPAPI发出许多请求。但当我提出请求时,会出现以下错误: Traceback (most recent call last): File "GetRequest.py", line 53, in <module> the_page = json.load(response) NameError: name 'response' is not defined 为了安全起见,我已经关掉了实际的密码

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

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

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

将最后两行代码移到try块中。问题在于,如果存在
HTTPError
,则不会定义
response
#!/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]