environment class

get_session
This commit is contained in:
Ruud
2011-02-23 13:57:13 +01:00
parent 80cc8abf68
commit cdde98653e
8 changed files with 78 additions and 108 deletions
-2
View File
@@ -94,5 +94,3 @@ class Settings():
return True
except ValueError:
return False
settings = Settings()
-64
View File
@@ -1,64 +0,0 @@
import sqlalchemy as sa
from sqlalchemy import orm
class DatabaseError(Exception):
"""Custom exceptions related to the database."""
pass
def _session_cls_cache(cache={}):
"""Holds a dictionary to cache session objects."""
return cache
def get_session(engine=None, test=False):
"""
Get the current session or create a new one based on the engine.
>>> from couchpotato import db
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:')
>>> session = db.get_session(engine)
>>> session #doctest: +ELLIPSIS
<sqlalchemy.orm.session.Session object at ...>
Once a session has been created, get_session will return session instances
of the same Session class.
>>> type(session) == type(db.get_session())
True
If you create multiple sessions for different engines, you need to
specify which session you want by passing the engine explicitely.
>>> other_engine = create_engine('sqlite:///:memory:')
>>> other_session = db.get_session(other_engine)
>>> type(other_session) is type(db.get_session(other_engine))
True
"""
cache = _session_cls_cache()
assert not(engine and test), "Cannot pass both test and engine."
# It doesn't make sense to both pass an engine and instruct the function
# to create a new engine. Decide what you want to do, but not both.
if test:
in_memory = sa.create_engine('sqlite:///:memory:')
session = orm.sessionmaker(bind=in_memory)()
# create Session class ^ ^
# create Session instance ^
elif engine:
key = (engine, )
if key not in cache:
cache[key] = orm.sessionmaker(bind=engine)
session = cache[key]()
elif len(cache) == 1:
session = (cache[key] for key in cache).next()()
# return the first element ^ ^
# instantiate session ^
elif len(cache) >= 1:
raise DatabaseError("Multiple Session classes found. Choose one.")
else:
raise DatabaseError("No session found. You need to create one.")
return session
+13 -11
View File
@@ -1,7 +1,10 @@
from elixir import *
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.schema import ThreadLocalMetaData
from elixir.entity import Entity
from elixir.fields import Field
from elixir.options import options_defaults
from elixir.relationships import OneToMany, ManyToOne
from sqlalchemy.types import Integer, String, Unicode
options_defaults["shortnames"] = True
# We would like to be able to create this schema in a specific database at
# will, so we can test it easily.
@@ -10,12 +13,11 @@ from sqlalchemy.schema import ThreadLocalMetaData
# http://elixir.ematia.de/trac/wiki/Recipes/MultipleDatabasesOneMetadata
__session__ = None
class Resource(Entity):
"""Represents a resource of movies. This recources can be online or
offline."""
name = Field(UnicodeString(255))
path = Field(UnicodeString(255))
"""Represents a resource of movies.
This resources can be online or offline."""
name = Field(Unicode(255))
path = Field(Unicode(255))
releases = OneToMany('Release')
@@ -30,7 +32,7 @@ class Release(Entity):
class File(Entity):
"""File that belongs to a release."""
history = OneToMany('RenameHistory')
path = Field(UnicodeString(255), nullable = False, unique = True)
path = Field(Unicode(255), nullable = False, unique = True)
# Subtitles can have multiple parts, too
part = Field(Integer)
release = ManyToOne('Release')
@@ -42,7 +44,7 @@ class File(Entity):
class FileType(Entity):
"""Types could be trailer, subtitle, movie, partial movie etc."""
identifier = Field(String(20), unique = True)
name = Field(UnicodeString(255), nullable = False)
name = Field(Unicode(255), nullable = False)
files = OneToMany('File')