0 Replies - 193 Views - Last Post: 14 April 2013 - 05:24 PM Rate Topic: -----

#1 aivoric  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-April 13

Yandex.Direct - API Query

Posted 14 April 2013 - 05:24 PM

Hi everyone!

I am new here and relatively new to python, however I have been trying to accomplish a complicated task. I have been stuck with the code below for a while because I don't quite understand how the urllib interacts with the httplib. Yes I have been through all the python documentation for it but still struggling to understand the presence of for example AbstractHTTPHandler. Any small explanation as to how the class constructs interact with one another would be very appreciated. Apologies for the "how does this work question" and not the "where is the error?" question :)/>

Many gigantic thanks,

Aivoric

Full code found here: http://api.yandex.co...python-json.xml

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')



Is This A Good Question/Topic? 0
  • +

Page 1 of 1