# Buggy code
def find_series_id(name):
    """Looks up the tvdb id for a series"""
    try:
        series = TVDBRequest().get("search/series", name=name)
    except requests.RequestException as e:
        raise LookupError("Unable to get search results for %s: %s" % (name, e))

    series_list = []

    name = name.lower()

    for s in series:
        # Exact match
        if s["seriesName"].lower() == name:
            return s["id"]
        if s["firstAired"]:
            series_list.append((s["firstAired"], s["id"]))

    # If there is no exact match, sort by airing date and pick the latest
    if series_list:
        series_list.sort(key=lambda s: s[0], reverse=True)
        return series_list[0][1]
    else:
        raise LookupError("No results for `%s`" % name)


# Traceback (FlushError)
2016-04-01 21:04 INFO     download      tv_shows        Downloading: Sleepy.Hollow.S03E17.720p.HDTV.x264-AVS
2016-04-01 21:04 ERROR    api_tvdb      tv_shows        Could not get update information from tvdb: 404 Client Error: Not Found for url: https://api-beta.thetvdb.com/updated/query?fromTime=1459529228
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
2016-04-01 21:04 CRITICAL manager       tv_shows        An unexpected crash has occurred. Writing crash report to /home/pi/.flexget/crash_report.2016.04.01.210426572780.log. Please verify you are running the latest version of flexget by using "flexget -V" from CLI or by using version_checker plugin at http://flexget.com/wiki/Plugins/version_checker. You are currently using version 1.2.499
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
2016-04-01 21:04 CRITICAL manager       tv_shows        An unexpected crash has occurred. Writing crash report to /home/pi/.flexget/crash_report.2016.04.01.210427914486.log. Please verify you are running the latest version of flexget by using "flexget -V" from CLI or by using version_checker plugin at http://flexget.com/wiki/Plugins/version_checker. You are currently using version 1.2.499
2016-04-01 21:04 INFO     transmission  tv_shows        "Sleepy.Hollow.S03E17.720p.HDTV.x264-AVS" torrent added to transmission
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
2016-04-01 21:04 CRITICAL manager       tv_shows        An unexpected crash has occurred. Writing crash report to /home/pi/.flexget/crash_report.2016.04.01.210434515925.log. Please verify you are running the latest version of flexget by using "flexget -V" from CLI or by using version_checker plugin at http://flexget.com/wiki/Plugins/version_checker. You are currently using version 1.2.499
2016-04-01 21:04 ERROR    lazy_lookup   tv_shows        Unhandled error in lazy lookup plugin
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flexget/utils/lazy_dict.py", line 36, in __getitem__
func(self.store)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/metainfo/thetvdb_lookup.py", line 115, in lazy_series_poster_lookup
return self.series_lookup(entry, self.series_poster_map)
File "/usr/local/lib/python2.7/dist-packages/flexget/utils/database.py", line 30, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flexget/utils/sqlalchemy_utils.py", line 137, in __exit__
self.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 801, in commit
self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 392, in commit
self._prepare_impl()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 372, in _prepare_impl
self.session.flush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2019, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2137, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2101, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 373, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 532, in execute
uow
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 149, in save_obj
base_mapper, states, uowtransaction
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 301, in _organize_states_for_save
state_str(existing)))
FlushError: New instance <TVDBGenre at 0x68f50970> with identity key (<class 'flexget.plugins.api_tvdb.TVDBGenre'>, (4,)) conflicts with persistent instance <TVDBGenre at 0x68f433d0>

# Fixed code
def find_series_id(name):
    """Looks up the tvdb id for a series"""
    try:
        series = TVDBRequest().get("search/series", name=name)
    except requests.RequestException as e:
        raise LookupError("Unable to get search results for %s: %s" % (name, e))

    series_list = []

    name = name.lower()

    for s in series:
        # Exact match
        if s.get("seriesName").lower() == name:
            return s["id"]
        if s["firstAired"]:
            series_list.append((s["firstAired"], s["id"]))

    # If there is no exact match, sort by airing date and pick the latest
    if series_list:
        series_list.sort(key=lambda s: s[0], reverse=True)
        return series_list[0][1]
    else:
        raise LookupError("No results for `%s`" % name)