2014-11-25 74 views
1

我使用Google DFP API來收集點擊我們網站上的廣告的一些統計數據。代碼是用Python編寫的。目前,我想升級的代碼使用OAuth 2
因爲,代碼每天自動運行,無需任何用戶參與,我在我的谷歌項目創建一個
服務帳戶和添加的帳戶使用DoubleClick for
出版商我們公司的網絡。基於WEB的樣本代碼,我寫了這個:在Python中使用服務帳戶創建DfpClient

import httplib2 
from oauth2client.client import SignedJwtAssertionCredentials 
from apiclient.discovery import build 
from googleads.dfp import DfpClient 

GOOGLE_DFP_SCOPE="https://www.googleapis.com/auth/dfp" 
API_VERSION="v201411" 
KEY_FILE="*******.p12" 
ACCT_EMAIL="************************@developer.gserviceaccount.com" 
NETWORK_CODE="**********" 
with open(KEY_FILE) as config_file: 
    my_private_key = config_file.read() 
credentials = SignedJwtAssertionCredentials(service_account_name=ACCT_EMAIL, private_key=my_private_key,scope=GOOGLE_DFP_SCOPE) 
http = httplib2.Http() 
http_auth = credentials.authorize(http) 
dfp_client = build(serviceName='dfp',version=API_VERSION,http=http_auth) 

此代碼似乎並不正確,因爲network_code未獲通過 在代碼的任何地方。另外,它失敗並顯示以下消息:

apiclient.errors.UnknownApiNameOrVersion:name:dfp version:v201411。

此外,線下:

dfp_client = DfpClient.LoadFromStorage() 

不適合我的情況下工作,因爲,這是基於googleads.yaml這似乎 只爲web應用程序賬戶的客戶端祕密進行格式化,不是P12私鑰。

有什麼建議嗎?謝謝。

回答

2

Apiclient.discovery使用默認的route來檢查服務。 但我沒有找到適用於發佈商的DoubleClick服務。

我使用此代碼與Oauth2一起使用API​​。使用Flask

import json 
import requests 
import flask 

from googleads import dfp 
from googleads import oauth2 

app = flask.Flask(__name__) 

CLIENT_ID = '' 
CLIENT_SECRET = '' # Read from a file or environmental variable in a real app 
SCOPE = 'https://www.googleapis.com/auth/dfp' 
REDIRECT_URI = '' 
APPLICATION_NAME = 'DFP API SERVICE' 
NETWORK_CODE = '' 


@app.route('/') 
def index(): 

    if 'credentials' not in flask.session: 
     return flask.redirect(flask.url_for('oauth2callback')) 
    credentials = json.loads(flask.session['credentials']) 
    if credentials['expires_in'] <= 0: 
     return flask.redirect(flask.url_for('oauth2callback')) 
    else: 
     try: 
      refresh_token = credentials['refresh_token'] 
      oauth2_client = oauth2.GoogleRefreshTokenClient(CLIENT_ID, CLIENT_SECRET, refresh_token) 
      dfp_client = dfp.DfpClient(oauth2_client, APPLICATION_NAME, NETWORK_CODE) 
      user_service = dfp_client.GetService('UserService', version='v201508') 
      user = user_service.getCurrentUser() 
      return flask.render_template('index.html', name=user['name']) 
     except: 
      flask.session.pop('credentials', None) 
      return flask.redirect(flask.url_for('oauth2callback')) 

@app.route('/oauth2callback') 
def oauth2callback(): 
    if 'code' not in flask.request.args: 
     auth_uri = ('https://accounts.google.com/o/oauth2/auth?response_type=code' 
       '&access_type=offline&client_id={}&redirect_uri={}&scope={}&').format(CLIENT_ID, REDIRECT_URI, SCOPE) 
     return flask.redirect(auth_uri) 
    else: 
     auth_code = flask.request.args.get('code') 
     data = {'code': auth_code, 
      'client_id': CLIENT_ID, 
      'client_secret': CLIENT_SECRET, 
      'redirect_uri': REDIRECT_URI, 
      'grant_type': 'authorization_code'} 
     r = requests.post('https://www.googleapis.com/oauth2/v3/token', data=data) 
     flask.session['credentials'] = r.text 
     return flask.redirect(flask.url_for('index')) 

if __name__ == '__main__': 
    import uuid 
    app.secret_key = str(uuid.uuid4()) 
    app.debug = False 
    app.run() 

我希望這可以幫助您

0

你是正確的。您在創建dfp客戶端時必須傳遞網絡代碼。版本是沒有必要的。嘗試下面的代碼在python中創建客戶端。

import os 

from googleads import oauth2 
from googleads import dfp 

def get_dfp_client(): 
    application_name = "Your application name" # from google developer console. eg: Web Client 
    network_code = ******** 
    private_key_password = 'notasecret' 
    key_file = os.path.join('path/to/p12file') 
    service_account_email = '****@***.iam.gserviceaccount.com' 
    # create oath2 client(google login) 
    oauth2_client = oauth2.GoogleServiceAccountClient(
     oauth2.GetAPIScope('dfp'), service_account_email, key_file) 

    dfp_client = dfp.DfpClient(oauth2_client, application_name, network_code) 
    return dfp_client 

client = get_dfp_client() 

Reference

,如果你需要更多的澄清,請評論。