使用oauth2client.django_orm.Storage-class存储DriveAPI凭据 [英] Storage of DriveAPI credentials using oauth2client.django_orm.Storage-class

查看:45
本文介绍了使用oauth2client.django_orm.Storage-class存储DriveAPI凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存从Drive API获得的客户端凭据。我在下面尝试了以下代码,它可以很好地存储凭据,但是当我在上传视图中访问数据时,它没有返回凭据

I want to save the client credentials obtained from Drive API. I tried the following code below, it's working well to store credentials but when I'm accessing the data in upload view it's not returning the credential

views.py

from oauth2client.django_orm import Storage
from drv_app.models import CredentialsModel

#authorization of the client by the user
def authorize_application(request):

    #setting flow to get permission and code 
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI, ACCESS_TYPE)
    authorize_url = flow.step1_get_authorize_url()

    code = request.GET.get('code', '')

    if code:

    #setting flow step2 to exchage code for access token    
        credential = flow.step2_exchange(code)

    #initialising httplib2 instance and building a DriveAPI service
        http = httplib2.Http()
        http = credential.authorize(http)
        drive_service = build('drive', 'v2', http=http)

 user, created = User.objects.get_or_create(username=username, email=email)

    #saving credentials to database 
        if created == True: 
            storage = Storage(CredentialsModel, 'id', user, 'credential')
            storage.put(credential)
            return HttpResponseRedirect('/upload/')
        else:
        return HttpResponseRedirect('/upload/')
    else:
        return HttpResponseRedirect(authorize_url)



def upload_file(request):

    username = request.session['username']
    user = User.objects.get(username=username)
    storage = Storage(CredentialsModel, 'id', user, 'credential')

    credential = storage.get()

    http = httplib2.Http()
    http = credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)

    media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
    body = {
        'title': 'vishnu_test',
        'description': 'A test document',
        'mimeType': 'text/plain'
        }
    file = drive_service.files().insert(body=body, media_body=media_body).execute()
    pprint.pprint(file)

    return HttpResponse('uploaded')

models.py

from oauth2client.django_orm import FlowField
from oauth2client.django_orm import CredentialsField


class CredentialsModel(models.Model):
  id = models.ForeignKey(User, primary_key=True)
  credential = CredentialsField()

我做错了什么?请提出必要的改进建议。

What I'm doing wrong? Please suggest the necessary improvements.

推荐答案

用<$ c替换 ForeignKey CredentialsModel中的$ c> OneToOneField

Replace ForeignKey with OneToOneField in CredentialsModel

这篇关于使用oauth2client.django_orm.Storage-class存储DriveAPI凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