无法验证Google AnalyticsAPI的批量请求。
我有一个凭证.json文件,看起来像这样。
{ "type": "service_account", "project_id": "xxx", "private_key_id": "xxx", "private_key": "xxx", "client_email": "xxx", "client_id": "xxx", "client_secret":"xxx", "auth_uri": "xxx", "token_uri": "xxx", "auth_provider_x509_cert_url": "xxx", "client_x509_cert_url": "xxx" }
这是我的回调函数
def test_callback(request_id, response, exception): """Handle batched request responses.""" print request_id if exception is not None: if isinstance(exception, HttpError): message = json.loads(exception.content)['error']['message'] print ('Request %s returned API error : %s : %s ' % (request_id, exception.resp.status, message)) else: print response
这是我验证的地方
"""Init and return the Google Analytics service""" CREDS = 'credentials/google.json' scopes = ['https://www.googleapis.com/auth/analytics.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDS, scopes) http = httplib2.Http() http = credentials.authorize(http)
这是我尝试添加批量请求的地方
""" This is the function I use in a helper file. No execute on the end def ga_service_test(service, profile_id, start_date, end_date): # ensure lower case ids = "ga:" + profile_id metrics = "ga:pageviewsPerSession" return service.data().ga().get( ids=ids, start_date=start_date, end_date=end_date, metrics=metrics )""" # Build the Analytics Service Object with the authorized http object session = build('analytics', 'v3', http=http) batch = BatchHttpRequest(callback=test_callback) a_session = ga_service_test(session, a_id, yesterday.strftime('%Y-%m-%d'), i.strftime('%Y-%m-%d')) b_session = ga_service_test(session, b_id, yesterday.strftime('%Y-%m-%d'), i.strftime('%Y-%m-%d')) c_session = ga_service_test(session, c_id, yesterday.strftime('%Y-%m-%d'), i.strftime('%Y-%m-%d')) for request in [a_session, b_session, c_session]: batch.add(request) return batch.execute(http=httplib2.Http())
我继续在终端
中收到此错误Traceback (most recent call last): 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 135, in handle 15:47:09 web.1 | self.handle_request(listener, req, client, addr) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request 15:47:09 web.1 | respiter = self.wsgi(environ, resp.start_response) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ 15:47:09 web.1 | return self.wsgi_app(environ, start_response) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app 15:47:09 web.1 | response = self.make_response(self.handle_exception(e)) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception 15:47:09 web.1 | reraise(exc_type, exc_value, tb) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app 15:47:09 web.1 | response = self.full_dispatch_request() 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request 15:47:09 web.1 | rv = self.handle_user_exception(e) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 15:47:09 web.1 | reraise(exc_type, exc_value, tb) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request 15:47:09 web.1 | rv = self.dispatch_request() 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request 15:47:09 web.1 | return self.view_functions[rule.endpoint](**req.view_args) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store/application.py", line 84, in test 15:47:09 web.1 | return batch.execute(http=httplib2.Http()) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/oauth2client/util.py", line 140, in positional_wrapper 15:47:09 web.1 | return wrapped(*args, **kwargs) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/googleapiclient/http.py", line 1325, in execute 15:47:09 web.1 | self._execute(http, self._order, self._requests) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/googleapiclient/http.py", line 1249, in _execute 15:47:09 web.1 | body = self._serialize_request(request) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/googleapiclient/http.py", line 1120, in _serialize_request 15:47:09 web.1 | request.http.request.credentials.apply(headers) 15:47:09 web.1 | File "/Users/bjones/test-app-two/data-store-two/venv/lib/python2.7/site-packages/oauth2client/client.py", line 676, in apply 15:47:09 web.1 | headers['Authorization'] = 'Bearer ' + self.access_token 15:47:09 web.1 | TypeError: cannot concatenate 'str' and 'NoneType' objects
This is my full .py file. I am assuming it has something to do with my authentication process but I can't seem to figure it out. If someone could help point me in the right direction it would help.
import requests import json from flask import Flask, request, jsonify, abort, render_template import time import calendar from datetime import datetime, date, timedelta import httplib2 from apiclient.errors import HttpError from apiclient.discovery import build from apiclient.http import BatchHttpRequest from oauth2client.service_account import ServiceAccountCredentials # Helper functions from another file from utils.helpers import ga_service, get_sessions, ga_service_test, get_pageviewsPerSession, hyphendate from werkzeug.wsgi import DispatcherMiddleware app = Flask(__name__) # Uncomment the line below to turn on debugging locally app.debug = True def test_callback(request_id, response, exception): """Handle batched request responses.""" print request_id if exception is not None: if isinstance(exception, HttpError): message = json.loads(exception.content)['error']['message'] print ('Request %s returned API error : %s : %s ' % (request_id, exception.resp.status, message)) else: print response @app.route("/test") def test(): a_id = 'xxx' b_id = 'xxx' c_id = 'xxx' i = datetime.now() yesterday = date.today() start = yesterday.strftime('%Y-%m-%d') end = i.strftime('%Y-%m-%d') """Init and return the Google Analytics service""" CREDS = 'credentials/google.json' scopes = ['https://www.googleapis.com/auth/analytics.readonly'] # Retrieve existing credendials credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDS, scopes) http = httplib2.Http() http = credentials.authorize(http) # Build the Analytics Service Object with the authorized http object session = build('analytics', 'v3', http=http) batch = BatchHttpRequest(callback=test_callback) a_session = ga_service_test(session, a_id, yesterday.strftime('%Y-%m-%d'), i.strftime('%Y-%m-%d')) b_session = ga_service_test(session, b_id, yesterday.strftime('%Y-%m-%d'), i.strftime('%Y-%m-%d')) c_session = ga_service_test(session, c_id, yesterday.strftime('%Y-%m-%d'), i.strftime('%Y-%m-%d')) for request in [a_session, b_session, c_session]: batch.add(request) return batch.execute(http=httplib2.Http()) if __name__ == "__main__": DispatcherMiddleware(app)