2016-12-08 58 views
0
from dropbox import Dropbox 
from dropbox import DropboxOAuth2FlowNoRedirect 

auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET) 

authorize_url = auth_flow.start() 
print "1. Go to: " + authorize_url 
print "2. Click \"Allow\" (you might have to log in first)." 
print "3. Copy the authorization code." 
auth_code = raw_input("Enter the authorization code here: ").strip() 

try: 
    access_token, user_id = auth_flow.finish(auth_code) 
except Exception, e: 
    print('Error: %s' % (e,)) 
    return 

dbx = Dropbox(access_token) 

我從http://dropbox-sdk-python.readthedocs.io/en/master/moduledoc.html#module-dropbox.oauth這是Dropbox文檔中的代碼嗎?

基本上我想是,測試一些簡單的命令什麼得到這個代碼。在我的代碼的開頭,我定義

APP_KEY = 'mykey' 
APP_SECRET = 'mysecret' 

每當我運行的代碼,提供訪問我的應用程序,並把在授權碼就給出了一個錯誤。

NameError: name 'access_token' is not defined 

我正在使用python2.7。 嘗試/例外部分有問題,但我無法弄清楚什麼。

任何人都可以幫忙嗎?

+2

也許他們忘了加一個功能存在,否則'return'語句有語法錯誤。 –

+0

當你運行它時,你是否看到'錯誤:'?您是否嘗試在try/except內打印出auth_flow.finish()調用的結果?你有什麼嘗試? –

+0

'return'用於退出函數,而不是程序/腳本。在'try/except'和'if access_token:dbx = Dropbox(access_token)'之前使用'exit()'或者使用'access_token = None'' – furas

回答

0

我試過你的代碼,它似乎在代碼中有所改變,但不是在documentation

現在auth_flow.finish(auth_code)返回對象OAuth2FlowNoRedirectResult(),與access_token, user_id不是元組,而這個對象的屬性obj.access_tokenobj.user_idobj.account_id

from dropbox import Dropbox 
from dropbox import DropboxOAuth2FlowNoRedirect 
import webbrowser 

APP_KEY = 'xxx' 
APP_SECRET = 'xxx' 

auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET) 
authorize_url = auth_flow.start() 

print "1. Go to: " + authorize_url 
print "2. Click \"Allow\" (you might have to log in first)." 
print "3. Copy the authorization code." 

webbrowser.open(authorize_url) # open page in browser 

auth_code = raw_input("Enter the authorization code here: ").strip() 

obj = None 

try: 
    obj = auth_flow.finish(auth_code) 
    #print obj 
    #print type(obj) 
    #print dir(obj) 
    print obj.access_token, obj.account_id, obj.user_id 
except Exception, e: 
    print 'Error:', e 
    #exit() 

if obj and obj.access_token: 
    dbx = Dropbox(obj.access_token) 
    print 'OK'