Google Drive Insert Permissions python 500 внутренняя ошибка сервера

этот вопрос похож на: http://stackoverflow.com/questions/12471180/frequently-http-500-internal-error-with-google-drive-api-drive-files-get Хотя нет ответа на 500 внутренних Ошибка сервера.

Я использую Google Диск (python) для перебора всех моих файлов и изменения разрешений для каждого файла. Я получаю такие ответы: Произошла ошибка: https://www.googleapis.com/drive/v2/files/12345CuV3wBsvZDM3ZmRjNWQtMWZkNC00NzQzLTg2MzMtM2IyY2Q0YWU1OTll/permissions?alt=json вернул "Внутренняя ошибка">

Мой код довольно прост из примеров Google и выглядит следующим образом:

#!/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 = '[email protected]'
password           = 'PersonAPassword'
personToShareWith  = "[email protected]"
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)

Это отправляет PersonB электронное письмо о том, что PersonA поделился с ним файлом. Означает ли это, что когда я смогу запустить приложение от PersonB, это позволит приложению personB читать файлы человека A?


person user1709076    schedule 18.10.2012    source источник
comment
Как вы думаете, это та же проблема, что и stackoverflow.com/questions/12558808/ ?   -  person Claudio Cherubino    schedule 19.10.2012
comment
Нет. Причина, по которой я это говорю, в том, что он/она говорит, что я могу обновить писатель до читателя. Принимая во внимание, что я не могу обновить файл для чтения. Я просто получаю внутреннюю ошибку сервера 500.   -  person user1709076    schedule 19.10.2012
comment
Я думаю, что это похоже в том смысле, что вы также пытаетесь обновить разрешения единственного владельца. На самом деле, у вас не будет проблем, если вы добавите разрешения, а не обновите их, верно?   -  person Claudio Cherubino    schedule 19.10.2012
comment
Привет, Клаудио, поэтому я попробовал ваше предложение и сделал «добавить разрешения» вместо «вставить разрешения», для чего требуется библиотека gdata. Таким образом, это изменяет мой код (ниже) и позволяет мне «делиться» документами пользователя A с пользователем B. Я добавил код для этого ниже. Я не уверен, что это то, чего я пытаюсь достичь, а именно: я хотел бы, чтобы пользователь B имел разрешения на «чтение» через приложение.   -  person user1709076    schedule 31.10.2012
comment
Я хотел бы решить эту проблему, используя аутентификацию OAuth, а не вход в систему с именем пользователя и паролем. Так что тему я еще не закрыл. Это потому, что я не ввел значение forCLIENTSECRETS_LOCATION = '‹PATH/TO/CLIENT_SECRETS.JSON›   -  person user1709076    schedule 05.12.2012