Skip to content
Browse files

Improved DB configuration in SQLA example.

- Get SQLite path from config file.
- Print out the path to the temporary DB file.
- Moved engine and Session creation from module level into main().
- Use engine directly instead of Session to populate example table.
  • Loading branch information...
1 parent 76d8461 commit c69bc4c9cfbdd4686a524d5eafd407967311173a @wylee committed May 14, 2012
Showing with 18 additions and 17 deletions.
  1. +18 −17 examples/sqlalchemy_orm_example.py
View
35 examples/sqlalchemy_orm_example.py
@@ -14,8 +14,6 @@
specifies the name of this database.
"""
-import os
-
from pyramid.config import Configurator
from pyramid_restler.model import SQLAlchemyORMContext
@@ -27,11 +25,7 @@
from sqlalchemy.types import Integer, String
-DB_NAME = 'pyramid_restler_example.db'
-
-engine = create_engine('sqlite:///{0}'.format(DB_NAME))
-Session = sessionmaker(bind=engine)
-Base = declarative_base(bind=engine)
+Base = declarative_base()
class MyThing(Base):
@@ -57,7 +51,14 @@ def root_view(context, request):
def main(global_config, **settings):
- create_and_populate_database()
+ db_path = settings['db_path']
+ print('Temporary SQLite database created at {0}.'.format(db_path))
+
+ global Session
+ engine = create_engine('sqlite:///{0}'.format(db_path))
+ Session = sessionmaker(bind=engine)
+ create_and_populate_database(engine)
+
config = Configurator(settings=settings)
config.add_route('root', '/')
config.add_view(route_name='root', view=root_view, renderer='example.mako')
@@ -66,12 +67,12 @@ def main(global_config, **settings):
return config.make_wsgi_app()
-def create_and_populate_database():
- Base.metadata.create_all()
- session = Session()
- session.add_all([
- MyThing(title='One'),
- MyThing(title='Two'),
- MyThing(title='Three'),
- ])
- session.commit()
+def create_and_populate_database(engine):
+ Base.metadata.drop_all(bind=engine)
+ Base.metadata.create_all(bind=engine)
+ engine.execute(
+ MyThing.__table__.insert(),
+ dict(title='One', description='First'),
+ dict(title='Two', description='Second'),
+ dict(title='Three', description='Third'),
+ )

0 comments on commit c69bc4c

Please sign in to comment.
Something went wrong with that request. Please try again.