python BlueKai - 用户数据API

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python BlueKai - 用户数据API相关的知识,希望对你有一定的参考价值。

import os
import sys
import urllib
import urllib2
import cookielib
import urlparse
import hashlib 
import hmac
import base64
import json
import random

headers = {"Accept":"application/json","Content-type":"application/json","User_Agent":"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5"}

# 1. Enter your BlueKai developer keys

bkuid = 'PUBLIC KEY' #Web Service User Key
bksecretkey = 'PRIVATE KEY' #Web Service Private Key

# 2.  Specify the service endpoint
#    - For GET (List) requests, add the desired sort and filter options in the query string
#    - For GET (Read), PUT or DELETE requests, append the item ID to the Url path
#     * NOTE: For the Campaign, Order, and Pixel URL APIs, insert the item ID in the query string instead of the Url path

siteID = 'ENTERSITEID' # Insert site ID

# Set ID details (only set ONE)
bkuuid = ''
puuid  = '12345.678'
idfa = ''
adid = ''

# (optional) Set pfield if setting 'puuid' - largely not needed even when PUUID is set
pfield = 'INSID'

# If using IDFA or AdID
ccode = ''

# Set phint(s) string (ensure you URL encode data within each query-string parameter (see below) - otherwise you'll get a signature mismatch)
phints = 'phint=birthyear%31990&phint=nation%3DSG'

# DO NOT EDIT BELOW THIS LINE

if bkuuid:
	id_type_string = 'userid=' + bkuuid
if puuid:
	if pfield:
		id_type_string = 'puserid=' + puuid + '&pfield=' + pfield
	else:	
		id_type_string = 'puserid=' + puuid
if idfa:
    id_type_string = 'idfa=' + idfa + "&ccode=" + ccode
if adid:
    id_type_string = 'adid=' + adid + "&ccode=" + ccode

Url = 'https://api.tags.bluekai.com/getdata/' + siteID + '/v1.2/?' + id_type_string + '&' + phints

# 3. For POST and PUT requests, uncomment the "data" variable and enter the JSON body
#data = '{"AND":[{"AND":[{"OR":[{"cat":937329}]}]}]}'

#Creating the method signature
def signatureInputBuilder(url, method, data):
    stringToSign = method
    parsedUrl = urlparse.urlparse(url)
    print parsedUrl
    stringToSign += parsedUrl.path
    
    # splitting the query into array of parameters separated by the '&' character
    #print parsedUrl.query
    qP = parsedUrl.query.split('&')
    #print qP

    if len(qP) > 0:
        for  qS in qP:
            qP2 = qS.split('=')
            #print qP2
            if len(qP2) > 1:
                stringToSign += qP2[1]
    
    #print stringToSign
    if data != None :
        stringToSign += data 
    print "\nString to be Signed:\n" + stringToSign
    
    h = hmac.new(bksecretkey, stringToSign, hashlib.sha256)

    s = base64.standard_b64encode(h.digest())
    print "\nRaw Method Signature:\n" + s 
    
    u = urllib.quote_plus(s)
    print "\nURL Encoded Method Signature (bksig):\n" + u

    newUrl = url 
    if url.find('?') == -1 :
        newUrl += '?'
    else:
        newUrl += '&'
        
    newUrl += 'bkuid=' + bkuid + '&bksig=' + u 

    return newUrl

#Generating  the method request 
def doRequest(url, method, data):
    print "\nFUNCTION CALLED : doRequest"
    try:
        cJ = cookielib.CookieJar()
        request = None
        if method == 'PUT': 
            request = urllib2.Request(url, data, headers)
            request.get_method = lambda: 'PUT'
        elif  method == 'DELETE' :
            request = urllib2.Request(url, data, headers)
            request.get_method = lambda: 'DELETE'
        elif data != None :            
            print "Calling API now..."
            request = urllib2.Request(url, data, headers)
            response = urllib2.urlopen(request)
            html = response.read()            
            print "Response received. See below:"
            print html
        else:
            print "\nCalling API now..."
            request = urllib2.Request(url, None, headers)  
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cJ))
            u = opener.open(request)
            rawData = u.read()
            print "\nResponse Code: 200"
            print "\nAPI Response:\n\n" + rawData
            return rawData

    except urllib2.HTTPError, e:
        print "\nHTTP error: %d %s" % (e.code, str(e)) 
        print "ERROR: ", e.read()
        return None
    except urllib2.URLError, e:
        print "Network error: %s" % e.reason.args[1]
        print "ERROR: ", e.read()
        return None

#4. Specify the API request method 
def main(argv=None):
    
    # Select the API Method by uncommenting the newUrl reference variable and doRequest() method
    
    # GET
    newUrl = signatureInputBuilder(Url, 'GET', None)
    print "API Call: \n" + newUrl
    doRequest(newUrl, 'GET', None)
    
    # POST
    #newUrl = signatureInputBuilder(Url, 'POST', data)
    #print "API Call: \n" + newUrl
    #doRequest(newUrl, 'POST', data)    
    
    # PUT
    #newUrl = signatureInputBuilder(Url, 'PUT', data)
    #doRequest(newUrl, 'PUT', data)
    
    #DELETE
    #newUrl = signatureInputBuilder(Url, 'DELETE', None)
    #doRequest(newUrl, 'DELETE', None)
    
    

if __name__ == "__main__":
   main()

以上是关于python BlueKai - 用户数据API的主要内容,如果未能解决你的问题,请参考以下文章

javascript BlueKai API Caller(Javascript)

javascript BlueKai CoreTag - 元数据

html 网络N - BlueKai CoreTag数据收集代码

html 网络N - BlueKai CoreTag数据收集代码(元关键字处理):GTM语法

html 优化X:BlueKai标签已加载(通过BlueKai激活'标签')

javascript BlueKai CoreTag - 付费与自然搜索