使用 OAuth2 代码在 python 中使用 Dropbox API 时出现问题

Problem using Dropbox API in python with OAuth2 code

我正在尝试使用 Dropbox 作为用户共享文件的媒介来设置一个应用程序。

我可以使用应用程序令牌上传文件,但是当我尝试使用授权码时,文件无法上传;应用程序没有报错。

后面的代码包含两种方法:

dbx = get_dbx_with_token()

有效,但是

dbx = get_dbx_with_auth_code()

没有。任何帮助表示赞赏。

import webbrowser

from dropbox import Dropbox
from dropbox.files import WriteMode
from dropbox import DropboxOAuth2FlowNoRedirect

APP_KEY = '<my app key>'
APP_SECRET = '<my app secret>'
APP_TOKEN = '<my app token>'

def upload(dbx):
    local_file = '<path to local file>'
    remote_file = '<remote file name>'
    with open(local_file, 'rb') as f_upload:
        try:
            foo = dbx.files_upload(f_upload.read(), remote_file, 
                                   mode=WriteMode('overwrite'))
            print('done ...', foo)
        except:
            print('Upload error')

def get_dbx_with_auth_code():
    auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)
    authorize_url = auth_flow.start()
    webbrowser.open(authorize_url)
    auth_code = input('Authorization code: ').strip()
    try:
        oauth_result = auth_flow.finish(auth_code)
    except:
        print('Token error')
        return None
    dbx = Dropbox(oauth_result.access_token)
    return dbx

def get_dbx_with_token():
    dbx = Dropbox(APP_TOKEN)
    return dbx

if __name__ == '__main__':
    dbx = get_dbx_with_token()
    #dbx = get_dbx_with_auth_code()
    upload(dbx)

dbx.files_upload函数(foo)returns:

 FileMetadata(
      name='uploaded.txt', 
      id='id:<my_id>', 
      client_modified=datetime.datetime(2018, 12, 13, 18, 24, 15), 
      server_modified=datetime.datetime(2018, 12, 13, 18, 24, 15), 
      rev='013000000010ede3870', size=6, path_lower='/upload test/uploaded.txt', 
      path_display='/upload test/uploaded.txt', 
      parent_shared_folder_id=None, 
      media_info=None, 
      symlink_info=None, 
      sharing_info=None, 
      property_groups=None, 
      has_explicit_shared_members=None, content_hash='<content hash>')

get_dbx_with_token 的文件元数据不同:

parent_shared_folder_id='1234567890', 
sharing_info=FileSharingInfo(read_only=False,
parent_shared_folder_id='1234567890',
modified_by='dbid:AAAyXwp1wvSzPzmqzCJ9SWFuxhc')

(顺便说一句,我上传的文件夹是属于另一个用户的共享文件夹)

我认为它不起作用的原因是如果我使用 get_dbx_with_auth_code() 它不会出现在我的(浏览器)Dropbox 文件夹中,但如果我使用 get_dbx_with_token( ).

感谢 Greg 的评论,我意识到上传确实在进行,但我对 API 的有限理解意味着我没有意识到使用 auth_code 选项放置了文件在应用程序的特定文件夹中。很好,现在我知道在哪里可以找到它了。

The output indicates that the file was successfully uploaded, so it sounds like you're looking in a different folder or account when looking for it on the Dropbox web site. Double check what account/folder you're looking in. Also, you may be using a different app between the two flows, so note that if an app has the "app folder" permission, it will upload into the special "app folder" made for the app, by default inside "/Apps"

打印 files_upload 的输出显示了正在发生的事情。