是否可以将OAUTH 2与Google Reporting API一起使用?

时间:2012-11-06 14:51:15

标签: python api oauth reporting

我目前正在使用OAuth 1进行身份验证,使用带有GData和Python的Reporting API。是否可以使用OAuth 2,我找不到这是可行的参考?

1 个答案:

答案 0 :(得分:0)

我无法找到OAuth 2和Reporting API的任何参考,但是可以通过以下GData库的示例(http://code.google.com/p/gdata-python-client/source/browse /#hg%2Fsamples%2Fapps)我能够把它拼凑在一起:

#!/usr/bin/python
import sys
import os
import time
import gdata.gauth
import gdata.client
import httplib2
import oauth2client.file
import oauth2client.tools
REPORTING_URI = 'https://www.google.com/hosted/services/v1.0/reports/ReportingData'
REPORTING_XML_TEMPLATE = '''<?xml version="1.0" encoding="UTF-8"?>
<rest xmlns="google:accounts:rest:protocol"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <type>Report</type>
    <domain>%s</domain>
    <date>%s</date>
    <page>%s</page>
    <reportType>daily</reportType>
    <reportName>%s</reportName>
</rest>'''
OAUTH2FILENAME = 'oauth_20.dat'
OAUTH2JSONFILE = 'client_secrets.json'
OAUTH2SCOPES = 'https://www.google.com/hosted/services/v1.0/reports/ReportingData'
OAUTH2USERAGENT = 'REPORTING'
CLIENTSOURCE = 'REPORTING'
MISSING_OAUTHJSON_FILE_MESSAGE = """
WARNING: Please configure OAuth 2.0

To continue you will need to populate the client_secrets.json file:

   %s

with information from the APIs Console <https://code.google.com/apis/console>.

""" % os.path.join(os.path.dirname(__file__), OAUTH2JSONFILE)

### Reporting
def RunReport (http_object, domain, report=None, date=None):
    if date is None:
        now = time.time()
        report_time = time.gmtime(now)
        date = time.strftime("%Y-%m-%d",report_time)
    if report is None:
        report='accounts'
    report_data = RequestReport(http_object,domain=domain,report=report,date=date)
    if not report_data:
        print 'No report data'
    return report_data

def RequestReport (http_object, domain=None, report=None, date=None):
    """Retrieves a report
    Args:
        domain: string
        report: string: accounts, activity, disk_space, email_clients, summary
        date: string: YYYY-MM-DD
    Returns:
        String, the report data
    """
    report_data = ''
    uri = REPORTING_URI
    if not report or report is None:
        return report_data
    if not date or date is None:
        return report_data
    if not domain or domain is None:
        domain = self.domain
    page = 1
    while True:
        report_xml = REPORTING_XML_TEMPLATE %(domain, date, page, report)
        response = ''
        report_page = ''
        try:
            response, report_page = http_object.request(
                uri,method='POST',body=report_xml)
        except Exception, rexcept:
            print 'Exception: ',rexcept
            report_page = ''
            break
        if response.status != 200:
            print 'Error: ',response.status
            report_page = ''
            break
        if not report_page or report_page == 'End-Of-Report':
            break
        else:
            report_data += report_page
            page = page + 1
    return report_data

scopes = OAUTH2SCOPES
user_agent = OAUTH2USERAGENT
client_source = CLIENTSOURCE
str_oauth2file = OAUTH2FILENAME
str_oauthjsonfile = OAUTH2JSONFILE
domain = 'somedomain'
report_name = 'accounts'
client_id = 'string'
client_secret = 'string'
report_data = ''
oauth2_flow = ''

now = time.time()
report_time = time.gmtime(now)
report_date = time.strftime("%Y-%m-%d",report_time)

if not os.path.isfile(str_oauth2file):
    token = gdata.gauth.OAuth2Token(client_id=client_id,
            client_secret=client_secret, scope=scopes, user_agent=user_agent)
    uri = token.generate_authorize_url()
    print 'Please visit this URL to authorize the application:'
    print uri
    # Get the verification code from the standard input.
    code = raw_input('What is the verification code? ').strip()
    token.get_access_token(code)
    oauth2_flow = oauth2client.client.flow_from_clientsecrets(str_oauthjsonfile,
        scope=scopes,message=MISSING_OAUTHJSON_FILE_MESSAGE)
storage = oauth2client.file.Storage(str_oauth2file)
oauth2_credentials = storage.get()
if oauth2_credentials is None or oauth2_credentials.invalid:
    if not oauth2_flow:
        oauth2_flow = oauth2client.client.flow_from_clientsecrets(str_oauthjsonfile,
            scope=scopes,message=MISSING_OAUTHJSON_FILE_MESSAGE)
    print '\nYou must authorize access to the request APIS.\n'
    # Save the credentials in storage to be used in subsequent runs.
    oauth2_credentials = oauth2client.tools.run(oauth2_flow, storage)
http_oauth2_object = httplib2.Http()
http_oauth2_object = oauth2_credentials.authorize(http_oauth2_object)
report_data = RunReport(
    http_oauth2_object,domain,report=report_name,date=report_date)
if report_data:
    print report_data
sys.exit(0)