Skip to content

Instantly share code, notes, and snippets.

@emre
Created February 1, 2011 00:16
Show Gist options
  • Select an option

  • Save emre/805137 to your computer and use it in GitHub Desktop.

Select an option

Save emre/805137 to your computer and use it in GitHub Desktop.
TMDB icin python wrapper
# -*- coding: utf8 -*-
import urllib, simplejson
class TMDBException(Exception):
"""
custom exception class for TMDB errors.
"""
pass
class TMDB(object):
"""
base class for the TMDB api wrapper.
"""
TMDB_API_URL = 'http://api.themoviedb.org/2.1'
DEFAULT_LANGUAGE = 'en'
DEFAULT_RESULT_TYPE = 'json'
def __init__(self, apiKey):
self.setApiKey(apiKey)
def setApiKey(self, apiKey):
"""
sets api_key attribute.
@params:
- apiKey (string)
@return void
"""
self.api_key = apiKey
def getApiKey(self):
"""
gets api_key attribute.
@return string
"""
return self.api_key
def query(self, method, baseParameters = None, queryParameters = None, language = None):
"""
main query method for tmdb api.
@params:
- method (string)
- baseParameters (list)
- queryParameters (dict)
- language (string)
- result type (string)
"""
result_type = TMDB.DEFAULT_RESULT_TYPE
url = '%s/%s/%s/%s/%s' % (TMDB.TMDB_API_URL, method, language, result_type, self.getApiKey())
if baseParameters:
if not isinstance(baseParameters, list):
raise TMDBException("baseParameters must be a list not %s." % type(baseParameters).__name__)
queryString = "/"
for parameter in baseParameters:
queryString += parameter + '/'
url += queryString[:-1]
if queryParameters:
url += '?' + urllib.urlencode(queryParameters)
data = urllib.urlopen(url).read()
try:
data = {
"result" : simplejson.loads(data),
}
except simplejson.decoder.JSONDecodeError:
data = {
"result": None,
}
if data.get("result") == ['Nothing found.']:
data["result"] = None
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment