Skip to content
Browse files

Add assorted authenticated methods.

This adds methods for setting ratings and favorite status against
movies, as well as pulling lists of movies for which those have been
set. This adds a bypass in the cache to not operate on anything with a
lifetime of '0'.
  • Loading branch information...
1 parent 3debcd5 commit fb7c7cd3dfd4692e6c5acc61f0d2fd927b04d50e @wagnerrp wagnerrp committed Apr 14, 2012
Showing with 60 additions and 18 deletions.
  1. +2 −0 tmdb3/cache.py
  2. +6 −0 tmdb3/request.py
  3. +47 −14 tmdb3/tmdb_api.py
  4. +5 −4 tmdb3/tmdb_auth.py
View
2 tmdb3/cache.py
@@ -102,6 +102,8 @@ def __call__(self, *args, **kwargs):
raise TMDBCacheError('Cache.Cached must be provided a '+\
'callable object.')
return self.__class__(self.cache, self.callback, args[0])
+ elif self.inst.lifetime == 0:
+ return self.func(*args, **kwargs)
else:
key = self.callback()
data = self.cache.get(key)
View
6 tmdb3/request.py
@@ -81,11 +81,17 @@ def new(self, **kwargs):
obj.lifetime = self.lifetime
return obj
+ def add_data(self, data):
+ """Provide data to be sent with POST."""
+ urllib2.Request.add_data(self, urlencode(data))
+
def open(self):
"""Open a file object to the specified URL."""
try:
if DEBUG:
print 'loading '+self.get_full_url()
+ if self.has_data():
+ print ' '+self.get_data()
return urllib2.urlopen(self)
except urllib2.HTTPError, e:
raise TMDBHTTPError(str(e))
View
61 tmdb3/tmdb_api.py
@@ -22,7 +22,7 @@
Preliminary API specifications can be found at
http://help.themoviedb.org/kb/api/about-3"""
-__version__="v0.5.0"
+__version__="v0.6.0"
# 0.1.0 Initial development
# 0.2.0 Add caching mechanism for API queries
# 0.2.1 Temporary work around for broken search paging
@@ -42,6 +42,7 @@
# 0.4.5 Add locale fallthrough for images and alternate titles
# 0.4.6 Add slice support for search results
# 0.5.0 Rework cache framework and improve file cache performance
+# 0.6.0 Add user authentication support
from request import set_key, Request
from util import Datapoint, Datalist, Datadict, Element
@@ -64,26 +65,22 @@ def _populate(self):
Configuration = Configuration()
class Account( Element ):
- session = Datapoint('session', initarg=1, default=None)
-
- def _populate_account(self):
- if self.session is None:
- self.session = get_session()
- return Request('account', session_id=self.session.sessionid)
+ def _populate(self):
+ return Request('account', session_id=self._session.sessionid)
- id = Datapoint('id', poller=_populate_account)
- adult = Datapoint('include_adult', poller=_populate_account)
- country = Datapoint('iso_3166_1', poller=_populate_account)
- language = Datapoint('iso_639_1', poller=_populate_account)
- name = Datapoint('name', poller=_populate_account)
- username = Datapoint('username', poller=_populate_account)
+ id = Datapoint('id')
+ adult = Datapoint('include_adult')
+ country = Datapoint('iso_3166_1')
+ language = Datapoint('iso_639_1')
+ name = Datapoint('name')
+ username = Datapoint('username')
@property
def locale(self):
return get_locale(self.language, self.country)
def __repr__(self):
- return "<{0} {1.name}>".format(self.__class__.__name__, self)
+ return '<{0} "{1.name}">'.format(self.__class__.__name__, self)
def searchMovie(query, locale=None, adult=False):
return MovieSearchResult(
@@ -342,6 +339,28 @@ def toprated(cls, locale=None):
return res
@classmethod
+ def favorites(cls, session=None):
+ if session is None:
+ session = get_session()
+ account = Account(session=session)
+ res = MovieSearchResult(
+ Request('account/{0}/favorite_movies'.format(account.id),
+ session_id=session.sessionid))
+ res._name = "Favorites"
+ return res
+
+ @classmethod
+ def ratedmovies(cls, session=None):
+ if session is None:
+ session = get_session()
+ account = Account(session=session)
+ res = MovieSearchResult(
+ Request('account/{0}/rated_movies'.format(account.id),
+ session_id=session.sessionid))
+ res._name = "Movies You Rated"
+ return res
+
+ @classmethod
def fromIMDB(cls, imdbid, locale=None):
try:
# assume string
@@ -414,6 +433,20 @@ def _populate_translations(self):
apple_trailers = Datalist('quicktime', handler=AppleTrailer, poller=_populate_trailers)
translations = Datalist('translations', handler=Translation, poller=_populate_translations)
+ def setFavorite(self, value):
+ req = Request('account/{0}/favorite'.format(Account(session=self._session).id), session_id=self._session.sessionid)
+ req.add_data({'movie_id':self.id, 'favorite':str(bool(value)).lower()})
+ req.lifetime = 0
+ req.readJSON()
+
+ def setRating(self, value):
+ if not (0 <= value <= 10):
+ raise TMDBError("Ratings must be between '0' and '10'.")
+ req = Request('movie/{0}/favorite'.format(self.id), session_id=self._session.sessionid)
+ req.lifetime = 0
+ req.add_data({'value':value})
+ req.readJSON()
+
def __repr__(self):
if self.title is not None:
s = u"'{0}'".format(self.title)
View
9 tmdb3/tmdb_auth.py
@@ -60,6 +60,7 @@ def fromIso(cls, isotime, sep='T'):
return cls(*dt)
from request import Request
+from tmdb_exceptions import *
syssession = None
@@ -89,14 +90,14 @@ def __init__(self, sessionid):
def sessionid(self):
if self._sessionid is None:
if self._authtoken is None:
- raise RuntimeError("No Auth Token to produce Session for")
+ raise TMDBError("No Auth Token to produce Session for")
# TODO: check authtokenexpiration against current time
req = Request('authentication/session/new', \
request_token=self._authtoken)
req.lifetime = 0
dat = req.readJSON()
if not dat['success']:
- raise RuntimeError("Session generation failed")
+ raise TMDBError("Session generation failed")
self._sessionid = dat['session_id']
return self._sessionid
@@ -113,13 +114,13 @@ def sessionid(self, value):
@property
def authtoken(self):
if self.authenticated:
- raise RuntimeError("Session is already authenticated")
+ raise TMDBError("Session is already authenticated")
if self._authtoken is None:
req = Request('authentication/token/new')
req.lifetime = 0
dat = req.readJSON()
if not dat['success']:
- raise RuntimeError("Auth Token request failed")
+ raise TMDBError("Auth Token request failed")
self._authtoken = dat['request_token']
self._authtokenexpiration = datetime.fromIso(dat['expires_at'])
return self._authtoken

0 comments on commit fb7c7cd

Please sign in to comment.
Something went wrong with that request. Please try again.