python - 使用 Python 中的服务帐户创建 DfpClient

标签 python yaml jwt google-dfp service-accounts

我使用 Google DFP api 收集有关在我们网站上点击的广告的一些统计信息。
代码是用Python编写的。目前,我正在尝试升级代码以使用 oAuth 2。
由于代码每天都会自动运行,无需任何用户参与,因此我创建了一个
我的Google项目下的服务帐户并将该帐户添加到DoubleClick for
我们公司的出版商网络。根据网上的示例代码,我写了这样的:

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:名称:dfp 版本:v201411。

另外,下面一行:

dfp_client = DfpClient.LoadFromStorage()

不适用于我的情况,因为,这是基于 googleads.yaml 的,这似乎 仅针对具有客户端 key (而非 P12 私钥)的网络应用帐户进行格式化。

有什么建议吗?谢谢。

最佳答案

Apiclient.discovery 使用默认值 route检查服务。 但我没有找到适用于发布商的 DoubleClick 服务。

我使用此代码将 API 与 Oauth2 结合使用。使用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()

希望对你有帮助

关于python - 使用 Python 中的服务帐户创建 DfpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27117733/

相关文章:

python - 工厂中的一对一关系 - 完整性错误

Python 将奇怪的 Unicode 写入 CSV

linux - 在 YAML 文件中的特定字符串之后传递变量值

c++ - 如何在 yaml-cpp 中发出带有额外换行符的映射序列

Java 从 Keycloak 离线验证 JWT 访问 token

python - Pandas 系列的部分总和

python - 带有 asyncio 的 UDP 服务器

.net - Azure DevOps YAML - 手动还原多个项目

node.js - 使用 MEAN 堆栈编辑/更新 API 端点的访问控制/授权

node.js - 生成 GitHub 安装访问 token 时出现 PEM 错误