2015-06-11 75 views
1

我試圖授權我的django應用程序使用oauth2爲了與購物API的谷歌內容進行交互。但是,我一直在遇到oauth2的問題。Oauth2使用Python 3.4和Django 1.7

我安裝了oauth2client和google-api-python-client。我的觀點是如下:

CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secret.json') 

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS, 
    scope='https://www.googleapis.com/auth/content', 
    redirect_uri='https://127.0.0.1:8000/oauth2/oauth2callback') 


def get_account_ids(service): 
    accounts = service.management().accounts().list().execute() 
    ids = [] 
    if accounts.get('items'): 
     for account in accounts['items']: 
      ids.append(account['id']) 
    return ids 


@login_required 
def index(request): 
    user = request.user 
    storage = Storage(CredentialsModel, 'id', user, 'credential') 
    credential = storage.get()  
    if credential is None: 
     FLOW.params['state'] = xsrfutil.generate_token(
      settings.SECRET_KEY, user) 
     authorize_url = FLOW.step1_get_authorize_url() 
     f = FlowModel(id=user, flow=FLOW) 
     f.save() 
     return HttpResponseRedirect(authorize_url) 
    else: 
     http = httplib2.Http() 
     http = credential.authorize(http) 
     service = build('content', 'v2', http=http) 
     ids = get_account_ids(service) 
     return render(
      request, 'index.html', {'ids':ids}) 


@login_required 
def auth_return(request): 
    user = request.user 
    if not xsrfutil.validate_token(settings.SECRET_KEY, bytes(request.GET['state'], 'utf-8'), user): 
     return HttpResponseBadRequest() 
    credential = FLOW.step2_exchange(request.GET, http=None) 
    storage = Storage(CredentialsModel, 'id', user, 'credential') 
    storage.put(credential) 
    return HttpResponseRedirect("/oauth2/") 

起初,我是從auth_return認爲串由request.GET中[「狀態」]重新調整得到一個錯誤沒有編碼,所以我改變這樣的:

if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'], user): 

這樣:

if not xsrfutil.validate_token(settings.SECRET_KEY, bytes(request.GET['state'], 'utf-8'), user): 
     return HttpResponseBadRequest() 

和錯誤不見了。但是,我現在得到錯誤:

'bytes' object has no attribute 'authorize' 

從索引視圖。導致例外的確切線爲:

http = credential.authorize(http) 

看起來這是由我之前做出的更改引起的。我是使用oauth2的新手,並且已經花費了很多小時來嘗試調試。任何人都可以請我指出正確的方向?

預先感謝您。

回答

1

我終於找到了答案。

似乎oauth2client中的django_orm模塊在CredentialsField定義中使用'to_python'函數,該函數不起作用,因此返回Base64數據。

爲了解決這個問題,必須從編輯oauth2client/django_orm源定義:

class CredentialsField(models.Field): 

到:

from django.utils.six import with_metaclass 
class CredentialsField(with_metaclass(models.SubfieldBase, models.Field)): 

這將允許其返回證書對象兩個Python2和Python3 。

請確保先刪除當前存儲的憑證對象,因爲它是字符串對象而不是憑證對象。