Projects
Multimedia
python-tvdb_api
Sign Up
Log In
Username
Password
Sorry, you are not authorized to perform this action.
×
We truncated the diff of some files because they were too big. If you want to see the full diff for every file,
click here
.
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
Expand all
Collapse all
Changes of Revision 3
View file
python-tvdb_api.changes
Changed
@@ -1,4 +1,14 @@ ------------------------------------------------------------------- +Thu Nov 1 16:49:30 UTC 2018 - Aliaksei Padvalski <avvissu@yandex.by> + +- Update to 2.0: + * Switch to TheTVDB new JSON based API - issue #57 +- Add support for Python3 +- Fix: non-executable-script +- Update to description +- Spec file cleanup + +------------------------------------------------------------------- Fri Apr 21 12:40:16 UTC 2017 - aloisio@gmx.com - Update to version 1.10
View file
python-tvdb_api.spec
Changed
@@ -1,6 +1,7 @@ # # spec file for package python-tvdb_api # +# Copyright (c) 2018 SUSE LINUX GmbH, Nuernberg, Germany. # Copyright (c) 2017 Packman Team <packman@links2linux.de> # # All modifications and additions to the file contributed by third parties @@ -16,42 +17,60 @@ # -%define modname tvdb_api +%{?!python_module:%define python_module() %{!?skip_python2:python-%{**}} %{!?skip_python3:python3-%{**}}} Name: python-tvdb_api -Version: 1.10 +Version: 2.0 Release: 0 -Summary: Python module to access the API from thetvdb.com +Summary: Interface to thetvdb.com # The UnLicense (https://unlicense.org) License: SUSE-Permissive Group: Productivity/Multimedia/Other -Url: https://github.com/dbr/tvdb_api/tree/master -Source0: https://files.pythonhosted.org/packages/source/t/%{modname}/%{modname}-%{version}.tar.gz -BuildRequires: python-devel -BuildRequires: python-setuptools -BuildRoot: %{_tmppath}/%{name}-%{version}-build +URL: https://github.com/dbr/tvdb_api +Source0: https://files.pythonhosted.org/packages/source/t/tvdb_api/tvdb_api-%{version}.tar.gz +BuildRequires: %{python_module devel} +BuildRequires: %{python_module rpm-macros} +BuildRequires: %{python_module setuptools} +BuildRequires: fdupes +Requires: python-requests-cache BuildArch: noarch -%py_requires +%python_subpackages %description -tvdb_api is an easy to use interface to thetvdb.com via python +An easy to use API interface to TheTVDB.com. %prep -%setup -q -n %{modname}-%{version} -for file in {tvdb_cache,tvdb_api,tvdb_ui,tvdb_exceptions} -do - sed -i "1d" $file.py -done +%setup -q -n tvdb_api-%{version} %build -python setup.py build +%python_build %install -python setup.py install --root=%{buildroot} --prefix=%{_prefix} +%python_install + +# Fix: non-executable-script +%{python_expand \ +pushd %{buildroot}%{$python_sitelib} +for _file in $(grep -rl '^\#\!\/'); do + find -name ${_file##*/} -type f -not -perm /111 -exec sed '/^\#\!\//d' -i {} + + find -name ${_file##*/} -type f -perm /111 -exec sed 's|#!%{_bindir}/env python|#!%__$python|' -i {} + +done +popd +} + +%if 0%{?have_python2} +%py_compile %{buildroot}%{python2_sitelib} +%py_compile -O %{buildroot}%{python2_sitelib} +%endif +%if 0%{?have_python3} +%py3_compile %{buildroot}%{python3_sitelib} +%py3_compile -O %{buildroot}%{python3_sitelib} +%endif +# + +%python_expand %fdupes %{buildroot}%{$python_sitelib} -%files -%defattr(-,root,root) +%files %{python_files} %doc UNLICENSE readme.md -%{python_sitelib}/tvdb_*.py* -%{python_sitelib}/%{modname}-%{version}-py%{python_version}.egg-info +%{python_sitelib}/* %changelog
View file
tvdb_api-1.10.tar.gz/tvdb_cache.py
Deleted
@@ -1,251 +0,0 @@ -#!/usr/bin/env python -#encoding:utf-8 -#author:dbr/Ben -#project:tvdb_api -#repository:http://github.com/dbr/tvdb_api -#license:unlicense (http://unlicense.org/) - -""" -urllib2 caching handler -Modified from http://code.activestate.com/recipes/491261/ -""" -from __future__ import with_statement - -__author__ = "dbr/Ben" -__version__ = "1.10" - -import os -import time -import errno -import httplib -import urllib2 -import StringIO -from hashlib import md5 -from threading import RLock - -cache_lock = RLock() - -def locked_function(origfunc): - """Decorator to execute function under lock""" - def wrapped(*args, **kwargs): - cache_lock.acquire() - try: - return origfunc(*args, **kwargs) - finally: - cache_lock.release() - return wrapped - -def calculate_cache_path(cache_location, url): - """Checks if cache_location/hash_of_url.headers and .body exist - """ - thumb = md5(url).hexdigest() - header = os.path.join(cache_location, thumb + ".headers") - body = os.path.join(cache_location, thumb + ".body") - return header, body - -def check_cache_time(path, max_age): - """Checks if a file has been created/modified in the last max_age seconds. - False means the file is too old (or doesn't exist), True means it is - up-to-date and valid""" - if not os.path.isfile(path): - return False - cache_modified_time = os.stat(path).st_mtime - time_now = time.time() - if cache_modified_time < time_now - max_age: - # Cache is old - return False - else: - return True - -@locked_function -def exists_in_cache(cache_location, url, max_age): - """Returns if header AND body cache file exist (and are up-to-date)""" - hpath, bpath = calculate_cache_path(cache_location, url) - if os.path.exists(hpath) and os.path.exists(bpath): - return( - check_cache_time(hpath, max_age) - and check_cache_time(bpath, max_age) - ) - else: - # File does not exist - return False - -@locked_function -def store_in_cache(cache_location, url, response): - """Tries to store response in cache.""" - hpath, bpath = calculate_cache_path(cache_location, url) - try: - outf = open(hpath, "wb") - headers = str(response.info()) - outf.write(headers) - outf.close() - - outf = open(bpath, "wb") - outf.write(response.read()) - outf.close() - except IOError: - return True - else: - return False - -@locked_function -def delete_from_cache(cache_location, url): - """Deletes a response in cache.""" - hpath, bpath = calculate_cache_path(cache_location, url) - try: - if os.path.exists(hpath): - os.remove(hpath) - if os.path.exists(bpath): - os.remove(bpath) - except IOError: - return True - else: - return False - -class CacheHandler(urllib2.BaseHandler): - """Stores responses in a persistant on-disk cache. - - If a subsequent GET request is made for the same URL, the stored - response is returned, saving time, resources and bandwidth - """ - @locked_function - def __init__(self, cache_location, max_age = 21600): - """The location of the cache directory""" - self.max_age = max_age - self.cache_location = cache_location - if not os.path.exists(self.cache_location): - try: - os.mkdir(self.cache_location) - except OSError, e: - if e.errno == errno.EEXIST and os.path.isdir(self.cache_location): - # File exists, and it's a directory, - # another process beat us to creating this dir, that's OK. - pass - else: - # Our target dir is already a file, or different error, - # relay the error! - raise - - def default_open(self, request): - """Handles GET requests, if the response is cached it returns it - """ - if request.get_method() is not "GET": - return None # let the next handler try to handle the request - - if exists_in_cache( - self.cache_location, request.get_full_url(), self.max_age - ): - return CachedResponse( - self.cache_location, - request.get_full_url(), - set_cache_header = True - ) - else: - return None - - def http_response(self, request, response): - """Gets a HTTP response, if it was a GET request and the status code - starts with 2 (200 OK etc) it caches it and returns a CachedResponse - """ - if (request.get_method() == "GET" - and str(response.code).startswith("2") - ): - if 'x-local-cache' not in response.info(): - # Response is not cached - set_cache_header = store_in_cache( - self.cache_location, - request.get_full_url(), - response - ) - else: - set_cache_header = True - - return CachedResponse( - self.cache_location, - request.get_full_url(), - set_cache_header = set_cache_header - ) - else: - return response - -class CachedResponse(StringIO.StringIO): - """An urllib2.response-like object for cached responses. - - To determine if a response is cached or coming directly from - the network, check the x-local-cache header rather than the object type. - """ - - @locked_function - def __init__(self, cache_location, url, set_cache_header=True): - self.cache_location = cache_location - hpath, bpath = calculate_cache_path(cache_location, url) - - StringIO.StringIO.__init__(self, file(bpath, "rb").read()) - - self.url = url - self.code = 200 - self.msg = "OK" - headerbuf = file(hpath, "rb").read() - if set_cache_header: - headerbuf += "x-local-cache: %s\r\n" % (bpath) - self.headers = httplib.HTTPMessage(StringIO.StringIO(headerbuf)) - - def info(self): - """Returns headers - """ - return self.headers - - def geturl(self): - """Returns original URL
View file
tvdb_api-1.10.tar.gz/PKG-INFO -> tvdb_api-2.0.tar.gz/PKG-INFO
Changed
@@ -1,6 +1,6 @@ Metadata-Version: 1.1 Name: tvdb_api -Version: 1.10 +Version: 2.0 Summary: Interface to thetvdb.com Home-page: http://github.com/dbr/tvdb_api/tree/master Author: dbr/Ben @@ -14,7 +14,7 @@ >>> ep = t'My Name Is Earl'122 >>> ep <Episode 01x22 - Stole a Badge> - >>> ep'episodename' + >>> ep'episodeName' u'Stole a Badge' Platform: UNKNOWN @@ -27,6 +27,8 @@ Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 Classifier: Topic :: Multimedia Classifier: Topic :: Utilities Classifier: Topic :: Software Development :: Libraries :: Python Modules
View file
tvdb_api-1.10.tar.gz/Rakefile -> tvdb_api-2.0.tar.gz/Rakefile
Changed
@@ -47,7 +47,7 @@ end desc "Upload current version to PyPi" -task :topypi do +task :topypi => :test do cur_file = File.open("tvdb_api.py").read() tvdb_api_version = cur_file.scan(/__version__ = "(.*)"/) tvdb_api_version = tvdb_api_version00
View file
tvdb_api-1.10.tar.gz/readme.md -> tvdb_api-2.0.tar.gz/readme.md
Changed
@@ -65,7 +65,7 @@ The data is stored in an attribute named `data`, within the Show instance: >>> t'scrubs'.data.keys() - 'networkid', 'rating', 'airs_dayofweek', 'contentrating', 'seriesname', 'id', 'airs_time', 'network', 'fanart', 'lastupdated', 'actors', 'ratingcount', 'status', 'added', 'poster', 'imdb_id', 'genre', 'banner', 'seriesid', 'language', 'zap2it_id', 'addedby', 'tms_wanted', 'firstaired', 'runtime', 'overview' + 'networkid', 'rating', 'airs_dayofweek', 'contentrating', 'seriesname', 'id', 'airs_time', 'network', 'fanart', 'lastupdated', 'actors', 'ratingcount', 'status', 'added', 'poster', 'tms_wanted_old', 'imdb_id', 'genre', 'banner', 'seriesid', 'language', 'zap2it_id', 'addedby', 'firstaired', 'runtime', 'overview' Although each element is also accessible via `t'scrubs'` for ease-of-use: @@ -105,7 +105,7 @@ Remember a simple list of actors is accessible via the default Show data: >>> t'scrubs''actors' - u'|Zach Braff|Donald Faison|Sarah Chalke|Christa Miller|Aloma Wright|Robert Maschio|Sam Lloyd|Neil Flynn|Ken Jenkins|Judy Reyes|John C. McGinley|Travis Schuldt|Johnny Kastl|Heather Graham|Michael Mosley|Kerry Bish\xe9|Dave Franco|Eliza Coupe|' + u'|Zach Braff|Donald Faison|Sarah Chalke|Judy Reyes|John C. McGinley|Neil Flynn|Ken Jenkins|Christa Miller|Aloma Wright|Robert Maschio|Sam Lloyd|Travis Schuldt|Johnny Kastl|Heather Graham|Michael Mosley|Kerry Bish\xe9|Dave Franco|Eliza Coupe|' tvdb: http://thetvdb.com tvnamer: http://github.com/dbr/tvnamer
View file
tvdb_api-1.10.tar.gz/setup.py -> tvdb_api-2.0.tar.gz/setup.py
Changed
@@ -1,25 +1,34 @@ import sys from setuptools import setup +from setuptools.command.test import test as TestCommand -IS_PY2 = sys.version_info0 == 2 -_requirements = -if not IS_PY2: - _requirements.append('requests_cache') +class PyTest(TestCommand): + user_options = ('pytest-args=', 'a', "Arguments to pass to py.test") - # 'requests' is installed as requirement by requests-cache, - # commented out because it triggers a bug in setuptool: - # https://bitbucket.org/pypa/setuptools/issue/196/tests_require-pytest-pytest-cov-breaks + def initialize_options(self): + TestCommand.initialize_options(self) + self.pytest_args = + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = + self.test_suite = True + def run_tests(self): + #import here, cause outside the eggs aren't loaded + import pytest + errno = pytest.main(self.pytest_args) + sys.exit(errno) + + +_requirements = 'requests_cache', 'requests' _modules = 'tvdb_api', 'tvdb_ui', 'tvdb_exceptions' -if IS_PY2: - _modules.append('tvdb_cache') setup( name = 'tvdb_api', -version='1.10', +version='2.0', author='dbr/Ben', description='Interface to thetvdb.com', @@ -35,13 +44,16 @@ >>> ep = t'My Name Is Earl'122 >>> ep <Episode 01x22 - Stole a Badge> ->>> ep'episodename' +>>> ep'episodeName' u'Stole a Badge' """, py_modules = _modules, install_requires = _requirements, +tests_require='pytest', +cmdclass = {'test': PyTest}, + classifiers= "Intended Audience :: Developers", "Natural Language :: English", @@ -52,6 +64,8 @@ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", "Topic :: Multimedia", "Topic :: Utilities", "Topic :: Software Development :: Libraries :: Python Modules",
View file
tvdb_api-1.10.tar.gz/tests/test_tvdb_api.py -> tvdb_api-2.0.tar.gz/tests/test_tvdb_api.py
Changed
@@ -11,75 +11,58 @@ import os import sys import datetime -import unittest +import pytest # Force parent directory onto path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import tvdb_api -import tvdb_ui from tvdb_api import (tvdb_shownotfound, tvdb_seasonnotfound, -tvdb_episodenotfound, tvdb_attributenotfound) + tvdb_episodenotfound, tvdb_attributenotfound) -IS_PY2 = sys.version_info0 == 2 - - -class test_tvdb_basic(unittest.TestCase): +class TestTvdbBasic: # Used to store the cached instance of Tvdb() t = None - - def setUp(self): - if self.t is None: - self.__class__.t = tvdb_api.Tvdb(cache = True, banners = False) - + + @classmethod + def setup_class(cls): + if cls.t is None: + cls.t = tvdb_api.Tvdb(cache=True, banners=False) + def test_different_case(self): """Checks the auto-correction of show names is working. It should correct the weirdly capitalised 'sCruBs' to 'Scrubs' """ - self.assertEquals(self.t'scrubs'14'episodename', 'My Old Lady') - self.assertEquals(self.t'sCruBs''seriesname', 'Scrubs') + assert self.t'scrubs'14'episodeName' == 'My Old Lady' + assert self.t'sCruBs''seriesName' == 'Scrubs' def test_spaces(self): """Checks shownames with spaces """ - self.assertEquals(self.t'My Name Is Earl''seriesname', 'My Name Is Earl') - self.assertEquals(self.t'My Name Is Earl'14'episodename', 'Faked His Own Death') + assert self.t'My Name Is Earl''seriesName' == 'My Name Is Earl' + assert self.t'My Name Is Earl'14'episodeName' == 'Faked My Own Death' def test_numeric(self): """Checks numeric show names """ - self.assertEquals(self.t'24'220'episodename', 'Day 2: 3:00 A.M.-4:00 A.M.') - self.assertEquals(self.t'24''seriesname', '24') + assert self.t'24'220'episodeName' == 'Day 2: 3:00 A.M. - 4:00 A.M.' + assert self.t'24''seriesName' == '24' def test_show_iter(self): """Iterating over a show returns each seasons """ - self.assertEquals( - len( - season for season in self.t'Life on Mars' - ), - 2 - ) - + assert len(season for season in self.t'Life on Mars') == 2 + def test_season_iter(self): """Iterating over a show returns episodes """ - self.assertEquals( - len( - episode for episode in self.t'Life on Mars'1 - ), - 8 - ) + assert len(episode for episode in self.t'Life on Mars'1) == 8 def test_get_episode_overview(self): """Checks episode overview is retrieved correctly. """ - self.assertEquals( - self.t'Battlestar Galactica (2003)'16'overview'.startswith( - 'When a new copy of Doral, a Cylon who had been previously'), - True - ) + assert self.t'Battlestar Galactica (2003)'16'overview'.startswith('When a new copy of Doral, a Cylon who had been previously') == True def test_get_parent(self): """Check accessing series from episode instance @@ -88,329 +71,251 @@ season = show1 episode = show11 - self.assertEquals( - season.show, - show - ) - - self.assertEquals( - episode.season, - season - ) - - self.assertEquals( - episode.season.show, - show - ) + assert season.show == show + assert episode.season == season + assert episode.season.show == show def test_no_season(self): show = self.t'Katekyo Hitman Reborn' print(tvdb_api) print(show11) -class test_tvdb_errors(unittest.TestCase): - # Used to store the cached instance of Tvdb() + +class TestTvdbErrors: t = None - - def setUp(self): - if self.t is None: - self.__class__.t = tvdb_api.Tvdb(cache = True, banners = False) + + @classmethod + def setup_class(cls): + if cls.t is None: + cls.t = tvdb_api.Tvdb(cache=True, banners=False) def test_seasonnotfound(self): """Checks exception is thrown when season doesn't exist. """ - self.assertRaises(tvdb_seasonnotfound, lambda:self.t'CNNNN'101) + with pytest.raises(tvdb_seasonnotfound): + self.t'CNNNN'10 def test_shownotfound(self): """Checks exception is thrown when episode doesn't exist. """ - self.assertRaises(tvdb_shownotfound, lambda:self.t'the fake show thingy') - + with pytest.raises(tvdb_shownotfound): + self.t'the fake show thingy' + def test_episodenotfound(self): """Checks exception is raised for non-existent episode """ - self.assertRaises(tvdb_episodenotfound, lambda:self.t'Scrubs'130) + with pytest.raises(tvdb_episodenotfound): + self.t'Scrubs'130 def test_attributenamenotfound(self): """Checks exception is thrown for if an attribute isn't found. """ - self.assertRaises(tvdb_attributenotfound, lambda:self.t'CNNNN'16'afakeattributething') - self.assertRaises(tvdb_attributenotfound, lambda:self.t'CNNNN''afakeattributething') + with pytest.raises(tvdb_attributenotfound): + self.t'CNNNN'16'afakeattributething' + self.t'CNNNN''afakeattributething' -class test_tvdb_search(unittest.TestCase): + +class TestTvdbSearch: # Used to store the cached instance of Tvdb() t = None - - def setUp(self): - if self.t is None: - self.__class__.t = tvdb_api.Tvdb(cache = True, banners = False) + + @classmethod + def setup_class(cls): + if cls.t is None: + cls.t = tvdb_api.Tvdb(cache=True, banners=False) def test_search_len(self): """There should be only one result matching """ - self.assertEquals(len(self.t'My Name Is Earl'.search('Faked His Own Death')), 1) + assert len(self.t'My Name Is Earl'.search('Faked My Own Death')) == 1 def test_search_checkname(self): """Checks you can get the episode name of a search result """ - self.assertEquals(self.t'Scrubs'.search('my first')0'episodename', 'My First Day') - self.assertEquals(self.t'My Name Is Earl'.search('Faked His Own Death')0'episodename', 'Faked His Own Death') - + assert self.t'Scrubs'.search('my first')0'episodeName' == 'My First Day' + assert self.t'My Name Is Earl'.search('Faked My Own Death')0'episodeName' == 'Faked My Own Death' + def test_search_multiresults(self): """Checks search can return multiple results
View file
tvdb_api-1.10.tar.gz/tvdb_api.egg-info/PKG-INFO -> tvdb_api-2.0.tar.gz/tvdb_api.egg-info/PKG-INFO
Changed
@@ -1,6 +1,6 @@ Metadata-Version: 1.1 Name: tvdb-api -Version: 1.10 +Version: 2.0 Summary: Interface to thetvdb.com Home-page: http://github.com/dbr/tvdb_api/tree/master Author: dbr/Ben @@ -14,7 +14,7 @@ >>> ep = t'My Name Is Earl'122 >>> ep <Episode 01x22 - Stole a Badge> - >>> ep'episodename' + >>> ep'episodeName' u'Stole a Badge' Platform: UNKNOWN @@ -27,6 +27,8 @@ Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 Classifier: Topic :: Multimedia Classifier: Topic :: Utilities Classifier: Topic :: Software Development :: Libraries :: Python Modules
View file
tvdb_api-1.10.tar.gz/tvdb_api.egg-info/SOURCES.txt -> tvdb_api-2.0.tar.gz/tvdb_api.egg-info/SOURCES.txt
Changed
@@ -4,7 +4,6 @@ readme.md setup.py tvdb_api.py -tvdb_cache.py tvdb_exceptions.py tvdb_ui.py tests/gprof2dot.py @@ -13,4 +12,5 @@ tvdb_api.egg-info/PKG-INFO tvdb_api.egg-info/SOURCES.txt tvdb_api.egg-info/dependency_links.txt +tvdb_api.egg-info/requires.txt tvdb_api.egg-info/top_level.txt \ No newline at end of file
View file
tvdb_api-2.0.tar.gz/tvdb_api.egg-info/requires.txt
Added
@@ -0,0 +1,2 @@ +requests_cache +requests
View file
tvdb_api-1.10.tar.gz/tvdb_api.egg-info/top_level.txt -> tvdb_api-2.0.tar.gz/tvdb_api.egg-info/top_level.txt
Changed
@@ -1,4 +1,3 @@ tvdb_api -tvdb_ui tvdb_exceptions -tvdb_cache +tvdb_ui
View file
tvdb_api-1.10.tar.gz/tvdb_api.py -> tvdb_api-2.0.tar.gz/tvdb_api.py
Changed
@@ -1,9 +1,9 @@ #!/usr/bin/env python -#encoding:utf-8 -#author:dbr/Ben -#project:tvdb_api -#repository:http://github.com/dbr/tvdb_api -#license:unlicense (http://unlicense.org/) +# encoding:utf-8 +# author:dbr/Ben +# project:tvdb_api +# repository:http://github.com/dbr/tvdb_api +# license:unlicense (http://unlicense.org/) """Simple-to-use Python interface to The TVDB's API (thetvdb.com) @@ -11,42 +11,38 @@ >>> from tvdb_api import Tvdb >>> t = Tvdb() ->>> t'Lost'411'episodename' +>>> t'Lost'411'episodeName' u'Cabin Fever' """ -__author__ = "dbr/Ben" -__version__ = "1.10" -import sys +__author__ = "dbr/Ben" +__version__ = "2.0" -IS_PY2 = sys.version_info0 == 2 +import sys import os import time -if IS_PY2: - import urllib - import urllib2 - from tvdb_cache import CacheHandler - from urllib import quote as url_quote -else: - import requests - from urllib.parse import quote as url_quote +import types import getpass import tempfile import warnings import logging import datetime -import zipfile +import hashlib -try: - import xml.etree.cElementTree as ElementTree -except ImportError: - import xml.etree.ElementTree as ElementTree +import requests +import requests_cache +from requests_cache.backends.base import _to_bytes, _DEFAULT_HEADERS -try: - import gzip -except ImportError: - gzip = None + +IS_PY2 = sys.version_info0 == 2 + +if IS_PY2: + user_input = raw_input + from urllib import quote as url_quote +else: + from urllib.parse import quote as url_quote + user_input = input if IS_PY2: @@ -56,17 +52,217 @@ int_types = int text_type = str - -from tvdb_ui import BaseUI, ConsoleUI -from tvdb_exceptions import (tvdb_error, tvdb_userabort, tvdb_shownotfound, - tvdb_seasonnotfound, tvdb_episodenotfound, tvdb_attributenotfound) - lastTimeout = None + def log(): return logging.getLogger("tvdb_api") +## Exceptions + +class tvdb_exception(Exception): + """Any exception generated by tvdb_api + """ + pass + +class tvdb_error(tvdb_exception): + """An error with thetvdb.com (Cannot connect, for example) + """ + pass + +class tvdb_userabort(tvdb_exception): + """User aborted the interactive selection (via + the q command, ^c etc) + """ + pass + +class tvdb_notauthorized(tvdb_exception): + """An authorization error with thetvdb.com + """ + pass + +class tvdb_shownotfound(tvdb_exception): + """Show cannot be found on thetvdb.com (non-existant show) + """ + pass + +class tvdb_seasonnotfound(tvdb_exception): + """Season cannot be found on thetvdb.com + """ + pass + +class tvdb_episodenotfound(tvdb_exception): + """Episode cannot be found on thetvdb.com + """ + pass + +class tvdb_resourcenotfound(tvdb_exception): + """Resource cannot be found on thetvdb.com + """ + pass + +class tvdb_invalidlanguage(tvdb_exception): + """invalid language given on thetvdb.com + """ + def __init__(self, value): + self.value = value + + def __str__(self): + return repr(self.value) + +class tvdb_attributenotfound(tvdb_exception): + """Raised if an episode does not have the requested + attribute (such as a episode name) + """ + pass + + +## UI + +class BaseUI(object): + """Base user interface for Tvdb show selection. + + Selects first show. + + A UI is a callback. A class, it's __init__ function takes two arguments: + + - config, which is the Tvdb config dict, setup in tvdb_api.py + - log, which is Tvdb's logger instance (which uses the logging module). You can + call log.info() log.warning() etc + + It must have a method "selectSeries", this is passed a list of dicts, each dict + contains the the keys "name" (human readable show name), and "sid" (the shows + ID as on thetvdb.com). For example: + + {'name': u'Lost', 'sid': u'73739'}, + {'name': u'Lost Universe', 'sid': u'73181'} + + The "selectSeries" method must return the appropriate dict, or it can raise + tvdb_userabort (if the selection is aborted), tvdb_shownotfound (if the show + cannot be found). + + A simple example callback, which returns a random series: + + >>> import random + >>> from tvdb_ui import BaseUI + >>> class RandomUI(BaseUI): + ... def selectSeries(self, allSeries): + ... import random + ... return random.choice(allSeries) + + Then to use it.. + + >>> from tvdb_api import Tvdb + >>> t = Tvdb(custom_ui = RandomUI) + >>> random_matching_series = t'Lost' + >>> type(random_matching_series) + <class 'tvdb_api.Show'> + """ + def __init__(self, config, log = None): + self.config = config + if log is not None: + warnings.warn("the UI's log parameter is deprecated, instead use\n" + "use import logging; logging.getLogger('ui').info('blah')\n" + "The self.log attribute will be removed in the next version") + self.log = logging.getLogger(__name__) +
View file
tvdb_api-1.10.tar.gz/tvdb_exceptions.py -> tvdb_api-2.0.tar.gz/tvdb_exceptions.py
Changed
@@ -9,44 +9,20 @@ """ __author__ = "dbr/Ben" -__version__ = "1.10" +__version__ = "2.0" -__all__ = "tvdb_error", "tvdb_userabort", "tvdb_shownotfound", -"tvdb_seasonnotfound", "tvdb_episodenotfound", "tvdb_attributenotfound" +import logging -class tvdb_exception(Exception): - """Any exception generated by tvdb_api - """ - pass +__all__ = "tvdb_error", "tvdb_userabort", "tvdb_notauthorized", "tvdb_shownotfound", +"tvdb_seasonnotfound", "tvdb_episodenotfound", "tvdb_attributenotfound", +"tvdb_resourcenotfound", "tvdb_invalidlanguage" -class tvdb_error(tvdb_exception): - """An error with thetvdb.com (Cannot connect, for example) - """ - pass +logging.getLogger(__name__).warning( + "tvdb_exceptions module is deprecated - use classes directly from tvdb_api instead") -class tvdb_userabort(tvdb_exception): - """User aborted the interactive selection (via - the q command, ^c etc) - """ - pass - -class tvdb_shownotfound(tvdb_exception): - """Show cannot be found on thetvdb.com (non-existant show) - """ - pass - -class tvdb_seasonnotfound(tvdb_exception): - """Season cannot be found on thetvdb.com - """ - pass - -class tvdb_episodenotfound(tvdb_exception): - """Episode cannot be found on thetvdb.com - """ - pass - -class tvdb_attributenotfound(tvdb_exception): - """Raised if an episode does not have the requested - attribute (such as a episode name) - """ - pass +from tvdb_api import ( + tvdb_error, tvdb_userabort, tvdb_notauthorized, tvdb_shownotfound, + tvdb_seasonnotfound, tvdb_episodenotfound, + tvdb_resourcenotfound, tvdb_invalidlanguage, + tvdb_attributenotfound +)
View file
tvdb_api-1.10.tar.gz/tvdb_ui.py -> tvdb_api-2.0.tar.gz/tvdb_ui.py
Changed
@@ -5,45 +5,9 @@ #repository:http://github.com/dbr/tvdb_api #license:unlicense (http://unlicense.org/) -"""Contains included user interfaces for Tvdb show selection. - -A UI is a callback. A class, it's __init__ function takes two arguments: - -- config, which is the Tvdb config dict, setup in tvdb_api.py -- log, which is Tvdb's logger instance (which uses the logging module). You can -call log.info() log.warning() etc - -It must have a method "selectSeries", this is passed a list of dicts, each dict -contains the the keys "name" (human readable show name), and "sid" (the shows -ID as on thetvdb.com). For example: - -{'name': u'Lost', 'sid': u'73739'}, - {'name': u'Lost Universe', 'sid': u'73181'} - -The "selectSeries" method must return the appropriate dict, or it can raise -tvdb_userabort (if the selection is aborted), tvdb_shownotfound (if the show -cannot be found). - -A simple example callback, which returns a random series: - ->>> import random ->>> from tvdb_ui import BaseUI ->>> class RandomUI(BaseUI): -... def selectSeries(self, allSeries): -... import random -... return random.choice(allSeries) - -Then to use it.. - ->>> from tvdb_api import Tvdb ->>> t = Tvdb(custom_ui = RandomUI) ->>> random_matching_series = t'Lost' ->>> type(random_matching_series) -<class 'tvdb_api.Show'> -""" __author__ = "dbr/Ben" -__version__ = "1.10" +__version__ = "2.0" import sys import logging @@ -51,117 +15,7 @@ from tvdb_exceptions import tvdb_userabort +logging.getLogger(__name__).warning( + "tvdb_ui module is deprecated - use classes directly from tvdb_api instead") -IS_PY2 = sys.version_info0 == 2 - -if IS_PY2: - user_input = raw_input -else: - user_input = input - - -def log(): - return logging.getLogger(__name__) - -class BaseUI: - """Default non-interactive UI, which auto-selects first results - """ - def __init__(self, config, log = None): - self.config = config - if log is not None: - warnings.warn("the UI's log parameter is deprecated, instead use\n" - "use import logging; logging.getLogger('ui').info('blah')\n" - "The self.log attribute will be removed in the next version") - self.log = logging.getLogger(__name__) - - def selectSeries(self, allSeries): - return allSeries0 - - -class ConsoleUI(BaseUI): - """Interactively allows the user to select a show from a console based UI - """ - - def _displaySeries(self, allSeries, limit = 6): - """Helper function, lists series with corresponding ID - """ - if limit is not None: - toshow = allSeries:limit - else: - toshow = allSeries - - print("TVDB Search Results:") - for i, cshow in enumerate(toshow): - i_show = i + 1 # Start at more human readable number 1 (not 0) - log().debug('Showing allSeries%s, series %s)' % (i_show, allSeriesi'seriesname')) - if i == 0: - extra = " (default)" - else: - extra = "" - - output = "%s -> %s %s # http://thetvdb.com/?tab=series&id=%s&lid=%s%s" % ( - i_show, - cshow'seriesname', - cshow'language', - str(cshow'id'), - cshow'lid', - extra - ) - if IS_PY2: - print(output.encode("UTF-8", "ignore")) - else: - print(output) - - def selectSeries(self, allSeries): - self._displaySeries(allSeries) - - if len(allSeries) == 1: - # Single result, return it! - print("Automatically selecting only result") - return allSeries0 - - if self.config'select_first' is True: - print("Automatically returning first search result") - return allSeries0 - - while True: # return breaks this loop - try: - print("Enter choice (first number, return for default, 'all', ? for help):") - ans = user_input() - except KeyboardInterrupt: - raise tvdb_userabort("User aborted (^c keyboard interupt)") - except EOFError: - raise tvdb_userabort("User aborted (EOF received)") - - log().debug('Got choice of: %s' % (ans)) - try: - selected_id = int(ans) - 1 # The human entered 1 as first result, not zero - except ValueError: # Input was not number - if len(ans.strip()) == 0: - # Default option - log().debug('Default option, returning first series') - return allSeries0 - if ans == "q": - log().debug('Got quit command (q)') - raise tvdb_userabort("User aborted ('q' quit command)") - elif ans == "?": - print("## Help") - print("# Enter the number that corresponds to the correct show.") - print("# a - display all results") - print("# all - display all results") - print("# ? - this help") - print("# q - abort tvnamer") - print("# Press return with no input to select first result") - elif ans.lower() in "a", "all": - self._displaySeries(allSeries, limit = None) - else: - log().debug('Unknown keypress %s' % (ans)) - else: - log().debug('Trying to return ID: %d' % (selected_id)) - try: - return allSeriesselected_id - except IndexError: - log().debug('Invalid show number entered!') - print("Invalid number (%s) selected!") - self._displaySeries(allSeries) - +from tvdb_api import BaseUI, ConsoleUI
Locations
Projects
Search
Status Monitor
Help
Open Build Service
OBS Manuals
API Documentation
OBS Portal
Reporting a Bug
Contact
Mailing List
Forums
Chat (IRC)
Twitter
Open Build Service (OBS)
is an
openSUSE project
.