当前位置: 首页>>代码示例>>Python>>正文


Python appengine.AppAssertionCredentials类代码示例

本文整理汇总了Python中oauth2client.appengine.AppAssertionCredentials的典型用法代码示例。如果您正苦于以下问题:Python AppAssertionCredentials类的具体用法?Python AppAssertionCredentials怎么用?Python AppAssertionCredentials使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AppAssertionCredentials类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

  def __init__ (self, table, date = None):

    if date is not None:
      self.today = date
    else:
      self.today = datetime.today()
    logger.info("date:" + str(self.today))

    urlfetch.set_default_fetch_deadline(60) # Increase url fetch deadline for slow Google Analytics API calls

    # Fetch the API key if we haven't pulled it from the keyfile already
    global api_key
    if api_key == "":
      with open ("key.txt", "r") as keyfile:
        api_key=keyfile.read().replace('\n', '')

    # Set Query Range
    self.startdate = self.today - query_range
    self.extended_startdate = self.today - extended_query_range;
    self.expdate = self.today - cache_time

    # Setup analytics service authentication
    credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/analytics.readonly')
    http_auth = credentials.authorize(Http(memcache))
    self.service = build('analytics', 'v3', http=http_auth, developerKey=api_key)
    self.table_id = table
开发者ID:wcarle,项目名称:active-analytics,代码行数:26,代码来源:extractionservice.py

示例2: __init__

    def __init__(self):
        self._is_gae = os.getenv(
            'SERVER_SOFTWARE', '').startswith('Google App Engine')
        if self._is_gae:
            credentials = AppAssertionCredentials(scope=self._SCOPE)
            http = credentials.authorize(httplib2.Http())
        else:
            # parser = argparse.ArgumentParser(description=__doc__,
            #                                  formatter_class=argparse.RawDescriptionHelpFormatter,
            #                                  parents=[tools.argparser])
            # flags = parser.parse_args([])
            # self._FLOW = client.flow_from_clientsecrets(self._CLIENT_SECRETS,
            #                                             scope=[
            #                                             'https://www.googleapis.com/auth/analytics.readonly'
            #                                             ],
            #                                             redirect_uri=
            #                                             message=tools.message_if_missing(self._CLIENT_SECRETS))

            # storage = file.Storage('analytics.dat')
            # credentials = storage.get()
            # if credentials is None or credentials.invalid:
            #     credentials = tools.run_flow(self._FLOW, storage, flags)

            # http = httplib2.Http()
            http = auth_google_api.get_http_service()

        self._service = build('analytics', 'v3', http=http)
开发者ID:mcminis1,项目名称:wizeline-dashboard,代码行数:27,代码来源:analytics_client.py

示例3: _get_content

  def _get_content(self, path, method='POST', body=None):
    scope = [
      'https://www.googleapis.com/auth/genomics'
    ]
    # The API Key is required when deployed to app engine
    api_key = os.environ['API_KEY']
    credentials = AppAssertionCredentials(scope=scope)
    http = httplib2.Http(cache=memcache)
    http = credentials.authorize(http)

    try:
      response, content = http.request(
        uri="https://www.googleapis.com/genomics/v1beta/%s?key=%s"
            % (path, api_key),
        method=method, body=json.dumps(body) if body else None,
        headers={'Content-Type': 'application/json; charset=UTF-8'})
    except DeadlineExceededError:
      raise ApiException('API fetch timed out')

    try:
      content = json.loads(content)
    except ValueError:
      logging.error("non-json api content %s" % content)
      raise ApiException('The API returned invalid JSON')

    if response.status >= 300:
      logging.error("error api response %s" % response)
      logging.error("error api content %s" % content)
      if 'error' in content:
        raise ApiException(content['error']['message'])
      else:
        raise ApiException('Something went wrong with the API call!')
    return content
开发者ID:Tong-Chen,项目名称:genomics-tools,代码行数:33,代码来源:genomicsapi.py

示例4: createDriveService

def createDriveService(credential_path=None):
  """
  Create drive service based on service account credentialed from api_key in secret_files/config.json.  Utilizes 'https://www.googleapis.com/auth/drive' scope.
  """
  
  # Determine if running in local appengine SDK dev_server environment.  
  # AppAssertionCredentials does not load in this context.  
  # Therefore, service must be mimicked locally using an installed client oauth flow.
  if os.environ.get('SERVER_SOFTWARE') is None:
    os.environ['SERVER_SOFTWARE'] = 'Development'
    
  if 'Development' in os.environ.get('SERVER_SOFTWARE'):
    # Acquire credentials stored from running `python secret.py` from the commandline.
    if credential_path is None:
      credential_path = secret_cred.CREDENTIALS
    storage = Storage(credential_path)
    credentials = storage.get()
    http = httplib2.Http()
    http = credentials.authorize(http)

    return build('drive', 'v2', http=http)

    
  else:
    service_account_email = secret_cred.SERVICE_ACCOUNT
    api_key = secret_cred.API_KEY
    credentials = AppAssertionCredentials(scope=OAUTH_SCOPE)
    http = httplib2.Http()
    http = credentials.authorize(http)

    return build('drive', 'v2', http=http, developerKey=api_key)
