예제 #1
0
파일: db.py 프로젝트: bmnz90/cozy
def init_db():
    global db
    global update
    global data_dir

    tmp_db = None
    
    if update:
        update_db()
    else:
        tmp_db = SqliteDatabase(os.path.join(data_dir, "cozy.db"))
        if PeeweeVersion[0] == '2':
            with tmp_db.connection_context():
                tmp_db.create_tables([Track, Book, Settings, ArtworkCache, Storage, StorageBlackList, OfflineCache], True)
        else:
            with tmp_db.connection_context():
                tmp_db.create_tables([Track, Book, Settings, ArtworkCache, Storage, StorageBlackList, OfflineCache])

    # this is necessary to ensure that the tables have indeed been created
    if tmp_db:
        while not tmp_db.table_exists("settings"):
            time.sleep(0.01)

    try:
        db.connect()
    except Exception as e:
        log.error("Could not connect to database. ")
        log.error(e)


    if PeeweeVersion[0] == '3':
        db.bind([Book, Track, Settings, ArtworkCache, StorageBlackList, OfflineCache, Storage], bind_refs=False, bind_backrefs=False)

    if (Settings.select().count() == 0):
        Settings.create(path="", last_played_book=None)
예제 #2
0
def setup_person_table(db_name):
    '''setup a people SQLite3 database'''
    db = SqliteDatabase(db_name)
    if db.connect():
        if db.table_exists('person'):
            print(f'''WARNING: person already exists in {db_name}''')
        else:
            db.create_tables([Person])
    else:
        print(f'''ERROR: could not connect to {db_name}''')
def init_db(configuration: Configuration):
    if configuration.debug:
        local_dir = _try_dir("/opt/too-simple", _IN_USER_DIR)
        database = SqliteDatabase(f"{local_dir}/debug.db")
    else:

        host, port = configuration.pg_db_url.split(":")
        connection_kwargs = dict(host=host,
                                 port=port,
                                 user=configuration.pg_username,
                                 password=configuration.pg_password)
        _create_psql_database(configuration.pg_database, **connection_kwargs)
        database = PostgresqlDatabase(configuration.pg_database,
                                      **connection_kwargs)

    DB.initialize(database)
    if not database.table_exists(Entity.__name__):
        database.create_tables([Entity])
        database.commit()
예제 #4
0
def init_db():
    tmp_db = None

    _connect_db(_db)

    if Settings.table_exists():
        update_db()
    else:
        tmp_db = SqliteDatabase(os.path.join(get_data_dir(), "cozy.db"))
        if PeeweeVersion[0] == '2':
            tmp_db.create_tables([
                Track, Book, Settings, ArtworkCache, Storage, StorageBlackList,
                OfflineCache
            ], True)
        else:
            with tmp_db.connection_context():
                tmp_db.create_tables([
                    Track, Book, Settings, ArtworkCache, Storage,
                    StorageBlackList, OfflineCache
                ])

    # this is necessary to ensure that the tables have indeed been created
    if tmp_db:
        if PeeweeVersion[0] == '2':
            while not Settings.table_exists():
                time.sleep(0.01)
        else:
            while not tmp_db.table_exists("settings"):
                time.sleep(0.01)

    _connect_db(_db)

    if PeeweeVersion[0] == '3':
        _db.bind([
            Book, Track, Settings, ArtworkCache, StorageBlackList,
            OfflineCache, Storage
        ],
                 bind_refs=False,
                 bind_backrefs=False)

    if (Settings.select().count() == 0):
        Settings.create(path="", last_played_book=None)
예제 #5
0
class NLTKReflections(Model):
    active = BooleanField(default=True)
    reflection_phrase = TextField(null=True)
    reflection = TextField(null=True)

    class Meta:
        database = db
        verbose_name = "Reflection"
        verbose_name_plural = "Reflections"


class NLTKPairs(Model):
    active = BooleanField(default=True)
    question = TextField(null=True)
    answer = TextField(null=True)

    class Meta:
        database = db
        verbose_name = "Question pattern"
        verbose_name_plural = "Question Patterns"


db.connect()

models = [NLTKReflections, NLTKPairs]

for model in models:
    if not db.table_exists(model):
        db.create_tables([model])
class BaseModel(Model):
    """ Base model for Customer """
    class Meta:
        """ Meta class for the model """
        database = db


class Customer(BaseModel):
    """
        This class defines Customer, which maintains
        the details of the customer's contact information.
    """
    customer_id = AutoField()  # Auto-incrementing primary key.
    customer_name = CharField(max_length=50)
    customer_lastname = CharField(max_length=50)
    customer_address = CharField(max_length=300, null=True)
    customer_phone_number = CharField(max_length=20, null=True)
    customer_email = CharField(max_length=100, null=True)
    status = BooleanField(default=False)
    credit_limit = DoubleField(null=True)

    # credit_limit = DecimalField(max_digits=18, decimal_places=2)

    class Meta:
        """ Meta class to name the table """
        table_name = 'customers'


if not db.table_exists(Customer):
    db.create_tables([Customer])
    class Meta:
        database = database


class NameCat(BaseModel):
    record_id = CharField(40, unique=True)
    name = CharField(50)
    cat = CharField(50)

    def __init__(self, record_id, name, cat, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.record_id = record_id
        self.cat = cat
        self.name = name

    def keys(self):
        return ['record_id', 'name', 'cat']

    def __getitem__(self, item):
        return vars(self).get("__data__", {}).get(item, None)

    def __setitem__(self, item, value):
        if item == 'cat':
            self.cat = value
        if item == 'name':
            self.name = value


if not database.table_exists(NameCat):
    database.create_tables([NameCat])
예제 #8
0
            )
        else:
            next_birthday = birthday.replace(
                year=today.year
                if birthday.replace(year=today.year) >= today
                else today.year + 1
            )
        return (next_birthday - today).days

    @staticmethod
    def next_leap_year(given_year):
        leap_year = None
        while not leap_year:
            if given_year % 4 == 0 or given_year % 400 == 0 and given_year % 100 == 0:
                leap_year = given_year
            given_year = given_year + 1
        return leap_year

    @staticmethod
    def filter_numbers(string):
        return functools.reduce(lambda a, b: a + b if b.isnumeric() else a, string, "")


if __name__ == "__main__":
    if not db.table_exists("person"):
        db.create_tables([Person])
    App.parse()
    actions = Actions(App.args)
    actions.execute()

예제 #9
0
db = SqliteDatabase("todo.db")

flask_db = FlaskDB(database=db)
flask_db.init_app(app)


class ToDo(Model):
    class Meta:
        database = db

    title = CharField(max_length=255)
    order = IntegerField()
    done = BooleanField(default=False)


if not db.table_exists("todo"):
    db.create_tables([ToDo])


@app.route("/")
def index():
    if request.json:
        return jsonify("success")
    # return render_template('collections.html')
    return render_template("index.html")


class ManView(MethodView):
    def get(self):
        pass