Home Database Mysql Tutorial 一大坨GoogleAPI的学习笔记之三(基于oAuth2.0的domain

一大坨GoogleAPI的学习笔记之三(基于oAuth2.0的domain

Jun 07, 2016 pm 03:08 PM
oauth based on study notes

http://blog.csdn.net/btyh17mxy/article/details/9939035 在Google Apps中域管理员可以访问域中其他用户的数据,包括Drive、Gmail什么的。当然要想访问就需要进行domain-wide(域)认证。 在Google的官方文档中只有https://developers.google.com/drive/del

http://blog.csdn.net/btyh17mxy/article/details/9939035

    在Google Apps中域管理员可以访问域中其他用户的数据,包括Drive、Gmail什么的。当然要想访问就需要进行domain-wide(域)认证。

    在Google的官方文档中只有https://developers.google.com/drive/delegation这么一篇,介绍的是Drive的domain-wide认证,我参考了这篇文档并做了些修改。

#-coding:utf-8
#!/usr/bin/python

import httplib2
import pprint
import sys

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = '下图中的email地址'

"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '密钥文件路径'

def getCredentials(user_email):
    """Get cardentials for an Google Apps user
    Args:
        user_email: The email of the user
    Returns:
        The cardentials that you can use to get access to the
        user's data or something
    """
    f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
    key = f.read()
    f.close()
    
    credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
            scope='https://www.googleapis.com/auth/drive', sub=user_email)
    return credentials
Copy after login
一大坨GoogleAPI的学习笔记之三(基于oAuth2.0的domain

这样就获取到了域下指定用户的证书,可以使用该证书构建Drive服务,就像下面这样:

#-coding:utf-8
#!/usr/bin/python

import httplib2
from apiclient.discovery import build
from apiclient import errors

class Drive:
    def __init__(self,credentials):
        self.credentials=credentials

    def getFileList(self,maxResults,pageToken,q,projection="FULL"):
        http = httplib2.Http()
        http = self.credentials.authorize(http)

        service = build('drive', 'v2', http=http)
        
        result = []
        page_token = pageToken
        while True:
            try:
                #param = {'maxResults':500}
                param={'maxResults':maxResults,'pageToken':page_token,'projection':projection,'q':q}
                if page_token:
                    param['pageToken'] = page_token
                files = service.files().list(**param).execute()
                #print files['items']
                result.extend(files['items'])
                page_token = files.get('nextPageToken')
                
                if not page_token:
                    break
            except errors.HttpError, error:
                print 'An error occurred: %s' % error
                break
        
        return result

    def getFileByID(fileID):
        """
        Get a Drive File instance by it's id
        Args:
        fileID: id of this file item
        Rerurns:
        A Drive File instance if successful, None if otherwise
        """
        try :
            file = self.service.files().get(fileID).execute()
            return file
        except errors.HttpError,e:
            print 'An error occurred: %s ' % e
            return None


    def print_file(file_id):
        """
        Print a file's metadata.
        Args:
        service: Drive API service instance.
        file_id: ID of the file to print metadata for.
        """
        try:
            file = self.service.files().get(fileId=file_id).execute()
            print 'Title: %s' % file['title']
            print 'MIME type: %s' % file['mimeType']
        except errors.HttpError, error:
            print 'An error occurred: %s' % error
        
    def download_file(drive_file):
        """
        Download a file's content.
        Args:
        service: Drive API service instance.
        drive_file: Drive File instance.
        Returns:
        File's content if successful, None otherwise.
        """
        download_url = drive_file.get('downloadUrl')
        if download_url:
            resp, content = self.service._http.request(download_url)
            if resp.status == 200:
                print 'Status: %s' % resp
                return content
            else:
                print 'An error occurred: %s' % resp
                return None
            
        else:
            # The file doesn't have any content stored on Drive.
            return None
        
Copy after login

#-coding:utf-8
#!/usr/bin/python

import d_oauth
from drive import Drive

if __name__ == '__main__':
    c = d_oauth.getCredentials('btyh17mxy@gdocsapp.com')
    drive = Drive(c)
    files = drive.getFileList(1000,None,None)
    for f in files:
        print "FileName:%s\nFileType:%s\nFileID:%s\n" % (f['title'],f['mimeType'],f['id'])
Copy after login



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete Xiaohongshu notes How to delete Xiaohongshu notes Mar 21, 2024 pm 08:12 PM

How to delete Xiaohongshu notes? Notes can be edited in the Xiaohongshu APP. Most users don’t know how to delete Xiaohongshu notes. Next, the editor brings users pictures and texts on how to delete Xiaohongshu notes. Tutorial, interested users come and take a look! Xiaohongshu usage tutorial How to delete Xiaohongshu notes 1. First open the Xiaohongshu APP and enter the main page, select [Me] in the lower right corner to enter the special area; 2. Then in the My area, click on the note page shown in the picture below , select the note you want to delete; 3. Enter the note page, click [three dots] in the upper right corner; 4. Finally, the function bar will expand at the bottom, click [Delete] to complete.

What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? Mar 21, 2024 pm 09:30 PM

As a Xiaohongshu user, we have all encountered the situation where published notes suddenly disappeared, which is undoubtedly confusing and worrying. In this case, what should we do? This article will focus on the topic of "What to do if the notes published by Xiaohongshu are missing" and give you a detailed answer. 1. What should I do if the notes published by Xiaohongshu are missing? First, don't panic. If you find that your notes are missing, staying calm is key and don't panic. This may be caused by platform system failure or operational errors. Checking release records is easy. Just open the Xiaohongshu App and click "Me" → "Publish" → "All Publications" to view your own publishing records. Here you can easily find previously published notes. 3.Repost. If found

How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu Mar 12, 2024 am 10:40 AM

How to add product links in notes in Xiaohongshu? In the Xiaohongshu app, users can not only browse various contents but also shop, so there is a lot of content about shopping recommendations and good product sharing in this app. If If you are an expert on this app, you can also share some shopping experiences, find merchants for cooperation, add links in notes, etc. Many people are willing to use this app for shopping, because it is not only convenient, but also has many Experts will make some recommendations. You can browse interesting content and see if there are any clothing products that suit you. Let’s take a look at how to add product links to notes! How to add product links to Xiaohongshu Notes Open the app on the desktop of your mobile phone. Click on the app homepage

Learn to completely uninstall pip and use Python more efficiently Learn to completely uninstall pip and use Python more efficiently Jan 16, 2024 am 09:01 AM

No more need for pip? Come and learn how to uninstall pip effectively! Introduction: pip is one of Python's package management tools, which can easily install, upgrade and uninstall Python packages. However, sometimes we may need to uninstall pip, perhaps because we wish to use another package management tool, or because we need to completely clear the Python environment. This article will explain how to uninstall pip efficiently and provide specific code examples. 1. How to uninstall pip The following will introduce two common methods of uninstalling pip.

A deep dive into matplotlib's colormap A deep dive into matplotlib's colormap Jan 09, 2024 pm 03:51 PM

To learn more about the matplotlib color table, you need specific code examples 1. Introduction matplotlib is a powerful Python drawing library. It provides a rich set of drawing functions and tools that can be used to create various types of charts. The colormap (colormap) is an important concept in matplotlib, which determines the color scheme of the chart. In-depth study of the matplotlib color table will help us better master the drawing functions of matplotlib and make drawings more convenient.

Revealing the appeal of C language: Uncovering the potential of programmers Revealing the appeal of C language: Uncovering the potential of programmers Feb 24, 2024 pm 11:21 PM

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Feb 19, 2024 pm 10:10 PM

Learn Pygame from scratch: complete installation and configuration tutorial, specific code examples required Introduction: Pygame is an open source game development library developed using the Python programming language. It provides a wealth of functions and tools, allowing developers to easily create a variety of type of game. This article will help you learn Pygame from scratch, and provide a complete installation and configuration tutorial, as well as specific code examples to get you started quickly. Part One: Installing Python and Pygame First, make sure you have

Let's learn how to input the root number in Word together Let's learn how to input the root number in Word together Mar 19, 2024 pm 08:52 PM

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

See all articles