开发者ID:gddb,项目名称:gddb,代码行数:31,代码来源:service.py

示例5: get_big_query_service

def get_big_query_service():
    global _bigquery_service
    if _bigquery_service is None:
        credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/bigquery')
        http = credentials.authorize(httplib2.Http(memcache))
        _bigquery_service = build('bigquery', 'v2', http=http)
    return _bigquery_service
开发者ID:kkocaerkek,项目名称:bigquery_streaming,代码行数:7,代码来源:bigquery.py

示例6: test_get_access_token

    def test_get_access_token(self):
        app_identity_stub = self.AppIdentityStubImpl()
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service", app_identity_stub)
        apiproxy_stub_map.apiproxy.RegisterStub("memcache", memcache_stub.MemcacheServiceStub())

        credentials = AppAssertionCredentials(["dummy_scope"])
        token = credentials.get_access_token()
        self.assertEqual("a_token_123", token.access_token)
        self.assertEqual(None, token.expires_in)
开发者ID:kaste,项目名称:oauth2client,代码行数:10,代码来源:test_appengine.py

示例7: TestQuery

def TestQuery():
    """Runs a test query against the measurement-lab BigQuery database.
    
    Returns:
        (string) The query results formatted as an HTML page.
    """
    # Certify BigQuery access credentials.
    credentials = AppAssertionCredentials(
        scope='https://www.googleapis.com/auth/bigquery')
    http = credentials.authorize(httplib2.Http(memcache))
    service = build('bigquery', 'v2', http=http)
    job_runner = service.jobs()

    # Run a query against the BigQuery database.
    logging.debug('Query: %s' % TEST_QUERY)
    jobdata = {'configuration': {'query': {'query': TEST_QUERY}}}
    insert = job_runner.insert(projectId=PROJECT_ID,
                               body=jobdata).execute()
    logging.debug('Response: %s' % insert)

    currentRow = 0
    queryReply = job_runner.getQueryResults(
        projectId=PROJECT_ID,
        jobId=insert['jobReference']['jobId'],
        startIndex=currentRow).execute()
    results = queryReply

    while 'rows' in queryReply and currentRow < queryReply['totalRows'] :
        currentRow += len(queryReply['rows'])
        queryReply = job_runner.getQueryResults(
            projectId=PROJECT_ID,
            jobId=queryReply['jobReference']['jobId'],
            startIndex=currentRow).execute()
        if 'schema' not in results or 'fields' not in results['schema']:
            if 'schema' in queryReply and 'fields' in queryReply['schema']:
                results['schema'] = queryReply['schema']
        if 'rows' in queryReply:
            results['rows'].extend(queryReply['rows'])

    # Format the results as an HTML page.
    body = '<h2>The Query</h2><pre>%s</pre>\n<hr>\n' % TEST_QUERY

    tablerows = '<tr>'
    for field in results['schema']['fields']:
        tablerows += '<th>%s</th>' % field['name']

    for row in results['rows']:
        tablerows += '</tr><tr>'
        for value in row['f']:
            tablerows += '<td>%s</td>' % value['v']
    tablerows += '</tr>'

    body += '<table border=1>\n%s\n</table>\n' % tablerows

    return '<!DOCTYPE html><html><body>%s</body></html>' % body
开发者ID:dcurley,项目名称:mlab-metrics-api-server,代码行数:55,代码来源:main.py

示例8: initService

def initService():

  api_key = 'YOUR GOOGLE API KEY'

  credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/calendar')
  http = httplib2.Http(memcache)
  http = credentials.authorize(http)

  service = build("calendar", "v3", http=http, developerKey=api_key)

  return service
开发者ID:alfredyuan,项目名称:privateTutoring,代码行数:11,代码来源:middleware.py

示例9: createDriveService

def createDriveService():
    """Builds and returns a Drive service object authorized with the
       application's service account.
       Returns:
           Drive service object.
    """

    credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/drive')
    http = httplib2.Http()
    http = credentials.authorize(http)
    return build('drive', 'v1', http=http, developerKey='AIzaSyA9j1GWqNWUjpBA6DhRQzAQYeJQalfJSWs')
开发者ID:karishma-sureka,项目名称:fotolitic,代码行数:11,代码来源:try2.py

