# Buggy code
def _get_db_genres(genre_names, session=None):
    genres = []
    if genre_names:
        for genre_name in genre_names:
            genre = (
                session.query(TVDBGenre).filter(TVDBGenre.name == genre_name).first()
            )
            if not genre:
                genre = TVDBGenre(name=genre_name)
                session.add(genre)
            genres.append({"id": genre.id, "name": genre.name})

    return genres


# 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 _get_db_genres(genre_names):
    genres = []
    if genre_names:
        with Session() as session:
            for genre_name in genre_names:
                genre = (
                    session.query(TVDBGenre)
                    .filter(func.lower(TVDBGenre.name) == genre_name.lower())
                    .first()
                )
                if not genre:
                    genre = TVDBGenre(name=genre_name)
                    session.add(genre)
                    session.commit()
                genres.append({"id": genre.id, "name": genre.name})

    return genres