簡體   English   中英

使用Python Dropbox API的UnboundLocalError問題

[英]UnboundLocalError issue using Python Dropbox API

我正在嘗試在python中創建一個類,該類讀取投寄箱的訪問密鑰/秘密,然后下載文件。 密鑰/秘密部分可以正常工作,但是我似乎在識別客戶端對象時遇到了問題,這可能是由於全局變量與局部變量有關。 我在其他任何地方都找不到答案。

這是我的代碼的一部分:

from dropbox import client, rest, session

class GetFile(object):

    def __init__(self, file1):
        self.auth_user()

    def auth_user(self):
        APP_KEY = 'xxxxxxxxxxxxxx'
        APP_SECRET = 'xxxxxxxxxxxxxx'
        ACCESS_TYPE = 'dropbox'
        TOKENS = 'dropbox_token.txt'

        token_file = open(TOKENS)
        token_key,token_secret = token_file.read().split('|')
        token_file.close()

        sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE)
        sess.set_token(token_key,token_secret)
        client = client.DropboxClient(sess)

        base, ext = file1.split('.')

        f, metadata = client.get_file_and_metadata(file1)
        out = open('/%s_COPY.%s' %(base, ext), 'w')
        out.write(f.read())

這是錯誤:

Traceback (most recent call last):
File "access_db.py", line 30, in <module>
start = GetFile(file_name)
File "access_db.py", line 6, in __init__
self.auth_user()
File "access_db.py", line 20, in auth_user
client = client.DropboxClient(sess)
UnboundLocalError: local variable 'client' referenced before assignment

我是python的新手,所以讓我知道是否還有其他明顯的事情我可能做錯了。

您將dropbox.client模塊作為client導入到模塊范圍中,但是.auth_user()方法中具有一個本地變量client

當python在編譯時看到函數中的賦值(例如client = )時,它將該名稱標記為局部變量。 至此,您對client 模塊的導入已注定要失敗,在該功能下,該名稱不再可見。

接下來,在python的眼中,您正在嘗試訪問該函數中的局部變量client 您正在嘗試從中獲取屬性DropboxClient ,但此時尚未將任何內容分配變量client 因此,拋出UnboundLocal異常。

解決方法是要么不使用client作為局部變量,要么導入頂級dropbox模塊而不是其子模塊,然后使用完整的dropbox.client等路徑引用它的子模塊,或者第三,通過提供client模塊新名稱:

  1. 不要將client用作本地client

     dbclient = client.DropboxClient(sess) # ... f, metadata = dbclient.get_file_and_metadata(file1) 
  2. 直接導入dropbox模塊:

     import dropbox # ... sess = dropbox.session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE) # ... client = dropbox.client.DropboxClient(sess) 
  3. 提供client模塊的別名:

     from dropbox import session, rest from dropbox import client as dbclient # ... client = dbclient.DropboxClient(sess) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM