本文整理汇总了Python中sqlalchemy.create_engine方法的典型用法代码示例。如果您正苦于以下问题:Python sqlalchemy.create_engine方法的具体用法?Python sqlalchemy.create_engine怎么用?Python sqlalchemy.create_engine使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy
的用法示例。
在下文中一共展示了sqlalchemy.create_engine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUpClass
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def setUpClass(self):
"""Database setup before the CRUD tests."""
print("Creating a temporary datatbsse...")
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = scoped_session(sessionmaker(bind=engine))
self.API_NAME = "demoapi"
self.HYDRUS_SERVER_URL = "http://hydrus.com/"
self.session = session
self.doc = doc_maker.create_doc(
doc, self.HYDRUS_SERVER_URL, self.API_NAME)
test_classes = doc_parse.get_classes(self.doc.generate())
# Getting list of classes from APIDoc
self.doc_collection_classes = [
self.doc.collections[i]["collection"].class_.title for i in self.doc.collections]
print(self.doc_collection_classes)
print(random.choice(self.doc_collection_classes))
test_properties = doc_parse.get_all_properties(test_classes)
doc_parse.insert_classes(test_classes, self.session)
doc_parse.insert_properties(test_properties, self.session)
print("Classes and properties added successfully.")
print("Setup done, running tests...")
示例2: _db_dsn
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def _db_dsn(request):
name = 'test_{}'.format(uuid.uuid4().hex)
pg_dsn = 'postgresql://postgres:postgres@postgres:5432/postgres'
db_dsn = 'postgresql://postgres:postgres@postgres:5432/{}'.format(name)
pg_engine = sqlalchemy.create_engine(pg_dsn)
pg_engine.raw_connection()\
.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
pg_engine.execute('CREATE DATABASE {0}'.format(name))
pg_engine.dispose()
db_engine = sqlalchemy.create_engine(db_dsn)
setup_db(db_engine)
db_engine.dispose()
def fin():
pg_engine = sqlalchemy.create_engine(pg_dsn)
pg_engine.raw_connection() \
.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
pg_engine.execute('DROP DATABASE {0}'.format(name))
pg_engine.dispose()
request.addfinalizer(fin)
return db_dsn
示例3: connect_db
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def connect_db(self):
"""Connect the state manager to the persistent DB."""
self.db_engine = create_engine(
config.config_mgr.conf.database.database_connect_string,
pool_size=config.config_mgr.conf.database.pool_size,
pool_pre_ping=config.config_mgr.conf.database.pool_pre_ping,
max_overflow=config.config_mgr.conf.database.pool_overflow,
pool_timeout=config.config_mgr.conf.database.pool_timeout,
pool_recycle=config.config_mgr.conf.database.connection_recycle)
self.db_metadata = MetaData(bind=self.db_engine)
self.tasks_tbl = tables.Tasks(self.db_metadata)
self.result_message_tbl = tables.ResultMessage(self.db_metadata)
self.active_instance_tbl = tables.ActiveInstance(self.db_metadata)
self.boot_action_tbl = tables.BootAction(self.db_metadata)
self.ba_status_tbl = tables.BootActionStatus(self.db_metadata)
self.build_data_tbl = tables.BuildData(self.db_metadata)
return
示例4: main
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def main(args, env):
global Session
if args.verbose >= 1:
app.config['DEBUG'] = True
sys.stderr.write("connecting to DB server {:s}\n".format(args.db))
connection_succeeded = False
while not connection_succeeded:
try:
engine = create_engine(args.db)
Session = sessionmaker(bind = engine)
Base.metadata.create_all(engine)
sys.stderr.write("connection succeeded!\n")
connection_succeeded = True
app.run(debug = args.verbose >= 1, host = "0.0.0.0", port = 80)
except OperationalError as err:
if "Connection refused" in str(err):
connection_succeeded = False
time.sleep(10)
else:
raise
示例5: open
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def open(self,database):
"""
params:
database: str. Database to be opered. The path should be included
"""
assert(database[-4:]=='.mdo')
if not os.path.exists(database):
self._create(database)
operate_db=database[:-4]+'.op'
shutil.copy(database,operate_db)
# engine=create_engine('sqlite:///:memory:')
engine=create_engine('sqlite:///'+operate_db) #should be run in memory in the future
Session=o.sessionmaker(bind=engine)
self.session=Session()
self.__operate_db=operate_db
self.__storage_db=database
示例6: __init__
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def __init__(self, user, password, database, host, port):
driver = 'mysql+pymysql'
self.url = URL(driver, user, password, host, port, database)
# Hack to establish SSL connection (see #231)
try:
self._engine = create_engine(self.url, echo=True,
connect_args={'ssl': {'activate': True}})
self._engine.connect().close()
except InternalError:
self._engine = create_engine(self.url, echo=True)
self._Session = sessionmaker(bind=self._engine)
# Create the schema on the database.
# It won't replace any existing schema
ModelBase.metadata.create_all(self._engine)
示例7: test_query
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def test_query():
sa_engine = create_engine(
'sqlite://',
connect_args={'check_same_thread': False},
poolclass=StaticPool,
)
setup_db(sa_engine)
app = ConsoleApplication(GRAPH, engine, {SA_ENGINE_KEY: sa_engine},
debug=True)
query = b'[{:bar_list [:name :type {:foo_s [:name :count]}]}]'
status, headers, content = request(app, 'POST', '/', payload=query)
assert status == '200 OK'
assert ('Content-Type', 'application/json') in headers
result = json.loads(content.decode('utf-8'))
assert 'bar_list' in result
示例8: __init__
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def __init__(self, results_queue, thread_pool, use_file=True, use_database=True, filename="proxy-ip-list.csv"):
self.use_file = use_file
self.use_database = use_database
self.filename = filename
self.results_queue = results_queue
self.thread_pool = thread_pool
if use_database:
try:
cf = ConfigParser.ConfigParser()
cf.read("config.ini")
db_name = cf.get("Pansidong", "database")
username = cf.get(db_name, "username")
password = cf.get(db_name, "password")
host = cf.get(db_name, "host")
database = cf.get(db_name, "database")
except AttributeError, e:
logger.fatal(e.message)
sys.exit(1)
self.engine = create_engine("mysql://" + username + ":" + password + "@" +
host + "/" + database + "?charset=utf8")
self.db_session = sessionmaker(bind=self.engine)
self.session = self.db_session()
示例9: create_new_ensemble
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def create_new_ensemble():
req_body = request.get_json()
ensemble_name = req_body['ensemble_name']
if os.path.exists(ensemble_name):
return jsonify(message="File/folder already exists"), 400
os.makedirs(ensemble_name)
xcessiv_notebook_path = os.path.join(ensemble_name, app.config['XCESSIV_NOTEBOOK_NAME'])
sqlite_url = 'sqlite:///{}'.format(xcessiv_notebook_path)
engine = create_engine(sqlite_url)
models.Base.metadata.create_all(engine)
# Initialize
extraction = models.Extraction()
with functions.DBContextManager(ensemble_name) as session:
session.add(extraction)
session.commit()
return jsonify(message="Xcessiv notebook created")
示例10: init
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def init(config: Config) -> Engine:
db = sql.create_engine(config["database"])
Base.metadata.bind = db
for table in (DBPlugin, DBClient):
table.bind(db)
if not db.has_table("alembic_version"):
log = logging.getLogger("maubot.db")
if db.has_table("client") and db.has_table("plugin"):
log.warning("alembic_version table not found, but client and plugin tables found. "
"Assuming pre-Alembic database and inserting version.")
db.execute("CREATE TABLE IF NOT EXISTS alembic_version ("
" version_num VARCHAR(32) PRIMARY KEY"
");")
db.execute("INSERT INTO alembic_version VALUES ('d295f8dcfa64');")
else:
log.critical("alembic_version table not found. "
"Did you forget to `alembic upgrade head`?")
sys.exit(10)
return db
示例11: load
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def load(self) -> bool:
if not self.loader:
try:
self.loader = PluginLoader.find(self.type)
except KeyError:
self.log.error(f"Failed to find loader for type {self.type}")
self.db_instance.enabled = False
return False
if not self.client:
self.client = Client.get(self.primary_user)
if not self.client:
self.log.error(f"Failed to get client for user {self.primary_user}")
self.db_instance.enabled = False
return False
if self.loader.meta.database:
db_path = os.path.join(self.mb_config["plugin_directories.db"], self.id)
self.inst_db = sql.create_engine(f"sqlite:///{db_path}.db")
if self.loader.meta.webapp:
self.inst_webapp, self.inst_webapp_url = self.webserver.get_instance_subapp(self.id)
self.log.debug("Plugin instance dependencies loaded")
self.loader.references.add(self)
self.client.references.add(self)
return True
示例12: populate
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def populate(cli_ctx, fixture_path):
'''Populate fixtures.'''
with cli_ctx.logger:
log.info("populating fixture '{0}'", fixture_path)
try:
fixture = json.loads(fixture_path.read_text(encoding='utf8'))
except AttributeError:
log.error('No such fixture.')
return
engine = sa.create_engine(
f"postgres://{cli_ctx.config['db']['user']}:{cli_ctx.config['db']['password']}"
f"@{cli_ctx.config['db']['addr']}/{cli_ctx.config['db']['name']}")
conn = engine.connect()
populate_fixture(conn, fixture)
conn.close()
示例13: run_migrations_online
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = create_engine(DBURL, poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
示例14: init_db
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def init_db(app_db_path):
# Open session for database connection
global session
global app_DB_path
app_DB_path = app_db_path
engine = create_engine(u'sqlite:///{0}'.format(app_db_path), echo=False)
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
if os.path.exists(app_db_path):
Base.metadata.create_all(engine)
migrate_Database(session)
clean_database(session)
else:
Base.metadata.create_all(engine)
create_admin_user(session)
create_anonymous_user(session)
示例15: setup_connection
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import create_engine [as 别名]
def setup_connection(self) -> None:
assert isinstance(self.settings, SQLAlchemySettings), self.settings
if self._engine is None:
# Create SQLAlchemy engine.
if self.is_sqlite():
kwargs: Dict[str, Any] = {"connect_args": {"check_same_thread": False}}
elif self.settings.pool_size == 1:
kwargs = {"poolclass": StaticPool}
else:
kwargs = {"pool_size": self.settings.pool_size}
self._engine = create_engine(
self.settings.uri,
strategy=self._connection_strategy,
# echo=True,
**kwargs
)
assert self._engine