我对 Python 比较陌生,但是我试图了解一些可能有人可以帮助解释的中高级代码。
基本上,我正在建立一个到 Yandex.Direct(相当于俄罗斯的 Google Adwords)的 API 连接。在这里您可以找到一个 API 代码示例:http ://api.yandex.com/direct/doc/examples/python-json.xml
与服务器建立连接的实际代码如下(在 Python 2.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')
我不完全理解这段代码的以下部分:
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()])
如果有人能回答以下问题,将不胜感激:
1.上面的代码是如何一步一步工作的?例如,不同的对象如何相互作用?详细的解释会很棒!:)
2. * 在这里表示什么:urllib2.build_opener(*[YandexCertHandler()])
3.如果不使用类,如何在 Python 3.3 中编写上面的代码?
非常感谢你!
艾沃里克