本文整理汇总了Python中sqlalchemy.engine.url.URL属性的典型用法代码示例。如果您正苦于以下问题:Python url.URL属性的具体用法?Python url.URL怎么用?Python url.URL使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类sqlalchemy.engine.url
的用法示例。
在下文中一共展示了url.URL属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [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)
示例2: create
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def create(self, name_or_url, executor, **kwargs):
# create url.URL object
u = url.make_url(name_or_url)
dialect_cls = u.get_dialect()
dialect_args = {}
# consume dialect arguments from kwargs
for k in util.get_cls_kwargs(dialect_cls):
if k in kwargs:
dialect_args[k] = kwargs.pop(k)
# create dialect
dialect = dialect_cls(**dialect_args)
return MockEngineStrategy.MockConnection(dialect, executor)
示例3: init_db
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def init_db(db_type, username, password, host, db, db_location):
"""
Creates database engine
:param db_type: database type
:param username: database username
:param password: database password
:param host: database host
:param db: database name
:return:
"""
global engine
url = None
if db_type == 'mysql':
url = URL(db_type, username, password, host, database=db)
elif db_type == 'sqlite':
url = "sqlite:///" + db_location
engine = create_engine(url)
示例4: __init__
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def __init__(
self,
app: ASGIApp,
db_url: Optional[Union[str, URL]] = None,
custom_engine: Optional[Engine] = None,
engine_args: Dict = None,
session_args: Dict = None,
):
super().__init__(app)
global _Session
engine_args = engine_args or {}
session_args = session_args or {}
if not custom_engine and not db_url:
raise ValueError("You need to pass a db_url or a custom_engine parameter.")
if not custom_engine:
engine = create_engine(db_url, **engine_args)
else:
engine = custom_engine
_Session = sessionmaker(bind=engine, **session_args)
示例5: __init__
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def __init__(
self,
drivername,
host=None,
port=None,
database=None,
username=None,
password=None,
create_if_missing=False,
):
self.url = URL(
drivername=drivername,
username=username,
password=password,
host=host,
port=port,
database=database
)
self.create_if_missing = create_if_missing
示例6: adjust_database_uri
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def adjust_database_uri(cls, uri: URL, selected_schema: Optional[str]) -> None:
"""
Mutate the database component of the SQLAlchemy URI.
The URI here represents the URI as entered when saving the database,
``selected_schema`` is the schema currently active presumably in
the SQL Lab dropdown. Based on that, for some database engine,
we can return a new altered URI that connects straight to the
active schema, meaning the users won't have to prefix the object
names by the schema name.
Some databases engines have 2 level of namespacing: database and
schema (postgres, oracle, mssql, ...)
For those it's probably better to not alter the database
component of the URI with the schema name, it won't work.
Some database drivers like presto accept '{catalog}/{schema}' in
the database component of the URL, that can be handled here.
"""
示例7: __init__
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def __init__(self, dialect, database, username=None, password=None,
host=None, port=None, query=None):
"""
Accepts configuration for a database connection, and defines SQLAlchemy
ORM objects for all the tables in the database.
"""
# Prepare environment for pymysql
pymysql.install_as_MySQLdb()
pymysql.converters.encoders[np.float64] = pymysql.converters.escape_float
pymysql.converters.conversions = pymysql.converters.encoders.copy()
pymysql.converters.conversions.update(pymysql.converters.decoders)
db_url = URL(drivername=dialect, database=database, username=username,
password=password, host=host, port=port, query=query)
self.engine = create_engine(db_url)
self.session = None
self.get_session = sessionmaker(bind=self.engine,
expire_on_commit=False)
# create ORM objects for the tables
self._define_tables()
示例8: main_mulprocessing
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def main_mulprocessing(min_id=None,
max_id=None,
window_size=5000,
number_of_processes=4,
drop_first=False):
engine = create_engine(
URL(**CONF['database']['connect_args']),
pool_size=1,
pool_recycle=CONF['database']['pool_recycle'],
client_encoding='utf8')
init_tables(engine, drop_first)
try:
manager = ParserManager(
min_id=min_id,
max_id=max_id,
window_size=window_size,
number_of_processes=number_of_processes)
manager.start()
manager.join()
except (KeyboardInterrupt, SystemExit):
logger.info('interrupt signal received')
sys.exit(1)
except Exception as e:
raise e
示例9: create_database_engine
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def create_database_engine(user, password, database, host, port):
"""Create a database engine"""
driver = 'mysql+pymysql'
url = URL(driver, user, password, host, port, database,
query={'charset': 'utf8mb4'})
# Generic parameters for the engine.
#
# SSL param needs a non-empty dict to be activated in pymsql.
# That is why a fake parameter 'activate' is given but not
# used by the library.
#
engine_params = {
'poolclass': QueuePool,
'pool_size': 25,
'pool_pre_ping': True,
'echo': False,
'connect_args': {
'ssl': {
'activate': True
}
}
}
engine = create_engine(url, **engine_params)
try:
engine.connect().close()
except InternalError:
# Try non-SSL connection
engine_params['connect_args'].pop('ssl')
engine = create_engine(url, **engine_params)
engine.connect().close()
return engine
示例10: db_connect
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def db_connect(self):
"""
Performs database connection using database settings from settings.py.
Returns sqlalchemy engine instance
"""
domain = ConfigKeys.DATABASE
params = {
'drivername': self.driver,
}
host = self.env.config.get(ConfigKeys.HOST, default=None, domain=domain)
port = self.env.config.get(ConfigKeys.PORT, default=None, domain=domain)
username = self.env.config.get(ConfigKeys.USER, default=None, domain=domain)
password = self.env.config.get(ConfigKeys.PASSWORD, default=None, domain=domain)
database = self.env.config.get(ConfigKeys.DB, default=None, domain=domain)
pool_size = self.env.config.get(ConfigKeys.POOL_SIZE, default=75, domain=domain)
if host is not None and host != '':
params['host'] = host
if port is not None and port != '':
params['port'] = port
if username is not None and username != '':
params['username'] = username
if password is not None and password != '':
params['password'] = password
if database is not None and database != '':
params['database'] = database
return create_engine(URL(**params), pool_recycle=280, pool_size=pool_size)
示例11: _compile_dialect
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def _compile_dialect(self, execute_observed):
if self.dialect == 'default':
return DefaultDialect()
else:
# ugh
if self.dialect == 'postgresql':
params = {'implicit_returning': True}
else:
params = {}
return url.URL(self.dialect).get_dialect()(**params)
示例12: __call__
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def __call__(self, cfg, *arg):
if isinstance(cfg, compat.string_types):
url = sa_url.make_url(cfg)
elif isinstance(cfg, sa_url.URL):
url = cfg
else:
url = cfg.db.url
backend = url.get_backend_name()
if backend in self.fns:
return self.fns[backend](cfg, *arg)
else:
return self.fns['*'](cfg, *arg)
示例13: __call__
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def __call__(self, cfg, *arg):
if isinstance(cfg, compat.string_types):
url = sa_url.make_url(cfg)
elif isinstance(cfg, sa_url.URL):
url = cfg
else:
url = cfg.db.url
backend = get_url_backend_name(url)
if backend in self.fns:
return self.fns[backend](cfg, *arg)
else:
return self.fns['*'](cfg, *arg)
示例14: get_db_uri
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def get_db_uri():
from zou.app.config import DATABASE
return URL(**DATABASE)
示例15: parser_engines
# 需要导入模块: from sqlalchemy.engine import url [as 别名]
# 或者: from sqlalchemy.engine.url import URL [as 别名]
def parser_engines(cls):
connections = settings.DATABASE_CONNECTION
engines = {}
for connection_name, connection_item in connections.items():
if connection_name in engines:
raise ConfigError('conn:%s ,has already exist.' % connection_name)
engines[connection_name] = {
'kwargs': connection_item.get('kwargs', {}),
'master': [],
'slaves': [],
}
connections_str = connection_item['connections']
for conn in connections_str:
dburl = url.URL(drivername=conn['DRIVER']
, username=conn['UID']
, password=conn['PASSWD']
, host=conn['HOST']
, port=conn['PORT']
, database=conn['DATABASE']
, query=conn['QUERY'])
if conn['ROLE'] == _CONNECTION_TYPE[0]:
engines[connection_name]['master'].append(dburl)
elif conn['ROLE'] == _CONNECTION_TYPE[1]:
engines[connection_name]['slaves'].append(dburl)
else:
raise ConfigError('role %s not allowed.' % conn['ROLE'])
if not len(engines[connection_name]['master']):
raise ConfigError('conn:%s ,master connection not found.' % connection_name)
return engines