Skip to content

Commit

Permalink
Added docstring and formated code to PEP8
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielgisoldo committed Sep 26, 2017
1 parent 2226150 commit 618277b
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 34 deletions.
2 changes: 1 addition & 1 deletion vimeo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
version = (0, 3, 10)

from .client import VimeoClient
from .exceptions import *
from . import exceptions
6 changes: 5 additions & 1 deletion vimeo/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@

from __future__ import absolute_import

class GrantFailed(Exception): pass

class GrantFailed(Exception):
"""Grant permission failed."""

pass
5 changes: 3 additions & 2 deletions vimeo/auth/authorization_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
except NameError:
basestring = str


class AuthorizationCodeMixin(AuthenticationMixinBase):
"""Implement helpers for the Authorization Code grant for OAuth2."""

Expand Down Expand Up @@ -46,8 +47,8 @@ def auth_url(self, scope, redirect, state):

def exchange_code(self, code, redirect):
"""Perform the exchange step for the code from the redirected user."""
code, headers, resp = self.call_grant('/oauth/access_token',
{
code, headers, resp = self.call_grant(
'/oauth/access_token', {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect
Expand Down
6 changes: 2 additions & 4 deletions vimeo/auth/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import requests


class AuthenticationMixinBase(object):
"""Provide core logic to the authentication mixins."""

Expand All @@ -15,9 +16,6 @@ def call_grant(self, path, data):
"""
assert self.app_info[0] is not None and self.app_info[1] is not None

resp = self.post(path,
auth=self.app_info,
jsonify=False,
data=data)
resp = self.post(path, auth=self.app_info, jsonify=False, data=data)

return resp.status_code, resp.headers, resp.json()
8 changes: 5 additions & 3 deletions vimeo/auth/client_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,18 @@
from .base import AuthenticationMixinBase
from . import GrantFailed


class ClientCredentialsMixin(AuthenticationMixinBase):
"""Implement the client credentials grant for Vimeo.
"""
Implement the client credentials grant for Vimeo.
This class should never be inited on it's own.
"""

def load_client_credentials(self):
"""Retrieve a client credentials token for this app."""
code, headers, resp = self.call_grant('/oauth/authorize/client',
{"grant_type": "client_credentials"})
code, headers, resp = self.call_grant(
'/oauth/authorize/client', {"grant_type": "client_credentials"})

if not code == 200:
raise GrantFailed()
Expand Down
9 changes: 6 additions & 3 deletions vimeo/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ class VimeoClient(ClientCredentialsMixin, AuthorizationCodeMixin, UploadMixin):
"""Client handle for the Vimeo API."""

API_ROOT = "https://api.vimeo.com"
HTTP_METHODS = set(('head', 'get', 'post', 'put', 'patch', 'options', 'delete'))
HTTP_METHODS = set(('head', 'get', 'post', 'put', 'patch', 'options',
'delete'))
ACCEPT_HEADER = "application/vnd.vimeo.*;version=3.2"
USER_AGENT = "pyvimeo 0.3.10; (http://developer.vimeo.com/api/docs)"

Expand All @@ -32,15 +33,16 @@ def __init__(self, token=None, key=None, secret=None, *args, **kwargs):
# Internally we back this with an auth mechanism for Requests.
@property
def token(self):
"""Get the token string from the class _BearerToken."""
return self._token.token

@token.setter
def token(self, value):
self._token = _BearerToken(value) if value else None

def __getattr__(self, name):
"""This is where we get the function for the verb that was just
requested.
"""
Method used to get the function for the verb that was just requested.
From here we can apply the authentication information we have.
"""
Expand Down Expand Up @@ -84,6 +86,7 @@ def caller(url, jsonify=True, **kwargs):

class _BearerToken(requests.auth.AuthBase):
"""Model the bearer token and apply it to the request."""

def __init__(self, token):
self.token = token

Expand Down
22 changes: 22 additions & 0 deletions vimeo/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@


class BaseVimeoException(Exception):
"""Base class for Vimeo Exceptions."""

def _get_message(self, response):
json = None
try:
Expand All @@ -16,6 +18,7 @@ def _get_message(self, response):
return message

def __init__(self, response, message):
"""Base Exception class init."""
# API error message
self.message = self._get_message(response)

Expand All @@ -26,60 +29,79 @@ def __init__(self, response, message):


class ObjectLoadFailure(Exception):
"""Object Load failure exception."""

def __init__(self, message):
"""Object Load failure exception init."""
super(ObjectLoadFailure, self).__init__(message)


class UploadTicketCreationFailure(BaseVimeoException):
"""Exception for upload tickt creation failure."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(UploadTicketCreationFailure, self).__init__(response, message)


class VideoCreationFailure(BaseVimeoException):
"""Exception for failure on the delete during the upload."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(VideoCreationFailure, self).__init__(response, message)


class VideoUploadFailure(BaseVimeoException):
"""Exception for failures during the actual upload od the file."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(VideoUploadFailure, self).__init__(response, message)


class PictureCreationFailure(BaseVimeoException):
"""Exception for failure on initial request to upload a picture."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(PictureCreationFailure, self).__init__(response, message)


class PictureUploadFailure(BaseVimeoException):
"""Exception for failure on the actual upload of the file."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(PictureUploadFailure, self).__init__(response, message)


class PictureActivationFailure(BaseVimeoException):
"""Exception for failure on activating the picture."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(PictureActivationFailure, self).__init__(response, message)


class TexttrackCreationFailure(BaseVimeoException):
"""Exception for failure on the initial request to upload a text track."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(TexttrackCreationFailure, self).__init__(response, message)


class TexttrackUploadFailure(BaseVimeoException):
"""Exception for failure on the actual upload of the file."""

def __init__(self, response, message):
"""Init method for this subclass of BaseVimeoException."""
super(TexttrackUploadFailure, self).__init__(response, message)


class APIRateLimitExceededFailure(BaseVimeoException):
"""Exception used when the user has exceeded the API rate limit."""

def _get_message(self, response):
guidelines = 'https://developer.vimeo.com/guidelines/rate-limiting'
Expand Down
56 changes: 36 additions & 20 deletions vimeo/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os
import io
import requests.exceptions
from .exceptions import *
from . import exceptions

try:
basestring
Expand Down Expand Up @@ -44,9 +44,9 @@ def replace(self, video_uri, filename, upgrade_to_1080=False):

def _perform_upload(self, filename, ticket):
"""Take an upload ticket and perform the actual upload."""

if ticket.status_code != 201:
raise UploadTicketCreationFailure(ticket, "Failed to create an upload ticket")
raise exceptions.UploadTicketCreationFailure(
ticket, "Failed to create an upload ticket")

ticket = ticket.json()

Expand All @@ -62,8 +62,8 @@ def _perform_upload(self, filename, ticket):
try:
self._make_pass(target, f, size, last_byte)
except requests.exceptions.Timeout:
# If there is a timeout here, we are okay with it, since
# we'll check and resume.
# If there is a timeout here, we are okay with it,
# since we'll check and resume.
pass
last_byte = self._get_progress(target, size)
except TypeError:
Expand All @@ -82,7 +82,8 @@ def _perform_upload(self, filename, ticket):
finalized_resp = self.delete(ticket['complete_uri'])

if finalized_resp.status_code != 201:
raise VideoCreationFailure(finalized_resp, "Failed to create the video")
raise exceptions.VideoCreationFailure(
finalized_resp, "Failed to create the video")

return finalized_resp.headers.get('Location', None)

Expand All @@ -98,7 +99,8 @@ def _get_progress(self, upload_target, filesize):
return int(last_byte)

def _make_pass(self, upload_target, f, size, last_byte):
"""Make a pass at uploading.
"""
Make a pass at uploading.
This particular function may do many things. If this is a large upload
it may terminate without having completed the upload. This can also
Expand All @@ -115,27 +117,34 @@ def _make_pass(self, upload_target, f, size, last_byte):
}, data=f)

if response.status_code != 200:
raise VideoUploadFailure(response, "Unexpected status code on upload")
raise exceptions.VideoUploadFailure(
response, "Unexpected status code on upload")


class UploadPictureMixin(object):
"""Functionality for uploading a picture to Vimeo for another object
"""
Class for uploading a picture to Vimeo.
Functionality for uploading a picture to Vimeo for another object
(video, user, etc).
"""

BASE_FIELDS = set(('link', 'uri'))

def upload_picture(self, obj, filename, activate=False, fields=None):
"""Upload a picture for the object.
"""
Upload a picture for the object.
The object (obj) can be the URI for the object or the response/parsed
json for it.
"""
if isinstance(obj, basestring):
obj = self.get(obj, params={'fields': 'metadata.connections.pictures.uri'})
obj = self.get(
obj, params={'fields': 'metadata.connections.pictures.uri'})

if obj.status_code != 200:
raise ObjectLoadFailure("Failed to load the target object")
raise exceptions.ObjectLoadFailure(
"Failed to load the target object")
obj = obj.json()

if isinstance(fields, basestring):
Expand All @@ -150,7 +159,8 @@ def upload_picture(self, obj, filename, activate=False, fields=None):
)

if picture.status_code != 201:
raise PictureCreationFailure(picture, "Failed to create a new picture with Vimeo.")
raise exceptions.PictureCreationFailure(
picture, "Failed to create a new picture with Vimeo.")

picture = picture.json()

Expand All @@ -160,27 +170,30 @@ def upload_picture(self, obj, filename, activate=False, fields=None):
data=f,
params={'fields': 'error'})
if upload_resp.status_code != 200:
raise PictureUploadFailure(upload_resp, "Failed uploading picture")
raise exceptions.PictureUploadFailure(
upload_resp, "Failed uploading picture")

