1 from sqlalchemy
import MetaData
, Table
, engine_from_config
, orm
3 from ..defaults
import get_default_db_uri
4 from .tables
import metadata
7 def connect(uri
=None, session_args
={}, engine_args
={}, engine_prefix
=''):
8 """Connects to the requested URI. Returns a session object.
10 With the URI omitted, attempts to connect to a default SQLite database
11 contained within the package directory.
13 Calling this function also binds the metadata object to the created engine.
16 # If we didn't get a uri, fall back to the default
18 uri
= engine_args
.get(engine_prefix
+ 'url', None)
20 uri
= get_default_db_uri()
22 ### Do some fixery for MySQL
23 if uri
[0:5] == 'mysql':
24 # MySQL uses latin1 for connections by default even if the server is
25 # otherwise oozing with utf8; charset fixes this
26 if 'charset' not in uri
:
27 uri
+= '?charset=utf8'
29 # Tables should be InnoDB, in the event that we're creating them, and
30 # use UTF-8 goddammit!
31 for table
in metadata
.tables
.values():
32 table
.kwargs
['mysql_engine'] = 'InnoDB'
33 table
.kwargs
['mysql_charset'] = 'utf8'
36 engine_args
[engine_prefix
+ 'url'] = uri
37 engine
= engine_from_config(engine_args
, prefix
=engine_prefix
)
38 conn
= engine
.connect()
39 metadata
.bind
= engine
41 all_session_args
= dict(autoflush
=True, autocommit
=False, bind
=engine
)
42 all_session_args
.update(session_args
)
43 sm
= orm
.sessionmaker(**all_session_args
)
44 session
= orm
.scoped_session(sm
)