示例10: test_get_access_token

  def test_get_access_token(self):
    app_identity_stub = self.AppIdentityStubImpl()
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
                                            app_identity_stub)
    apiproxy_stub_map.apiproxy.RegisterStub(
        'memcache', memcache_stub.MemcacheServiceStub())

    credentials = AppAssertionCredentials(['dummy_scope'])
    token = credentials.get_access_token()
    self.assertEqual('a_token_123', token)
开发者ID:Alexander-Attar,项目名称:oauth2client,代码行数:11,代码来源:test_appengine.py

示例11: index

def index(request):

   credentials = AppAssertionCredentials(
              scope='https://www.googleapis.com/auth/bigquery')
   http = credentials.authorize(httplib2.Http())
   bigquery_service = build('bigquery', 'v2', http=http)
   query_request = bigquery_service.jobs()
   query_data = {'query':'SELECT *  FROM [maveriks_assessment_sprint_1.test_new]'}
   query_response = query_request.query(projectId=PROJECT_NUMBER,
                                         body=query_data).execute()
   return render_to_response('AssessingPie_toBeremoved/testmeveriks.html',{'result':query_response['rows']},context_instance = RequestContext(request))
开发者ID:anks315,项目名称:Assesment2,代码行数:11,代码来源:maveriks.py

示例12: build_bq_client

def build_bq_client():
    
    from googleapiclient.discovery import build
    from oauth2client.appengine import AppAssertionCredentials
    import httplib2

    SCOPE = 'https://www.googleapis.com/auth/bigquery'
    credentials = AppAssertionCredentials(scope=SCOPE)
    http = credentials.authorize(httplib2.Http())
    bigquery_service = build('bigquery', 'v2', http=http)

    return bigquery_service
开发者ID:CGNx,项目名称:xanalytics,代码行数:12,代码来源:auth.py

示例13: post

  def post(self):
    self.response.headers['Content-Type'] = 'text/plain'

    jobid = self.request.get('jobid')
    job = job_info.JobInfo.get_by_id(jobid)
    if not job:
      return

    payload = urllib.urlencode({'q': 'MAX_TRACE_HANDLES=10'})
    query_url = '%s/query?%s' % (_PERFORMANCE_INSIGHTS_URL, payload)
    result = urlfetch.fetch(url=query_url,
                            payload=payload,
                            method=urlfetch.GET,
                            follow_redirects=False,
                            deadline=10)
    logging.info(result.content)

    taskid = str(uuid.uuid4())
    traces = json.loads(result.content)

    default_retry_params = gcs.RetryParams(initial_delay=0.2,
                                           max_delay=5.0,
                                           backoff_factor=2,
                                           max_retry_period=15)
    gcs_file = gcs.open(_DEFAULT_BUCKET.format(name=taskid),
                        'w',
                        content_type='text/plain',
                        options={},
                        retry_params=default_retry_params)
    gcs_file.write(json.dumps(traces))
    gcs_file.close()

    credentials = AppAssertionCredentials(
        scope='https://www.googleapis.com/auth/compute')
    http = credentials.authorize(httplib2.Http(memcache))
    compute = build("compute", "v1", http=http)

    startup_script = _STARTUP_SCRIPT.format(
        revision=job.revision)

    result = self._CreateGCEInstace(
        compute, 'mr-%s' % jobid, startup_script)

    logging.info('Call to instances().insert response:\n')
    for k, v in sorted(result.iteritems()):
        logging.info(' %s: %s' % (k, v))

    job.status = 'COMPLETE'
    job.put()

    response = {'success': False}
    self.response.out.write(json.dumps(response))
开发者ID:bashi,项目名称:catapult,代码行数:52,代码来源:task.py

示例14: createDriveService1

def createDriveService1():
  """Builds and returns a Drive service object authorized with the
  application's service account.

  Returns:
    Drive service object.
  """
  credentials = AppAssertionCredentials(
      scope='https://www.googleapis.com/auth/drive')
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('drive', 'v2', http=http, developerKey=API_KEY)
开发者ID:arp007,项目名称:memorizer,代码行数:13,代码来源:driveConnector.py

示例15: run

  def run(self, csv_output):

    credentials = AppAssertionCredentials(scope=SCOPE)
    http = credentials.authorize(httplib2.Http())
    bigquery_service = build("bigquery", "v2", http=http)

    jobs = bigquery_service.jobs()
    table_name = 'datastore_data_%s' % datetime.datetime.utcnow().strftime(
        '%m%d%Y_%H%M%S')
    files = [str(f.replace('/gs/', 'gs://')) for f in csv_output]
    result = jobs.insert(projectId=PROJECT_ID,
                        body=build_job_data(table_name,files))
    result.execute()
开发者ID:MrNiebieski,项目名称:bigquery-appengine-datastore-import-sample,代码行数:13,代码来源:main.py


注:本文中的oauth2client.appengine.AppAssertionCredentials类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。