2
# -*- coding: utf-8 -*-
3
#-----------------------
4
# Name: tmdb_request.py
6
# Author: Raymond Wagner
7
# Purpose: Wrapped urllib2.Request class pre-configured for accessing the
9
#-----------------------
11
from tmdb_exceptions import *
12
from cache import Cache
21
cache = Cache('pytmdb3.cache')
25
Specify the API key to use retrieving data from themoviedb.org. This
26
key must be set before any calls will function.
28
# MythTV key: c27cb71cff5bd76e1a7a009380562c62
30
raise TMDBKeyInvalid("Specified API key must be 128-bit hex")
34
raise TMDBKeyInvalid("Specified API key must be 128-bit hex")
35
Request._api_key = key
37
class Request( urllib2.Request ):
39
_base_url = "http://api.themoviedb.org/3/"
43
if self._api_key is None:
44
raise TMDBKeyMissing("API key must be specified before "+\
45
"requests can be made")
48
def __init__(self, url, **kwargs):
49
"""Return a request object, using specified API path and arguments."""
50
kwargs['api_key'] = self.api_key
51
self._url = url.lstrip('/')
53
url = '{0}{1}?{2}'.format(self._base_url, self._url,
54
urllib.urlencode(kwargs))
55
urllib2.Request.__init__(self, url)
56
self.add_header('Accept', 'application/json')
57
self.lifetime = 3600 # 1hr
59
def new(self, **kwargs):
60
"""Create a new instance of the request, with tweaked arguments."""
61
args = dict(self._kwargs)
62
for k,v in kwargs.items():
68
obj = self.__class__(self._url, **args)
69
obj.lifetime = self.lifetime
73
"""Open a file object to the specified URL."""
76
print 'loading '+self.get_full_url()
77
return urllib2.urlopen(self)
78
except urllib2.HTTPError, e:
79
raise TMDBHTTPError(str(e))
82
"""Return result from specified URL as a string."""
83
return self.open().read()
85
@cache.cached(urllib2.Request.get_full_url)
87
"""Parse result from specified URL as JSON data."""
88
url = self.get_full_url()
89
data = json.load(self.open())
90
handle_status(data, url)
93
pprint.PrettyPrinter().pprint(data)
98
2: TMDBRequestError('Invalid service - This service does not exist.'),
99
3: TMDBRequestError('Authentication Failed - You do not have '+\
100
'permissions to access this service.'),
101
4: TMDBRequestError("Invalid format - This service doesn't exist "+\
103
5: TMDBRequestError('Invalid parameters - Your request parameters '+\
105
6: TMDBRequestError('Invalid id - The pre-requisite id is invalid '+\
107
7: TMDBKeyInvalid('Invalid API key - You must be granted a valid key.'),
108
8: TMDBRequestError('Duplicate entry - The data you tried to submit '+\
110
9: TMDBOffline('This service is tempirarily offline. Try again later.'),
111
10: TMDBKeyRevoked('Suspended API key - Access to your account has been '+\
112
'suspended, contact TMDB.'),
113
11: TMDBError('Internal error - Something went wrong. Contact TMDb.'),
116
14: TMDBRequestError('Authentication Failed.'),
117
15: TMDBError('Failed'),
118
16: TMDBError('Device Denied'),
119
17: TMDBError('Session Denied')}
121
def handle_status(data, query):
122
status = status_handlers[data.get('status_code', 1)]
123
if status is not None: