私は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()])
ますか?
どうもありがとうございました!
アイボリック