本文整理汇总了Python中sqlalchemy_utils.create_database函数的典型用法代码示例。如果您正苦于以下问题:Python create_database函数的具体用法?Python create_database怎么用?Python create_database使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create_database函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: init_data
def init_data():
from imports import (
Widget,Article,Page,
User,Setting,Type,
Template,Tag,Role,
Category,Block,Profile,
ContactMessage)
"""Fish data for project"""
if prompt_bool('Do you want to kill your db?'):
if squ.database_exists(db.engine.url):
squ.drop_database(db.engine.url)
try:
db.drop_all()
except:
pass
try:
squ.create_database(db.engine.url)
db.create_all()
except:
pass
user = User.query.filter(User.email=='[email protected]').first()
if user is None:
user = User(username='kyle', email='[email protected]', password='14wp88')
user.save()
开发者ID:4johndoe,项目名称:flask-cms,代码行数:25,代码来源:manage.py
示例2: create_ctfd
def create_ctfd(ctf_name="CTFd", name="admin", email="[email protected]", password="password", setup=True):
app = create_app('CTFd.config.TestingConfig')
url = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
if url.drivername == 'postgres':
url.drivername = 'postgresql'
if database_exists(url):
drop_database(url)
create_database(url)
with app.app_context():
app.db.create_all()
if setup:
with app.app_context():
with app.test_client() as client:
data = {}
r = client.get('/setup') # Populate session with nonce
with client.session_transaction() as sess:
data = {
"ctf_name": ctf_name,
"name": name,
"email": email,
"password": password,
"nonce": sess.get('nonce')
}
client.post('/setup', data=data)
return app
开发者ID:semprix,项目名称:CTFIgniter,代码行数:28,代码来源:helpers.py
示例3: setup
def setup():
print(app.config['SQLALCHEMY_DATABASE_URI'])
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
if database_exists(engine.url):
drop_database(engine.url)
create_database(engine.url)
engine.execute('create extension if not exists fuzzystrmatch')
开发者ID:massover,项目名称:jaypeak,代码行数:7,代码来源:manage.py
示例4: makeDbEngine
def makeDbEngine(self):
'''
function to establish engine with PostgreSQl database
so that additional tables can be made
'''
try:
## connect to Postgres
dbname = self.getDbName()
username = self.getUserName()
print dbname
print username
## create and set
engine = create_engine('postgres://%[email protected]/%s'%(username, dbname))
self.setDbEngine(engine)
## test if it exists
db_exist = database_exists(engine.url)
if not db_exist:
create_database(engine.url)
db_exist = database_exists(engine.url)
self.setDbExist(db_exist)
return 0
except:
return 1
开发者ID:astrophys-degroot,项目名称:ncaa_mens_basketball,代码行数:25,代码来源:ncaa_basketball_db.py
示例5: add_db
def add_db(): # pragma: no cover
db_url = config['service']['db_uri']
global engine
engine = create_engine(db_url)
if database_exists(engine.url):
print('!!! DATABASE ALREADY EXISTS !!!')
return False
print()
print('!!! DATABASE NOT DETECTED !!!')
print()
try:
confirm = input('Create database designated in the config file? [Y/n]') or 'Y'
except KeyboardInterrupt:
confirm = ''
print()
if confirm.strip() != 'Y':
print('Not createing DB. Exiting.')
return False
create_database(engine.url)
return True
开发者ID:rewardStyle,项目名称:generator-plait,代码行数:25,代码来源:_model.py
示例6: init_db
def init_db(self):
"""
Initializes the database connection based on the configuration parameters
"""
db_type = self.config['db_type']
db_name = self.config['db_name']
if db_type == 'sqlite':
# we can ignore host, username, password, etc
sql_lite_db_path = os.path.join(os.path.split(CONFIG)[0], db_name)
self.db_connection_string = 'sqlite:///{}'.format(sql_lite_db_path)
else:
username = self.config['username']
password = self.config['password']
host_string = self.config['host_string']
self.db_connection_string = '{}://{}:{}@{}/{}'.format(db_type, username, password, host_string, db_name)
self.db_engine = create_engine(self.db_connection_string)
# If db not present AND type is not SQLite, create the DB
if not self.config['db_type'] == 'sqlite':
if not database_exists(self.db_engine.url):
create_database(self.db_engine.url)
Base.metadata.bind = self.db_engine
Base.metadata.create_all()
# Bind the global Session to our DB engine
global Session
Session.configure(bind=self.db_engine)
开发者ID:MITRECND,项目名称:multiscanner,代码行数:26,代码来源:sql_driver.py
示例7: create_postgres_db
def create_postgres_db():
dbname = 'beer_db_2'
username = 'postgres'
mypassword = 'simple'
## Here, we're using postgres, but sqlalchemy can connect to other things too.
engine = create_engine('postgres://%s:%[email protected]/%s'%(username,mypassword,dbname))
print "Connecting to",engine.url
if not database_exists(engine.url):
create_database(engine.url)
print "Does database exist?",(database_exists(engine.url))
# load a database from CSV
brewery_data = pd.DataFrame.from_csv('clean_data_csv/brewery_information_rescrape.csv')
## insert data into database from Python (proof of concept - this won't be useful for big data, of course)
## df is any pandas dataframe
brewery_data.to_sql('breweries', engine, if_exists='replace')
#dbname = 'beer_review_db'
# load a database from CSV
beer_data = pd.DataFrame.from_csv('clean_data_csv/beer_review_information_rescrape.csv')
#engine_2 = create_engine('postgres://%s:%[email protected]/%s'%(username,mypassword,dbname))
#print "connecting to",engine.url
#if not database_exists(engine_2.url):
# create_database(engine_2.url)
#print "Does database exist?",(database_exists(engine_2.url))
beer_data.to_sql('reviews',engine,if_exists='replace')
print "database",dbname,"has been created"
return
开发者ID:Jollyhrothgar,项目名称:ale_trail_codebase,代码行数:33,代码来源:create_db_from_csv.py
示例8: app
def app(request):
"""The Flask API (scope = Session)."""
config.DB_NAME = DB_NAME
DATABASE_URI = config.DATABASE_URI.format(**config.__dict__)
if not database_exists(DATABASE_URI):
create_database(DATABASE_URI)
print "Test Database: %s" % DATABASE_URI
# Config the app
_app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URI
_app.config["SQLALCHEMY_ECHO"] = True # Toggle SQL Alchemy output
_app.config["DEBUG"] = True
_app.config["TESTING"] = True
# Establish an application context before running the tests.
ctx = _app.app_context()
ctx.push()
# Initialize a null cache
cache.config = {}
cache.init_app(_app)
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return _app
开发者ID:adriancooney,项目名称:examist,代码行数:29,代码来源:conftest.py
示例9: create_findmyride_database
def create_findmyride_database(database_name):
engine = create_engine('postgresql://%s:%[email protected]/%s'%('dianeivy', password, database_name))
print(engine.url)
if not database_exists(engine.url):
create_database(engine.url)
print(database_exists(engine.url))
return engine
开发者ID:dianeivy,项目名称:FindMyRide,代码行数:8,代码来源:create_weather_database.py
示例10: create_db_test
def create_db_test():
create_database(url_db)
session = sessionmaker()
engine = create_engine(url_db)
session.configure(bind=engine)
Base.metadata.create_all(engine)
return engine
开发者ID:lffsantos,项目名称:captura,代码行数:8,代码来源:helper.py
示例11: create_db
def create_db(app):
from project.core.db import db
from sqlalchemy_utils import database_exists, create_database
if not database_exists(db.engine.url):
print '====> Create database'
create_database(db.engine.url)
else:
print '====> database exist'
开发者ID:fuboy,项目名称:tornado-base,代码行数:8,代码来源:manager.py
示例12: start_fixture
def start_fixture(self):
"""Create necessary temp files and do the config dance."""
global CONF
data_tmp_dir = tempfile.mkdtemp(prefix='gnocchi')
coordination_dir = os.path.join(data_tmp_dir, 'tooz')
os.mkdir(coordination_dir)
coordination_url = 'file://%s' % coordination_dir
conf = service.prepare_service([])
CONF = self.conf = conf
self.tmp_dir = data_tmp_dir
# Use the indexer set in the conf, unless we have set an
# override via the environment.
if 'GNOCCHI_TEST_INDEXER_URL' in os.environ:
conf.set_override('url',
os.environ.get("GNOCCHI_TEST_INDEXER_URL"),
'indexer')
# TODO(jd) It would be cool if Gabbi was able to use the null://
# indexer, but this makes the API returns a lot of 501 error, which
# Gabbi does not want to see, so let's just disable it.
if conf.indexer.url is None or conf.indexer.url == "null://":
raise case.SkipTest("No indexer configured")
# Use the presence of DEVSTACK_GATE_TEMPEST as a semaphore
# to signal we are not in a gate driven functional test
# and thus should override conf settings.
if 'DEVSTACK_GATE_TEMPEST' not in os.environ:
conf.set_override('driver', 'file', 'storage')
conf.set_override('coordination_url', coordination_url, 'storage')
conf.set_override('policy_file',
os.path.abspath('etc/gnocchi/policy.json'),
group="oslo_policy")
conf.set_override('file_basepath', data_tmp_dir, 'storage')
# NOTE(jd) All of that is still very SQL centric but we only support
# SQL for now so let's say it's good enough.
url = sqlalchemy_url.make_url(conf.indexer.url)
url.database = url.database + str(uuid.uuid4()).replace('-', '')
db_url = str(url)
conf.set_override('url', db_url, 'indexer')
sqlalchemy_utils.create_database(db_url)
index = indexer.get_driver(conf)
index.connect()
index.upgrade()
conf.set_override('pecan_debug', False, 'api')
# Turn off any middleware.
conf.set_override('middlewares', [], 'api')
self.index = index
开发者ID:idegtiarov,项目名称:gnocchi-rep,代码行数:58,代码来源:fixtures.py
示例13: createdb
def createdb():
print "Connecting to %s" % settings.SQLALCHEMY_DATABASE_URI
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI)
if settings.DROP_DB_ON_RESTART and database_exists(engine.url):
print "Dropping old database... (because DROP_DB_ON_RESTART=True)"
drop_database(engine.url)
if not database_exists(engine.url):
print "Creating databases..."
create_database(engine.url)
开发者ID:occrp,项目名称:osoba,代码行数:9,代码来源:core.py
示例14: start_fixture
def start_fixture(self):
"""Set up config."""
self.conf = None
self.conn = None
# Determine the database connection.
db_url = os.environ.get(
'AODH_TEST_STORAGE_URL', "").replace(
"mysql://", "mysql+pymysql://")
if not db_url:
self.fail('No database connection configured')
conf = service.prepare_service([], config_files=[])
# NOTE(jd): prepare_service() is called twice: first by load_app() for
# Pecan, then Pecan calls pastedeploy, which starts the app, which has
# no way to pass the conf object so that Paste apps calls again
# prepare_service. In real life, that's not a problem, but here we want
# to be sure that the second time the same conf object is returned
# since we tweaked it. To that, once we called prepare_service() we
# mock it so it returns the same conf object.
self.prepare_service = service.prepare_service
service.prepare_service = mock.Mock()
service.prepare_service.return_value = conf
conf = fixture_config.Config(conf).conf
self.conf = conf
opts.set_defaults(self.conf)
conf.set_override('policy_file',
os.path.abspath(
'aodh/tests/open-policy.json'),
group='oslo_policy',
enforce_type=True)
conf.set_override(
'paste_config',
os.path.abspath('aodh/tests/functional/gabbi/gabbi_paste.ini'),
group='api',
)
conf.set_override('pecan_debug', True, group='api',
enforce_type=True)
parsed_url = urlparse.urlparse(db_url)
if parsed_url.scheme != 'sqlite':
parsed_url = list(parsed_url)
parsed_url[2] += '-%s' % str(uuid.uuid4()).replace('-', '')
db_url = urlparse.urlunparse(parsed_url)
conf.set_override('connection', db_url, group='database',
enforce_type=True)
if (parsed_url[0].startswith("mysql")
or parsed_url[0].startswith("postgresql")):
sqlalchemy_utils.create_database(conf.database.connection)
self.conn = storage.get_connection_from_config(self.conf)
self.conn.upgrade()
开发者ID:ISCAS-VDI,项目名称:aodh-base,代码行数:57,代码来源:fixtures.py
示例15: createDatabase
def createDatabase(dbName):
"""Create specified database if it doesn't exist."""
config = CONFIG_DB
connectString = "postgresql://{}:{}@{}:{}/{}".format(
config["username"], config["password"], config["host"], config["port"], dbName
)
if not sqlalchemy_utils.database_exists(connectString):
sqlalchemy_utils.create_database(connectString)
开发者ID:fedspendingtransparency,项目名称:data-act-core,代码行数:9,代码来源:databaseSetup.py
示例16: _create_new_database
def _create_new_database(cls, url):
"""Used by testing to create a new database."""
purl = sqlalchemy_url.make_url(
cls.dress_url(
url))
purl.database = purl.database + str(uuid.uuid4()).replace('-', '')
new_url = str(purl)
sqlalchemy_utils.create_database(new_url)
return new_url
开发者ID:shushen,项目名称:gnocchi,代码行数:9,代码来源:sqlalchemy.py
示例17: initialize
def initialize(re_createTable= False):
if re_createTable :
if not database_exists(engine.url):
create_database(DATABASE.url)
print(database_exists(engine.url))
Base.metadata.drop_all(DATABASE, checkfirst = True)
Base.metadata.create_all(DATABASE, checkfirst = True)
开发者ID:jeeka321,项目名称:Production,代码行数:10,代码来源:models.py
示例18: setUp
def setUp(self):
self.app = self.create_app()
self.db = DB(engine,session,meta)
import sqlalchemy_utils as squ
if squ.database_exists(self.db.engine.url):
squ.drop_database(self.db.engine.url)
squ.create_database(self.db.engine.url)
meta.bind = self.db.engine
meta.create_all()
开发者ID:c0debrain,项目名称:flask-cms,代码行数:10,代码来源:testing.py
示例19: check_schema
def check_schema(schema):
url = db.engine.url
if url.database != schema:
copy_url = copy.copy(url)
copy_url.database = schema
url = copy_url
if not database_exists(url):
create_database(url)
开发者ID:aip,项目名称:phics,代码行数:10,代码来源:__init__.py
示例20: setUpClass
def setUpClass(cls):
cls.engine = create_engine('postgresql+psycopg2://[email protected]/monitor_test')
if not database_exists(cls.engine.url):
create_database(cls.engine.url, template='template_postgis')
model.create_database(cls.engine, drop=True)
cls.monitor = StatusMonitor(cls.engine)
cls.monitor.read_expected_csv(os.path.join(test_dir, 'data', 'expected-rates.csv'))
开发者ID:oceanobservatories,项目名称:ooi-status,代码行数:10,代码来源:test_db.py
注:本文中的sqlalchemy_utils.create_database函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论