Storage of DriveAPI credentials using oauth2client.django_orm.Storage-class

 ̄綄美尐妖づ 提交于 2019-12-23 02:44:21

问题


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.


回答1:


Replace ForeignKey with OneToOneField in CredentialsModel



来源:https://stackoverflow.com/questions/25059386/storage-of-driveapi-credentials-using-oauth2client-django-orm-storage-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!