我对Python还比较陌生,不过我正试着了解一些中高级代码,也许有人可以帮我解释一下。在
基本上,我正在构建一个到Yandex直接(相当于俄罗斯的谷歌广告词)。这里可以找到一个API代码示例:http://api.yandex.com/direct/doc/examples/python-json.xml
建立到服务器的连接的实际代码如下(在Python2.7中):
import json, urllib2, httplib
#name and path to files with the secret key and certificate
KEYFILE = '/path/to/private.key'
CERTFILE = '/path/to/cert.crt'
class YandexCertConnection(httplib.HTTPSConnection):
def __init__(self, host, port=None, key_file=KEYFILE, cert_file=CERTFILE, timeout=30):
httplib.HTTPSConnection.__init__(self, host, port, key_file, cert_file)
class YandexCertHandler(urllib2.HTTPSHandler):
def https_open(self, req):
return self.do_open(YandexCertConnection, req)
https_request = urllib2.AbstractHTTPHandler.do_request_
urlopener = urllib2.build_opener(*[YandexCertHandler()])
#address for sending JSON requests
url = 'https://api.direct.yandex.ru/json-api/v4/'
#input data structure (dictionary)
data = {
'method': 'GetClientInfo',
'param': ['agrom'],
'locale': 'en'
}
#convert the dictionary to JSON format and change encoding to UTF-8
jdata = json.dumps(data, ensure_ascii=False).encode('utf8')
#implement the request
response = urlopener.open(url, jdata)
#output results
print response.read().decode('utf8')
我不完全理解本规范的以下部分:
^{pr2}$希望有人能回答以下问题:
1.以上代码是如何逐步工作的?例如,不同的对象如何相互作用?详细解释太好了!:)
2.这里*表示什么:urllib2.build_opener(*[YandexCertHandler()])
3.如果不使用类,如何在Python3.3中编写上面的代码?在
非常感谢!在
嗜血的
2。},那么它就是
func(*args)
表示func(arg1, arg2, arg3, ...)
,如果args
是{func(x)
。在在本例中,它应该是
build_opener(YandexCertHandler())
,我认为没有理由用argument list unpacking来使代码复杂化。在3。在python3.3中,如果不使用类,我会使用requests模块:
如果它可以工作(没有测试),它也可以在python2中工作。在
相关问题 更多 >
编程相关推荐