Yandex直接Python中的API

2024-09-29 23:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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中编写上面的代码?在

非常感谢!在

嗜血的


Tags: andthetopathkey代码httpsself
1条回答
网友
1楼 · 发布于 2024-09-29 23:33:29

2func(*args)表示func(arg1, arg2, arg3, ...),如果args是{},那么它就是func(x)。在

在本例中,它应该是build_opener(YandexCertHandler()),我认为没有理由用argument list unpacking来使代码复杂化。在

3。在python3.3中,如果不使用类,我会使用requests模块:

import json
import requests

# name and path to files with the secret key and certificate
KEYFILE = '/path/to/private.key'
CERTFILE = '/path/to/cert.crt' 

# 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('utf-8')

response = requests.post(url, data=jdata, cert=(CERTFILE, KEYFILE))

print(response.content)

如果它可以工作(没有测试),它也可以在python2中工作。在

相关问题 更多 >

    热门问题