def setup(entities): """ Setup the database based on a list of user's entities """ elixir.setup_entities(entities) elixir.create_all()
def setup(): """Setup the database and create the tables that don't exists yet""" from elixir import setup_all, create_all from couchpotato import get_engine setup_all() create_all(get_engine())
def init_db_from_scratch(): """Build the necessary stuff in the db to run.""" init_db() elixir.drop_all() elixir.create_all() elixir.metadata.bind.execute(FIRST_FUNCTION) filler_data()
def setUp(self): """Creates the database, the :class:`~flask.Flask` object, the :class:`~flask_restless.manager.APIManager` for that application, and creates the ReSTful API endpoints for the :class:`testapp.Person` and :class:`testapp.Computer` models. """ # create the database self.db_fd, self.db_file = mkstemp() setup(create_engine('sqlite:///%s' % self.db_file)) create_all() # create the Flask application app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['TESTING'] = True self.app = app.test_client() # setup the URLs for the Person and Computer API self.manager = APIManager(app) self.manager.create_api(Person, methods=['GET', 'PATCH', 'POST', 'DELETE']) self.manager.create_api(Computer, methods=['GET', 'POST']) # to facilitate searching self.app.search = lambda url, q: self.app.get(url + '?q={}'.format(q))
def initDB(drop=False): from elixir import metadata, setup_all, drop_all, create_all from genericpath import exists from os import makedirs from posixpath import expanduser DB_NAME = "stockflow.sqlite" log = logging.getLogger(__name__) log.info("Inicializando o Core") dbpath = expanduser("~/.stockflow/") if not exists(dbpath): try: makedirs(dbpath) except OSError: log.warning("Nao foi possivel criar os diretorios, \ usando o home do usuário.") dbpath = expanduser("~") metadata.bind = "".join(("sqlite:///", dbpath, DB_NAME)) metadata.bind.echo = False setup_all() if(drop): drop_all() if not exists("".join((dbpath, DB_NAME))) or drop: log.debug("Criando tabelas...") create_all()
def __init__(self, filename): db_url = 'sqlite:///' + filename metadata.bind = db_url #metadata.bind.echo = True setup_all() if not os.path.exists(filename): create_all()
def create_storage(self): try: server = DatabaseServer(self.server_config) except: logger.log_error( 'Cannot connect to the database server that the services database is hosted on %s.' % self.server_config.database_name) raise if not server.has_database(self.server_config.database_name): server.create_database(self.server_config.database_name) try: services_db = server.get_database(self.server_config.database_name) except: logger.log_error('Cannot connect to a services database on %s.' % server.get_connection_string(scrub=True)) raise metadata.bind = services_db.engine setup_all() create_all() return services_db
def __init__(self, name, path): self.path = path self.name = name self.unrecognizedPerson = None self.connect() elixir.create_all() self.commit()
def setup(): """ Setup the database and create the tables that don't exists yet """ from elixir import setup_all, create_all from couchpotato import get_engine setup_all() create_all(get_engine())
def setup(options, kws, files, model = None): if model is None: model = load_model(options, kws, files) if 'drop' in options: print "DROPPING ALL TABLES" elixir.drop_all(bind=model.engine) if 'schema' in options or 'all' in options: print "CREATING TABLES" elixir.create_all(bind=model.engine) if 'views' in options: print "(RE)CREATING VIEWS" with model.engine.Session() as session: for view_method in elixir.metadata.ddl_listeners['after-create']: view = view_method.im_self if isinstance(view, Argentum.View): if not 'skip-materialized' in options or not view.is_materialized: view_method(None, elixir.metadata, session.bind) if 'data' in options or 'all' in options: print "INSERTING ORIGINAL DATA" with model.engine.Session() as session: model.createInitialData(session, *options, **kws)
def install(): """ Install database an default values """ # Drop tables print("Dropping all tables...") drop_all() # Create tables print("Creating all tables...") create_all() # Create default data buildingA = Localisation(building=u"Batiment A", floor=1) buildingB = Localisation(building=u"Batiment B", floor=1, phone=u"5104") buildingC = Localisation(building=u"Batiment C", floor=2, phone=u"3388") Person(firstname=u"Stéphanie", lastname=u"De Monaco", birthdate=date(1980, 4, 4), localisation=buildingA) Person(firstname=u"Jean", lastname=u"Delarue", birthdate=date(1960, 10, 6), localisation=buildingA) Person(firstname=u"Jean-Pierre", lastname=u"Pernault", birthdate=date(1981, 7, 4), localisation=buildingB) Person(firstname=u"Anne", lastname=u"Sinclair", birthdate=date(1975, 8, 7), localisation=buildingC) Person(firstname=u"Julien", lastname=u"Lepers", birthdate=date(1975, 8, 7), localisation=buildingC) Team(name=u"Manchester") Team(name=u"Barça") Team(name=u"Racing Club de Strasbourg") session.commit() print("Installation success with data test")
def setUp(self): e.create_all() self.movie_alias = pyamf.register_class(Movie, 'movie') self.genre_alias = pyamf.register_class(Genre, 'genre') self.director_alias = pyamf.register_class(Director, 'director') self.create_movie_data()
def setupDB(self): """Initialize/read database on disk""" self.db = SqlSoup(SQLITE + PATH_TO_RES + KANJIDIC2) #TODO: add check up setup_all() if not os.path.exists(PATH_TO_RES + DBNAME): create_all() session.bind = metadata.bind
def setupDB(self): """Initialize/read database on disk""" # self.db = SqlSoup(SQLITE + PATH_TO_RES + KANJIDIC2) setup_all() if not os.path.exists(PATH_TO_RES + DBNAME): create_all() session.bind = metadata.bind
def setUpClass(cls): # self._setupdb() logging.basicConfig(level=logging.DEBUG, format="%(funcName)s - %(lineno)d - %(message)s") metadata.bind = 'sqlite:///:memory:' create_all() from parsers import rosenberg_parser rosenberg_parser(open(cls.testfile, 'r')) logging.debug('DB (rosenberg test) has been set')
def createDb(): """ A function to create the database and fill some tables """ if not dbExists(): elixir.create_all() for fstate in FILESTATES: fis = FileState(state=fstate) elixir.session.commit()
def init_db(path=paths['freq_db']): """ Initialize specified DB. In case no DB file exists, it will be created. """ metadata.bind = "sqlite:///" + path setup_all() if not os.path.exists(path): create_all()
def create_new_database(): # Read schema and create entities setup_all() # Drop all the existing database. Warning!! metadata.drop_all() # Issue the commands to the local database create_all()
def gjms_config(): """ Setup backend config """ form = gjms.backend.forms.config(flask.request.form) if flask.request.method == "POST": if form.validate_on_submit(): parser.set("gjms", "label", form.label.data) parser.set("gjms", "manager", form.manager.data) parser.set("gjms", "manager_email", form.m_email.data) parser.set("gjms", "theme_voting", form.v_theme.data) parser.set("gjms", "game_ratings", form.ratings.data) parser.set("gjms", "game_comments", form.comments.data) parser.set("gjms", "database_engine", form.engine.data) parser.set("gjms", "database_host", form.host.data) parser.set("gjms", "database_port", form.port.data) parser.set("gjms", "database_user", form.user.data) parser.set("gjms", "database_password", form.password.data) parser.set("gjms", "database", form.db.data) if form.engine.data == "sqlite": db_url = "sqlite:///%s?check_same_thread=False" % form.host.data elif form.engine.data != "sqlite" and form.port.data == "": db_url = "%s://%s:%s@%s/%s" % (form.engine.data, form.user.data, form.password.data, form.host.data, form.db.data) else: db_url = "%s://%s:%s@%s:%s/%s" % (form.engine.data, form.user.data, form.password.data, form.host.data, form.port.data, form.db.data) gjms.util.database.setup(db_url) elixir.setup_all() elixir.create_all() parser.set("gjms", "db_url", db_url) parser.set("gjms", "database_setup", True) cfgfile = open(os.path.abspath(os.path.dirname(__file__)+"/../gjms.cfg"), "w") gjms.config.parser.write(cfgfile) flask.flash(u"Settings saved!", "success") else: flask.flash(u"Woops! That didn't work. Check below for details.", "error") else: form.label.data = parser.get("gjms", "label") form.manager.data = parser.get("gjms", "manager") form.m_email.data = parser.get("gjms", "manager_email") form.v_theme.data = parser.getboolean("gjms", "theme_voting") form.ratings.data = parser.getboolean("gjms", "game_ratings") form.comments.data = parser.getboolean("gjms", "game_comments") form.engine.data = parser.get("gjms", "database_engine") form.host.data = parser.get("gjms", "database_host") form.port.data = parser.get("gjms", "database_port") form.user.data = parser.get("gjms", "database_user") form.password.data = parser.get("gjms", "database_password") form.db.data = parser.get("gjms", "database") system = gjms.core.system.get(1) return flask.render_template("backend/config.html", form=form, time=datetime, system=system, config=parser, users=gjms.core.users, events=gjms.core.events, games=gjms.core.games, platforms=gjms.core.platforms, ratings=gjms.core.ratings)
def init_db(path = paths['freq_db']): """ Initialize specified DB. In case no DB file exists, it will be created. """ metadata.bind = "sqlite:///" + path setup_all() if not os.path.exists(path): create_all()
def __init__(self, dbfilename): try: self.name = dbfilename self.dbsemaphore = QSemaphore(1) # to control concurrent write access to db metadata.bind = "sqlite:///" + dbfilename # metadata.bind.echo = True # uncomment to see detailed database logs setup_all() create_all() except: print "[-] Could not create database. Please try again."
def _test(): import random from elixir import session, metadata, setup_all, create_all connection_line = 'sqlite:///:memory:' metadata.bind = connection_line setup_all() create_all() [iHS('snp_%s' % i, ) for i in xrange(10)]
def setUpClass(cls): # self._setupdb() logging.basicConfig(level=logging.DEBUG, format="%(funcName)s - %(lineno)d - %(message)s") metadata.bind = 'sqlite:///:memory:' create_all() from parsers import genotypes_parser, rosenberg_parser # populate with some individuals rosenberg_parser(open(cls.individualsfile, 'r')) genotypes_parser(open(cls.testfile, 'r')) logging.debug('DB (genotype test) has been set')
def create_new_database(): # Read schema and create entities setup_all() # Drop all the existing database. Warning!! choice = raw_input('drop all existing data? [y/N]') if choice in ('y', 'Y', 'yes', 'Yes', '1'): metadata.drop_all() # Issue the commands to the local database create_all()
def init(cls): """ Initialisation de la bdd Création si besoin des tables """ setup_all() create_all() config = cls.config() if not config: config = cls.reload_config() return config
def __init__(self, dbfilename): if not os.path.exists(os.path.dirname(dbfilename)): os.makedirs(os.path.dirname(dbfilename)) try: self.name = dbfilename metadata.bind = 'sqlite:///' + dbfilename #metadata.bind.echo = True # uncomment to see detailed database logs setup_all() create_all() except: logging.error('[-] Could not create database. Please try again.')
def setUp(self): """Creates a SQLite database in a temporary file and creates and sets up all the necessary tables. """ self.db_fd, self.db_file = mkstemp() setup(create_engine('sqlite:///%s' % self.db_file)) create_all() session.commit() self.model = Person
def setUp(self): """Method used to build a database""" metadata.bind = engine setup_all() create_all() article = Article(author='unknown', title='A Thousand and one nights', content='It has been related to me, O happy King, said Shahrazad') session.add(article) session.flush() session.expunge_all() self.article = Article.get(1)
def __init__(self, dbfilename): if not os.path.exists(os.path.dirname(dbfilename)): os.makedirs(os.path.dirname(dbfilename)) try: self.name = dbfilename metadata.bind = 'sqlite:///'+dbfilename #metadata.bind.echo = True # uncomment to see detailed database logs setup_all() create_all() except: logging.error('[-] Could not create database. Please try again.')
def __init__(self, dbfilename): try: self.name = dbfilename self.dbsemaphore = QSemaphore( 1) # to control concurrent write access to db metadata.bind = 'sqlite:///' + dbfilename # metadata.bind.echo = True # uncomment to see detailed database logs setup_all() create_all() except: print '[-] Could not create database. Please try again.'
def setUp(self): """Creates the database and all necessary tables. """ # set up the database self.db_fd, self.db_file = tempfile.mkstemp() metadata.bind = create_engine('sqlite:///%s' % self.db_file) metadata.bind.echo = False setup_all() create_all() session.commit()
def setUp(self): if not e: self.skipTest("'elixir' is not available") e.setup_all() e.create_all() self.movie_alias = pyamf.register_class(Movie, 'movie') self.genre_alias = pyamf.register_class(Genre, 'genre') self.director_alias = pyamf.register_class(Director, 'director') self.create_movie_data()
def __init__(self, *argl, **argd): super(OAuthDBMixin, self).__init__(*argl, **argd) self.engine = al.create_engine(self.DBPATH, **self.ENGINE_OPTION) self.Session = orm.scoped_session(orm.sessionmaker(bind=self.engine, **self.SESSION_OPTION)) self.metadata = el.metadata self.metadata.bind = self.engine class RequestToken(el.Entity): """ Request Token """ el.using_options(tablename="requestTokens", session=self.Session) token = el.Field(el.Unicode, required=True, index=True) secret = el.Field(el.Unicode, required=True) class AccessToken(el.Entity): """ Access Token """ el.using_options(tablename="accessTokens", session=self.Session) token = el.Field(el.Unicode, required=True, index=True) secret = el.Field(el.Unicode, required=True) sessions = el.OneToMany("SessionInfo") class SessionInfo(el.Entity): """ Session """ el.using_options(tablename="sessions", session=self.Session) sessionId = el.Field(el.Unicode, required=True, index=True) createdAt = el.Field(el.DateTime, required=False) token = el.ManyToOne(AccessToken, inverse="sessions") self.RequestToken = RequestToken self.AccessToken = AccessToken self.SessionInfo = SessionInfo el.setup_all() el.create_all() self.DBSession = lambda: contextlib.closing(self.Session())
def __init__(self, engine): self._session = scoped_session(sessionmaker(autoflush=True, bind=engine)) elixir.setup_all() elixir.create_all(engine) self.search = Searcher(self) self.scrape = Scraper(self) self.providers = Providers(self._session) self.raw = RawAccess(self._session) self.query = self.raw.query # Register providers self.providers.register(providers.IMDB())
def initialize(db_address="sqlite:///:memory:", logger=None, db_echo=True): """Bind the ORM module to a DB and setup and (if necessary) create the tables and mappings defined in the default collection. """ elixir.metadata.bind = db_address if logger is not None: elixir.metadata.bind.logger = logger elixir.metadata.bind.echo = db_echo # Show all SQL queries. # print db_address elixir.setup_all() elixir.create_all()
def setup_db(db_uri, echo=False): #from nobix.schema import check_migration_table from nobix.models import check_migration_table engine = create_engine(db_uri, echo=echo) if engine.name == "sqlite": conn = engine.raw_connection() conn.connection.create_function("regexp", 2, _sqlite_regexp) # Session.configure(bind=engine) metadata.bind = engine check_migration_table(bind=engine) elixir.setup_all() elixir.create_all()
def setup(): """Setup the database and create the tables that don't exists yet""" from elixir import setup_all, create_all from couchpotato.environment import Env engine = Env.getEngine() setup_all() create_all(engine) try: engine.execute("PRAGMA journal_mode = WAL") engine.execute("PRAGMA temp_store = MEMORY") except: pass
def set_databases(self, shape_file_database, road_network_database): self.digital_map = Digital_map(shape_file_database) self.road_network = Road_network(road_network_database) elixir.setup_all() elixir.create_all() self.digital_map.load_database() self.road_network.load_database() self.scene.clear() self.scene.draw_digital_map(self.digital_map) self.scene.draw_road_network(self.road_network) self.wanderlust.load_digital_map(self.digital_map) self.wanderlust.load_road_network(self.road_network)
def upgrade(): bind = op.get_bind() session.bind = bind elixir.metadata.bind = bind elixir.setup_all() elixir.create_all() is_sqlite = bind.engine.name == 'sqlite' select = sa.text('SELECT id, description, due_date, weight FROM card') for card_id, description, due_date, weight in bind.execute(select): if due_date is not None and is_sqlite: due_date = time.strptime(due_date, '%Y-%m-%d') due_date = date(due_date.tm_year, due_date.tm_mon, due_date.tm_mday) DataCardDescription(card_id=card_id, description=description) DataCardDueDate(card_id=card_id, due_date=due_date) DataCardWeight(card_id=card_id, weight=weight) session.flush() if not is_sqlite: # SQLite doesn't support column dropping op.drop_column('card', 'description') op.drop_column('card', 'due_date') op.drop_column('card', 'weight')
def setup_function(_): create_all() Father(name=u"Charles Ingalls") session.flush()
def create_db(inventory_dbname, scanned_dbname): setup_session(inventory_dbname, scanned_dbname) elixir.create_all()
def createDatabaseTables(): elixir.create_all()
def __init__(self, parent=None): QtCore.QThread.__init__(self) QtGui.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.filebrower) #for input file QtCore.QObject.connect(self.ui.pushButton_2, QtCore.SIGNAL("clicked()"), self.submit) #submit QtCore.QObject.connect(self.ui.pushButton_3, QtCore.SIGNAL("clicked()"), self.reset) #reset QtCore.QObject.connect(self.ui.pushButton_4, QtCore.SIGNAL("clicked()"), self.add_taxid1) #add taxid to include QtCore.QObject.connect(self.ui.pushButton_5, QtCore.SIGNAL("clicked()"), self.add_taxid2) #add taxid to exclude QtCore.QObject.connect(self.ui.pushButton_6, QtCore.SIGNAL("clicked()"), self.advance) #add taxid to exclude self.ui.progressBar.hide() self.ui.progressBar.setProperty("value", 0) self.ui.lineEdit_add3 = QtGui.QLineEdit(self.ui.groupBox_2) self.ui.lineEdit_add3.setGeometry(QtCore.QRect(70, 20, 281, 21)) self.ui.lineEdit_add3.setObjectName("lineEdit_3") self.ui.lineEdit_add3.setText( QtGui.QApplication.translate("Form", "", None, QtGui.QApplication.UnicodeUTF8)) completer = QCompleter() self.ui.lineEdit_add3.setCompleter(completer) model = QStringListModel() completer.setModel(model) completer.setModelSorting(QCompleter.CaseInsensitivelySortedModel) Expar.get_data(model) self.ui.lineEdit_add2 = QtGui.QLineEdit(self.ui.groupBox_4) self.ui.lineEdit_add2.setGeometry(QtCore.QRect(70, 19, 281, 21)) self.ui.lineEdit_add2.setObjectName("lineEdit_2") self.ui.lineEdit_add2.setText( QtGui.QApplication.translate("Form", "", None, QtGui.QApplication.UnicodeUTF8)) completer = QCompleter() self.ui.lineEdit_add2.setCompleter(completer) model = QStringListModel() completer.setModel(model) completer.setModelSorting(QCompleter.CaseInsensitivelySortedModel) Expar.get_data(model) self.dbdir = os.path.join(os.path.expanduser("~"), ".pyqtodo") self.dbfile = os.path.join(self.dbdir, str(int(time.time())) + "tasks.sqlite") if not os.path.isdir(self.dbdir): os.mkdir(self.dbdir) # Set up the Elixir internal thingamajigs elixir.metadata.bind = "sqlite:///%s" % self.dbfile elixir.setup_all() if not os.path.exists(self.dbfile): elixir.create_all() global saveData if elixir.__version__ < "0.6": saveData = elixir.session.flush else: saveData = elixir.session.commit saveData()
class Tag(Entity): nome = Field(Unicode(256)) comentarios = ManyToMany('Comentario') class Paragrafo(Entity): id = Field(Unicode(64), primary_key=True) conteudo = Field(Unicode) comentario = OneToMany('Comentario') class Comentario(Entity): data = Field(DateTime) autor = Field(Unicode) autor_url = Field(Unicode) instituicao = Field(Unicode) contribuicao = Field(Unicode) justificativa = Field(Unicode) opiniao = Field(Unicode) proposta = Field(Unicode) tags = ManyToMany(Tag, inverse='comentarios') paragrafo = ManyToOne(Paragrafo) metadata.bind = "sqlite:///db" metadata.bind.echo = True setup_all() if __name__ == '__main__': create_all()
def __init__(self, database_name): self.digital_map = Digital_map(database_name) elixir.setup_all() elixir.create_all()
def gjms_config(): """ Setup backend config """ form = gjms.backend.forms.config(flask.request.form) if flask.request.method == "POST": if form.validate_on_submit(): parser.set("gjms", "label", form.label.data) parser.set("gjms", "manager", form.manager.data) parser.set("gjms", "manager_email", form.m_email.data) parser.set("gjms", "theme_voting", form.v_theme.data) parser.set("gjms", "game_ratings", form.ratings.data) parser.set("gjms", "game_comments", form.comments.data) parser.set("gjms", "database_engine", form.engine.data) parser.set("gjms", "database_host", form.host.data) parser.set("gjms", "database_port", form.port.data) parser.set("gjms", "database_user", form.user.data) parser.set("gjms", "database_password", form.password.data) parser.set("gjms", "database", form.db.data) if form.engine.data == "sqlite": db_url = "sqlite:///%s?check_same_thread=False" % form.host.data elif form.engine.data != "sqlite" and form.port.data == "": db_url = "%s://%s:%s@%s/%s" % ( form.engine.data, form.user.data, form.password.data, form.host.data, form.db.data) else: db_url = "%s://%s:%s@%s:%s/%s" % ( form.engine.data, form.user.data, form.password.data, form.host.data, form.port.data, form.db.data) gjms.util.database.setup(db_url) elixir.setup_all() elixir.create_all() parser.set("gjms", "db_url", db_url) parser.set("gjms", "database_setup", True) cfgfile = open( os.path.abspath(os.path.dirname(__file__) + "/../gjms.cfg"), "w") gjms.config.parser.write(cfgfile) flask.flash(u"Your settings have been saved!", "success") else: flask.flash(u"Woops! That didn't work! Check below for details.", "error") else: form.label.data = parser.get("gjms", "label") form.manager.data = parser.get("gjms", "manager") form.m_email.data = parser.get("gjms", "manager_email") form.v_theme.data = parser.getboolean("gjms", "theme_voting") form.ratings.data = parser.getboolean("gjms", "game_ratings") form.comments.data = parser.getboolean("gjms", "game_comments") form.engine.data = parser.get("gjms", "database_engine") form.host.data = parser.get("gjms", "database_host") form.port.data = parser.get("gjms", "database_port") form.user.data = parser.get("gjms", "database_user") form.password.data = parser.get("gjms", "database_password") form.db.data = parser.get("gjms", "database") if parser.getboolean("gjms", "database_setup") is False: flask.flash(u"Welcome to the Game Jam Management System!", "success") flask.flash( u"To get you started, we need to set up a database for the system to use.", "note") flask.flash( u""" If you want to get started quickly, just hit the Save button and be done with it. The system is pre-configured to use SQLite. You can use MySQL or Postgres too, though! It's up to you, really. """, "note") system = gjms.core.system.get(1) return flask.render_template("backend/config.haml", form=form, time=datetime, system=system, config=parser, users=gjms.core.users, events=gjms.core.events, games=gjms.core.games, platforms=gjms.core.platforms, ratings=gjms.core.ratings)
import elixir, tw2.sqla elixir.session = tw2.sqla.transactional_session() elixir.metadata = elixir.sqlalchemy.MetaData('sqlite:///myapp.db') class Movie(elixir.Entity): title = elixir.Field(elixir.String) director = elixir.Field(elixir.String) genre = elixir.ManyToMany('Genre') cast = elixir.OneToMany('Cast') class Genre(elixir.Entity): name = elixir.Field(elixir.String) def __unicode__(self): return self.name class Cast(elixir.Entity): movie = elixir.ManyToOne(Movie) character = elixir.Field(elixir.String) actor = elixir.Field(elixir.String) elixir.setup_all() try: elixir.create_all() except: pass
def __init__(self, *args, **kwargs): setup_all() create_all() self.session = sessionmaker()() super(HouseSpider, self).__init__(*args, **kwargs)