1

この質問は次のようになります:http://stackoverflow.com/questions/12471180/frequently-http-500-internal-error-with-google-drive-api-drive-files-get500内部の答えはありませんがサーバーエラー。

Googleドライブ(Python)を使用して、すべてのファイルを反復処理し、各ファイルのアクセス許可を変更しています。次のような応答があります:エラーが発生しました:https://www.googleapis.com/drive/v2/files/12345CuV3wBsvZDM3ZmRjNWQtMWZkNC00NzQzLTg2MzMtM2IyY2Q0YWU1OTll/permissions?alt=jsonが「内部エラー」を返しました

私のコードはグーグルの例からかなりクッキーカッターであり、次のとおりです:

#!/usr/bin/python
from apiclient import errors
import httplib2
import pprint
import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
# Path to client_secrets.json which should contain a JSON document such as:
#   {
#     "web": {
#       "client_id": "[[YOUR_CLIENT_ID]]",
#       "client_secret": "[[YOUR_CLIENT_SECRET]]",
#       "redirect_uris": [],
#       "auth_uri": "https://accounts.google.com/o/oauth2/auth",
#       "token_uri": "https://accounts.google.com/o/oauth2/token"
#     }
#   }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
SCOPES = [
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
# Add other requested scopes.
]

class GetCredentialsException(Exception):
  """Error raised when an error occurred while retrieving credentials.

  Attributes:
    authorization_url: Authorization URL to redirect the user to in order to
                       request offline access.
  """

  def __init__(self, authorization_url):
    """Construct a GetCredentialsException."""
    self.authorization_url = authorization_url


class CodeExchangeException(GetCredentialsException):
  """Error raised when a code exchange has failed."""


class NoRefreshTokenException(GetCredentialsException):
  """Error raised when no refresh token has been found."""


class NoUserIdException(Exception):
  """Error raised when no user ID could be retrieved."""

def update_permission(service, file_id, permission_id, new_role):
  """Update a permission's role.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to update permission for.
    permission_id: ID of the permission to update.
    new_role: The value 'owner', 'writer' or 'reader'.

  Returns:
    The updated permission if successful, None otherwise.
  """
  try:
    # First retrieve the permission from the API.
    permission = service.permissions().get(
        fileId=file_id, permissionId=permission_id).execute()
    permission['role'] = new_role
    return service.permissions().update(
        fileId=file_id, permissionId=permission_id, body=permission).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None  

def retrieve_all_files(service):
  """Retrieve a list of File resources.

  Args:
    service: Drive API service instance.
  Returns:
    List of File resources.
  """
  result = []
  page_token = None
  while True:
    try:
      param = {}
      if page_token:
        param['pageToken'] = page_token
      files = service.files().list(**param).execute()

      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 retrieve_permissions(service, file_id):
  """Retrieve a list of permissions.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to retrieve permissions for.
  Returns:
    List of permissions.
  """
  try:
    permissions = service.permissions().list(fileId=file_id).execute()
    return permissions.get('items', [])
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None



def insert_permission(service, file_id, value, perm_type, role):
  """Insert a new permission.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to insert permission for.
    value: User or group e-mail address, domain name or None for 'default'
           type.
    perm_type: The value 'user', 'group', 'domain' or 'default'.
    role: The value 'owner', 'writer' or 'reader'.
  Returns:
    The inserted permission if successful, None otherwise.
  """
  new_permission = {
      'value': value,
      'type': perm_type,
      'role': role
  }
  try:
    return service.permissions().insert(
        fileId=file_id, body=new_permission).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None



def login(clientID, clientSecret, clientCode=0):
    # Copy your credentials from the APIs Console
    CLIENT_ID     = clientID        
    CLIENT_SECRET = clientSecret

    # Check https://developers.google.com/drive/scopes for all available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

    # Redirect URI for installed apps
    REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
    #REDIRECT_URI = 'http://localhost'

    # Run through the OAuth flow and retrieve credentials
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    if not clientCode:
        print 'Go to the following link in your browser: ' + authorize_url
        code = raw_input('Enter verification code: ').strip()

    else:
        print 'Client code supplied'
        code = clientCode 

    credentials = flow.step2_exchange(code)

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
http = credentials.authorize(http)

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

allFilesDictionary = retrieve_all_files(drive_service)
file = open('file3.txt', 'a')
for f in allFilesDictionary:
    fileID            = f['id']
    permissionsIDList = retrieve_permissions(drive_service, fileID)
    pidl = permissionsIDList[0]
    #for pidl in permissionsIDList:
    #It is a list of dictionaries.....
    #for p in pidl:
    #   file.write(fileID + '\t\t' + p + ' value is' + p['id'] + '\n')
    #Change permissions of ID...
    ####"owner"
    ####permissionsIDList["userPermission"]["id"]
    ####"me" gives 500 "Http 500 Internal server error" ... empty oauth_callback value while request_token ... give webaddress
    #permissionsResource = update_permission(drive_service, fileID, "me", "reader")

    insert_permission(drive_service, fileID, "me", "user", "reader")

file.close()

clientid    ='1234567872174.apps.googleusercontent.com'
clientsecret='abcdefgh3VXUu5EaJvO9BExc'

login(clientid, clientsecret)

「パーミッションの挿入」ではなく「パーミッションの追加」というクラウディオのアドバイスに従って、コードを次のように変更します。

import gdata.docs
import gdata.docs.service
userNameAtGmailCom = 'PersonAEmailAddress@gmail.com'
password           = 'PersonAPassword'
personToShareWith  = "PersonB@gmail.com"
def login(userNameAtGmailCom, password, personToShareWith): 
    client = gdata.docs.service.DocsService()
    client.ClientLogin(userNameAtGmailCom, password)
    documents_feed = client.GetDocumentListFeed()
    for document_entry in documents_feed.entry:
        print document_entry.title.text
        scope = gdata.docs.Scope(value=personToShareWith, type='user')
        role = gdata.docs.Role(value='reader')
        acl_entry = gdata.docs.DocumentListAclEntry(scope=scope, role=role)
        created_acl_entry = client.Post(acl_entry, document_entry.GetAclLink().href,     converter=gdata.docs.DocumentListAclEntryFromString)
login(userNameAtGmailCom, password, personToShareWith)

これにより、PersonAがファイルを共有したことを通知する電子メールがPersonBに送信されます。これは、PersonBのアプリがPersonAのファイルを読み取れるようにするPersonBからアプリを実行できる場合を意味しますか?

4

0 に答える 0