2 from django.db import models
3 from django.contrib.auth.models import User
4 from requests_oauthlib import OAuth2Session
5 from .settings import YOUTUBE_CLIENT_ID, YOUTUBE_CLIENT_SECRET, YOUTUBE_TOKEN_URL
8 class OAuthConnection(models.Model):
9 user = models.ForeignKey(User, models.CASCADE)
10 access = models.BooleanField(default=False)
11 token = models.CharField(max_length=64, null=True, blank=True)
12 token_secret = models.CharField(max_length=64, null=True, blank=True)
17 return cls.objects.get(user=user)
18 except cls.DoesNotExist:
24 class YouTubeToken(models.Model):
25 token = models.TextField()
27 def token_updater(self, token):
28 self.token = json.dumps(token)
31 def get_session(self):
33 client_id=YOUTUBE_CLIENT_ID,
34 auto_refresh_url=YOUTUBE_TOKEN_URL,
35 token=json.loads(self.token),
36 auto_refresh_kwargs={'client_id':YOUTUBE_CLIENT_ID,'client_secret':YOUTUBE_CLIENT_SECRET},
37 token_updater=self.token_updater
40 def call(self, method, url, params=None, data=None, media_data=None):
42 params['uploadType'] = 'resumable'
44 session = self.get_session()
45 response = session.request(
51 'X-Upload-Content-Length': str(len(media_data)),
52 'x-upload-content-type': 'application/octet-stream',
55 location = response.headers['Location']
59 headers={"Content-Type": "application/octet-stream"},