本文整理汇总了Python中sqlalchemy.orm.session.sessionmaker函数的典型用法代码示例。如果您正苦于以下问题:Python sessionmaker函数的具体用法?Python sessionmaker怎么用?Python sessionmaker使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sessionmaker函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_session
def create_session(self, engine=None, shard=False):
class_ = QKShardSession if shard else QKSession
factory = sessionmaker(
db=self, bind=engine, class_=class_,
autocommit=False, autoflush=False
)
return _scoped_session(factory, scopefunc=self.scopefunc)
示例2: persist_bundle_sensor
def persist_bundle_sensor(self):
from madmex.persistence.driver import persist_bundle
folder = '/LUSTRE/MADMEX/staging/madmex_antares/test_ingest/556_297_041114_dim_img_spot'
from sqlalchemy import create_engine
from sqlalchemy.orm.session import sessionmaker
from madmex.mapper.bundle.spot5 import Bundle
#from madmex.configuration import SETTINGS
dummy = Bundle(folder)
#dummy.target = '/LUSTRE/MADMEX/staging/'
target_url = getattr(SETTINGS, 'TEST_FOLDER')
print target_url
#TODO please fix me, horrible hack
dummy.target = target_url
persist_bundle(dummy)
my_database = getattr(SETTINGS, 'ANTARES_TEST_DATABASE')
klass = sessionmaker(bind=create_engine(my_database))
session = klass()
query = 'SELECT count(*) FROM product WHERE uuid=\'%s\';' % dummy.uuid_id
try:
result_set = session.execute(query)
for row in result_set:
self.assertGreater(row['count'], 0)
session.delete(dummy.get_database_object())
session.commit()
for file_name in dummy.get_files():
full_path = os.path.join(target_url, os.path.basename(file_name))
self.assertTrue(os.path.isfile(full_path))
os.remove(full_path)
except:
session.rollback()
raise
finally:
session.close()
示例3: __init__
def __init__(self, database, config):
self.name = database
self._config = config
url = Database.build_url(database, config)
self._engine = sa.create_engine(url)
self._metadata = sa.MetaData(bind=self._engine, naming_convention=kNamingConvention)
self._sessionmaker = sessionmaker(bind=self._engine)
示例4: db_searchreplace
def db_searchreplace(db_name, db_user, db_password, db_host, search, replace ):
engine = create_engine("mysql://%s:%[email protected]%s/%s" % (db_user, db_password, db_host, db_name ))
#inspector = reflection.Inspector.from_engine(engine)
#print inspector.get_table_names()
meta = MetaData()
meta.bind = engine
meta.reflect()
Session = sessionmaker(engine)
Base = declarative_base(metadata=meta)
session = Session()
tableClassDict = {}
for table_name, table_obj in dict.iteritems(Base.metadata.tables):
try:
tableClassDict[table_name] = type(str(table_name), (Base,), {'__tablename__': table_name, '__table_args__':{'autoload' : True, 'extend_existing': True} })
# class tempClass(Base):
# __tablename__ = table_name
# __table_args__ = {'autoload' : True, 'extend_existing': True}
# foo_id = Column(Integer, primary_key='temp')
for row in session.query(tableClassDict[table_name]).all():
for column in table_obj._columns.keys():
data_to_fix = getattr(row, column)
fixed_data = recursive_unserialize_replace( search, replace, data_to_fix, False)
setattr(row, column, fixed_data)
#print fixed_data
except Exception, e:
print e
示例5: __init__
def __init__(self, engine):
'''
Constructor
'''
self.engine = engine
klass = sessionmaker(bind=self.engine)
self.session = klass()
示例6: session_cm
def session_cm():
session = sessionmaker(bind=db_engine)()
try:
yield session
except Exception, e:
# logger.warn(traceback.format_exc())
raise
示例7: _run_indexer
def _run_indexer(options):
logging.info("Starting indexer %s:%s ..." % (options.host, options.port))
# initialize crawler
service = WaveformIndexer((options.host, options.port), MyHandler)
service.log = logging
try:
# prepare paths
if ',' in options.data:
paths = options.data.split(',')
else:
paths = [options.data]
paths = service._prepare_paths(paths)
if not paths:
return
# prepare map file
if options.mapping_file:
with open(options.mapping_file, 'r') as f:
data = f.readlines()
mappings = parse_mapping_data(data)
logging.info("Parsed %d lines from mapping file %s" %
(len(data), options.mapping_file))
else:
mappings = {}
# create file queue and worker processes
manager = multiprocessing.Manager()
in_queue = manager.dict()
work_queue = manager.list()
out_queue = manager.list()
log_queue = manager.list()
# spawn processes
for i in range(options.number_of_cpus):
args = (i, in_queue, work_queue, out_queue, log_queue, mappings)
p = multiprocessing.Process(target=worker, args=args)
p.daemon = True
p.start()
# connect to database
engine = create_engine(options.db_uri, encoding=native_str('utf-8'),
convert_unicode=True)
metadata = Base.metadata
# recreate database
if options.drop_database:
metadata.drop_all(engine, checkfirst=True)
metadata.create_all(engine, checkfirst=True)
# initialize database + options
_session = sessionmaker(bind=engine)
service.session = _session
service.options = options
service.mappings = mappings
# set queues
service.input_queue = in_queue
service.work_queue = work_queue
service.output_queue = out_queue
service.log_queue = log_queue
service.paths = paths
service._reset_walker()
service._step_walker()
service.serve_forever(options.poll_interval)
except KeyboardInterrupt:
quit()
logging.info("Indexer stopped.")
示例8: setUp
def setUp(self):
print "setup.."
#engine = create_engine('sqlite:///data/test.db', echo=True)
engine = create_engine('sqlite://', echo=True)
Session = sessionmaker(bind=engine)
self.session = Session()
ImageModel.metadata.create_all(engine)
示例9: __init__
def __init__(self):
'''
Constructor
'''
self.base = declarative_base()
self.SessionFactory = sessionmaker(bind=self.engine)
self.session = self.SessionFactory()
示例10: setUp
def setUp(self):
engine = create_engine("sqlite:///:memory:", echo=True)
Session = sessionmaker(bind=engine)
self.session = Session()
Base = declarative_base()
class Post(Base):
__tablename__ = "objectA"
__searchable__ = ["title", "body"]
id = Column(Integer, primary_key=True)
title = Column(Text)
body = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow())
def __repr__(self):
return "{0}(title={1})".format(self.__class__.__name__, self.title)
self.Post = Post
Base.metadata.create_all(engine)
self.index_manager = whooshalchemy.IndexService(session=self.session)
self.index_manager.register_class(Post)
示例11: _create_session
def _create_session(self, engine):
Base.metadata.create_all(engine)
# Distinguish sessions by thread.
session = scoped_session(sessionmaker(
extension=ZopeTransactionExtension()))
session.configure(bind=engine)
return session
示例12: __init__
def __init__(self, name, url, scope_func):
self._name = name
self._url, engine_params = self._parse_url(url)
self._engine = sqlalchemy.create_engine(self._url, **engine_params)
self._session_maker = sessionmaker(self.engine, class_=Session, expire_on_commit=False)
self._scoped_session_maker = scoped_session(self._session_maker, scopefunc=scope_func)
self.Model = declarative_base()
示例13: main
def main(keep_saved, config_location):
if not config_location:
config_location = os.path.dirname(os.path.abspath(__file__)) + "\\config.ini"
try:
open(config_location)
except IOError:
print "Problem opening config.ini at " + config_location
engine = create_engine(make_connection(config_location), echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class FeverItems(Base):
__tablename__ = 'fever_items'
id = Column(INTEGER, primary_key=True)
description = Column(LONGTEXT)
is_saved = Column(TINYINT)
records = session.query(FeverItems.description).filter_by(is_saved=1)
contents = []
for record in records:
contents.append(record)
if not keep_saved:
session.query(FeverItems).filter_by(is_saved=1).update({"is_saved": 0})
session.commit()
return contents
if __name__ == "__main__":
main(bool(sys.argv[1]), str(sys.argv[2]))
示例14: Session_Adapter_Add
def Session_Adapter_Add(data_information):
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
session.add(data_information)
session.flush()
session.commit()
示例15: _create_engine
def _create_engine(self, url):
echo = self.configuration.get('echo')
if echo:
echo = 'debug'
engine = self.dialect.create_engine(url, self.schema, echo=echo)
return engine, sessionmaker(bind=engine)