exec不允许在函数中包含带有自由变量的嵌套函数

时间:2013-06-22 20:00:01

标签: python json base64 exec urllib2

冷杉代码:

def add_credentials(request, username, password):
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    return request


def send(options, data, cb):
    if type(data).__name__ == "function":
        cb = data
        data = None
        print "YES"
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    results = {}
    url = "http://%s:%s" % (options['host'], str(options['port']))
    url += "%s" % options['path']
    if data is not None:
        request = urllib2.Request(url, data=data)
    else:
        request = urllib2.Request(url)
    request.add_header("Content-Type", "application/json")
    if 'username' in options and "password" in options:
        add_credentials(request, options['username'], options['password'])
    request.get_method = lambda: options['method'].upper()
    content = opener.open(request)
    for get_json in content:
        results.update(json.loads(get_json))
    exec "cb(results)"

options = {"host": 'localhost', "port": 5984, "path": '/hello-world/mangos', "method": "GET"}



def cb(p):
    print p

send(options, cb, "")

我正在构建一个CouchDB客户端,问题是当我执行我的文件时出现错误:

  

SyntaxError:函数'send'中不允许使用unqualified exec   包含带有自由变量的嵌套函数

我真的不知道发生了什么,我在谷歌搜索过,似乎没有解决我的问题:/谢谢你的回答D:

0 个答案:

没有答案