if activate:
active = self.patch(
picture['uri'],
data={"active": "true"},
params={'fields': 'error'})
if active.status_code != 200:
raise PictureActivationFailure(active, "Failed activating picture")
raise exceptions.PictureActivationFailure(
active, "Failed activating picture")
picture['active'] = True

return picture


class UploadTexttrackMixin(object):
"""Functionality for uploading a texttrack to Vimeo for a video.
"""
"""Functionality for uploading a texttrack to Vimeo for a video."""

TEXTTRACK_ENDPOINT = '{video_uri}/texttracks'
BASE_FIELDS = set(('link',))

def upload_texttrack(self, video_uri, track_type, language, filename, fields=None):
def upload_texttrack(self, video_uri, track_type, language, filename,
fields=None):
"""Upload the texttrack at the given uri with the named source file."""
uri = self.TEXTTRACK_ENDPOINT.format(video_uri=video_uri)
name = filename.split('/')[-1]
Expand All @@ -197,18 +210,21 @@ def upload_texttrack(self, video_uri, track_type, language, filename, fields=Non
params={'fields': ','.join(fields)})

if texttrack.status_code != 201:
raise TexttrackCreationFailure(texttrack, "Failed to create a new texttrack with Vimeo")
raise exceptions.TexttrackCreationFailure(
texttrack, "Failed to create a new texttrack with Vimeo")

texttrack = texttrack.json()

with io.open(filename, 'rb') as f:
upload_resp = self.put(texttrack['link'], data=f)
if upload_resp.status_code != 200:
raise TexttrackUploadFailure(upload_resp, "Failed uploading texttrack")
raise exceptions.TexttrackUploadFailure(
upload_resp, "Failed uploading texttrack")

return texttrack


class UploadMixin(UploadVideoMixin, UploadPictureMixin, UploadTexttrackMixin):
"""Handle uploading to the Vimeo API."""

pass

0 comments on commit 618277b

Please sign in to comment.