Problem with UnboundLocalError using Python's Dropbox API

I am trying to create a class in python that reads the access key / secret for dropbox and then uploads the file. The key / secret part works fine, but I seem to have a problem with recognizing the client object, possibly due to a problem with vs local global variables. I can not find the answer anywhere.

Here is part of my code:

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()) 

And here is the error:

 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 

I am new to python, so let me know if there are other obvious things that I may be doing wrong.

+4
source share
1 answer

You have imported the dropbox.client module into the scope of your module as client , but you also have a local client variable in your .auth_user() method.

When python sees the destination (e.g. client = ) in a function at compilation, it marks that name as a local variable. At the moment, your import of the client module is doomed, it is no longer displayed in your function under this name.

Next, in the eyes of python, you are trying to access this local client variable in a function; you are trying to get the DropboxClient attribute from it, but at the moment you have not assigned anything to the client variable yet. Thus, an UnboundLocal exception is UnboundLocal .

The workaround is to either not use client as a local variable to import the top-level dropbox module rather than submodules, and then reference its submodules with full dropbox.client , etc. or third, by providing the client module with a new name:

  • Do not use client as local:

     dbclient = client.DropboxClient(sess) # ... f, metadata = dbclient.get_file_and_metadata(file1) 
  • Import the dropbox module directly:

     import dropbox # ... sess = dropbox.session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE) # ... client = dropbox.client.DropboxClient(sess) 
  • Provide an alias for the client module:

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

Source: https://habr.com/ru/post/1434372/


All Articles