def makedb(dbfile):
    db = SqliteExtDatabase(dbfile)
    db.connect()

    global BaseModel
    class BaseModel(Model):
        class Meta:
            database = db

    global UniqueString
    class UniqueString(BaseModel):
        raw = CharField(index=True)
        count = IntegerField()
        malware_count = IntegerField()
        p_malware = FloatField(index=True)

    global Entity
    class Entity(BaseModel):
        name = CharField(index=True)
        label = FloatField()

    global String
    class String(BaseModel):
        uniquestring = ForeignKeyField(UniqueString,index=True)
        entity = ForeignKeyField(Entity,index=True)
        source = CharField(index=True,null=True)

    # create database
    db.create_tables([Entity,String,UniqueString])

    return db
Exemple #2
0
def start_database(dbname, sqlite=False, tbl_name=None, **kwargs):
    """Connect to a SQLite or MySQL database.

    Args:
        dbname (str): Database path (SQLite) or name (MySQL).

    Kwargs:
        sqlite (bool): Use SQLite instead of MySQL.
        tbl_name (str): Alternative name for locations table.
        host (str): MySQL host.
        user (str): Username for MySQL.
        passwd (str): Password for MySQL.
        ssl (dict): Dictionary of paths to SSL certificates.
    """
    if sqlite:
        db = SqliteExtDatabase(dbname)
    else:
        db = MySQLDatabase(dbname, **kwargs)

    if tbl_name is not None:
        Location._meta.db_table = tbl_name.strip()

    dbproxy.initialize(db)
    db.create_table(Location, safe=True)

    return db
Exemple #3
0
class Database(object):
	def __init__(self, database):
		"""Create a Database object.

		:param database: database file name
		:type database: str
		:returns:  Database

		"""

		self.database = SqliteExtDatabase('%s.db' % database)
		self.models = models

	def create(self, force = False, verbose = True):
		"""Create the database: create the file and the database tables.

		:param force: force the creation of a database even if another with the same name already exists
		:type db: bool

		"""

		if not os.path.isfile(self.database.database) or force == True: # self.database.database corresponds to the database file
			try:
				self.database.create_tables([self.models.Category, self.models.Music, self.models.Rating, self.models.Score])
			except Exception:
				print("Une erreur est survenue lors de la création de la base de données.")
		else:
			if verbose:
				print("La base de données existe déjà.")

	def connect(self):
		"""Connect to the database."""

		try:
			self.database.connect()
		except Exception:
			print("Une erreur est survenue lors de la connexion à la base de données.")

	def populate(self, what):
		""" Populate database with CSV files"""

		if what == "categories":
			csv_data = csv.get_csv_data("%s/categories" % settings.POPULATE_FILES_DIR)
			for data in csv_data:
				try:
					models.Category.create(name=data[0])
				except Exception:
					print("Une erreur est survenue lors du remplissage de la base de données.")
		elif what == "musics":
			csv_data_files = csv.get_csv_data("%s/musics" % settings.POPULATE_FILES_DIR, 7) # Hardcoded number of musics CSV file should be fixed
			for csv_data in csv_data_files:
				for data in csv_data:
					try:
						models.Music.create(name=data[0], category=data[1])
					except Exception:
						print("Une erreur est survenue lors du remplissage de la base de données.")
Exemple #4
0
def memdb():
    mdb = SqliteExtDatabase(':memory:')
    models = [db.Job]
    mdb.bind(models)
    mdb.connect()
    mdb.create_tables(models)

    yield mdb

    mdb.close()
Exemple #5
0
def get_tape_mgr(db=None):
    changer = get_changer()
    if db is None:
        db = SqliteExtDatabase(':memory:')
        db.connect()
        database_proxy.initialize(db)
    return tapemgr.TapeManager(db,
                               changer,
                               storage_choosers,
                               cleaning_chooser,
                               init_db=True)
Exemple #6
0
    def __init__(self, database):
        """Create a Database object.

		:param database: database file name
		:type database: str
		:returns:  Database

		"""

        self.database = SqliteExtDatabase('%s.db' % database)
        self.models = models
Exemple #7
0
def test_database():
    test_db = SqliteExtDatabase(":memory:")
    with test_db.bind_ctx(ALL_MODELS):
        test_db.create_tables(ALL_MODELS)
        try:
            yield
        finally:
            test_db.drop_tables(ALL_MODELS)
            test_db.close()
Exemple #8
0
    def init_database(self):
        migrate_db = SqliteExtDatabase(self.config.database.path)

        # Run migrations
        del (logging.getLogger('peewee_migrate').handlers[:])
        router = Router(migrate_db)
        router.run()

        migrate_db.close()

        self.db = SqliteQueueDatabase(self.config.database.path)
        models = [Event]
        self.db.bind(models)
Exemple #9
0
    def _init_db(self, db_path):
        from playhouse.sqlite_ext import SqliteExtDatabase

        if db_path is None:
            db_path = os.path.join(os.path.expanduser('~'), '.etesync', 'data.db')

        directory = os.path.dirname(db_path)
        if directory != '' and not os.path.exists(directory):
            os.makedirs(directory)

        database = SqliteExtDatabase(db_path, pragmas={'foreign_keys': 1})
        database.connect()

        self._set_db(database)
Exemple #10
0
    def setup(cls):
        """sets up the SQL System"""
        mode = CONFIG["database"]["mode"].value.lower()
        if mode == "sqlite3":
            database = SqliteExtDatabase(
                PROGRAMCONFIGLOCATION + "/Tackem.db",
                pragmas={
                    "journal_mode": "wal",
                    "foreign_keys": 0
                },
            )

        elif mode == "mysql":
            database = MySQLDatabase(
                CONFIG["database"]["database"].value,
                user=CONFIG["database"]["username"].value,
                password=CONFIG["database"]["password"].value,
                host=CONFIG["database"]["host"].value,
                port=CONFIG["database"]["port"].value,
            )
        else:
            print(mode)

        cls.__db.initialize(database)

        if mode == "sqlite3":
            cls.__migrator = SqliteMigrator(cls.__db)
        elif mode == "mysql":
            cls.__migrator = MySQLMigrator(cls.__db)
        TableVersion.create_table()
    def __init__(self, db_path):
        pragmas = [
            ('journal_mode', 'wal2'),
            ('cache_size', -1024*64)]
        
        self.db_path = os.path.join(db_path, DATASOURCE_NAME, f"{DATASOURCE_NAME}.db")        
        self.db_object = SqliteExtDatabase(self.db_path, pragmas=pragmas,  detect_types=sqlite3.PARSE_DECLTYPES)

        backups_table, status_table, stats_table, backup_list_table =  initialize(self.db_object)
        self.datasource_name = DATASOURCE_NAME
        self.config  = { 
            "tables": { 
                "stats_table": stats_table, 
                "status_table": status_table,
                "backup_table": backups_table,
                "backup_list_table": backup_list_table,
            },
            "utils":{
                "stats": stats,
                "status": status
            }
        }
        
        self.routes = {"GET": [ ("stats", stats), ("status", status), ("backup_list", backup_list),\
                    ("start_fresh_backup", start_fresh_backup),  ("generate_mnemonic", new_mnemonic)], 
                    "POST": [ ("store_mnemonic", store_mnemonic), ("check_mnemonic", check_mnemonic)]} 
        
        
Exemple #12
0
def init_db():
    driver = get_config('DATABASE', 'driver')
    host = get_config(driver, 'host')
    username = get_config(driver, 'username')
    password = get_config(driver, 'password')
    database = get_config(driver, 'database')
    port = int(get_config(driver, 'port'))

    if driver == 'POSTGRESQL':
        db = PostgresqlDatabase(database,
                                user=username,
                                host=host,
                                password=password)
    elif driver == 'SQLITE':
        from playhouse.sqlite_ext import SqliteExtDatabase
        db = SqliteExtDatabase('data/database.db')
    elif driver == 'MYSQL':
        db = MySQLDatabase(database,
                           user=username,
                           host=host,
                           password=password,
                           port=port)
    else:
        raise NotSupportedError
    return db
Exemple #13
0
    def __init__(self, key_field=None, value_field=None, ordered=False,
                 database=None, table_name='keyvalue'):
        if key_field is None:
            key_field = CharField(max_length=255, primary_key=True)
        if not key_field.primary_key:
            raise ValueError('key_field must have primary_key=True.')

        if value_field is None:
            value_field = PickleField()

        self._key_field = key_field
        self._value_field = value_field
        self._ordered = ordered
        self._database = database or SqliteExtDatabase(':memory:')
        self._table_name = table_name
        support_on_conflict = (isinstance(self._database, PostgresqlDatabase) or
                              (isinstance(self._database, SqliteDatabase) and
                               self._database.server_version >= (3, 24)))
        if support_on_conflict:
            self.upsert = self._postgres_upsert
            self.update = self._postgres_update
        else:
            self.upsert = self._upsert
            self.update = self._update

        self.model = self.create_model()
        self.key = self.model.key
        self.value = self.model.value

        # Ensure table exists.
        self.model.create_table()
 def __post_init__(self):
     self.path = os.path.join(self.directory, "plugins", self.plugin_name)
     self.pragmas = [('journal_mode', 'wal2'), ('cache_size', -1024 * 64)]
     self.db_object = SqliteExtDatabase(
         os.path.join(self.path, f"{self.plugin_name}.db"),
         pragmas=self.pragmas,
         detect_types=sqlite3.PARSE_DECLTYPES)
Exemple #15
0
class DatabaseHandler:
    """Class for managing database connection and loading given data into database"""
    # static field for storing database connection by peewee
    db = SqliteExtDatabase("database.db",
                           pragmas=(("cache_size", -1024 * 64),
                                    ("journal_mode", "wal"), ("foreign_keys",
                                                              1)))

    def __init__(self):
        """Calls method create_table for Person class"""
        self.create_table(Person)

    def create_table(self, table_class):
        """Create table from Person class in database"""
        table_class.create_table()

    def insert_data_into_person(self, data):
        """Call insert_data method with Person as parameter"""
        self.insert_data(data, Person)

    def insert_data(self, data, table_class):
        """
        Insert data into database in chunks using peewee functions
        :param table_class: Class which should store the given date in database
        :param data: List of persons to be stored in database
        """
        with self.db.atomic():
            for batch in chunked(data, 5):
                table_class.insert_many(batch).execute()
    def __init__(self, db_path):
        pragmas = [('journal_mode', 'wal2'), ('cache_size', -1024 * 64)]

        self.db_path = os.path.join(db_path, DATASOURCE_NAME,
                                    f"{DATASOURCE_NAME}.db")
        self.db_object = SqliteExtDatabase(
            self.db_path,
            pragmas=pragmas,
            detect_types=sqlite3.PARSE_DECLTYPES)

        creds_table = initialize(self.db_object)
        self.datasource_name = DATASOURCE_NAME
        self.config = {
            "tables": {
                "creds_table": creds_table,
            },
            "utils": {}
        }

        self.routes = {
            "GET": [("logout", user_logout), ("is_logged_in", is_logged_in)],
            "POST": [("login", login), ("signup", signup),
                     ("confirm_signup", confirm_signup),
                     ("forgot_password", forgot_password),
                     ("confirm_forgot_password", confirm_forgot_password),
                     ("change_password", change_password)]
        }
Exemple #17
0
    def __init__(self):

        self.settings = get_settings()
        self.isdebug = util.bc(self.settings[util.SETTINGS_KEYS[4]])
        inmemory = util.bc(self.settings[util.SETTINGS_KEYS[0]])
        if inmemory:
            val = ':memory:'
        else:
            val = (self.settings[util.SETTINGS_KEYS[1]])

        self.db = db
        if not self.db:
            hou.session.DBCONNECTION = DatabaseProxy()
            self.db.initialize(
                SqliteExtDatabase(val,
                                  pragmas=(("cache_size", -1024 * 64),
                                           ("journal_mode",
                                            "off"), ("temp_store", "memory"),
                                           ("synchronous", 0))))
            if inmemory or not os.path.isfile(
                    self.settings[util.SETTINGS_KEYS[1]]):
                db.create_tables([
                    Settings,
                    HContext,
                    Hotkeys,
                    HotkeysIndex,
                ])
                self.initialsetup(self.cur)

        self.cur = db.cursor()
        self.isdebug = None
        self.contexttime = 0
        self.hotkeystime = 0
Exemple #18
0
    def __init__(self,
                 key_field=None,
                 value_field=None,
                 ordered=False,
                 database=None,
                 table_name='keyvalue'):
        if key_field is None:
            key_field = CharField(max_length=255, primary_key=True)
        if not key_field.primary_key:
            raise ValueError('key_field must have primary_key=True.')

        if value_field is None:
            value_field = PickleField()

        self._key_field = key_field
        self._value_field = value_field
        self._ordered = ordered
        self._database = database or SqliteExtDatabase(':memory:')
        self._table_name = table_name
        self._has_upsert = not isinstance(self._database, PostgresqlDatabase)

        self.model = self.create_model()
        self.key = self.model.key
        self.value = self.model.value

        # Ensure table exists.
        self.model.create_table()
Exemple #19
0
def _recreate_db():
    src_dir = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(src_dir, '../data/main.db')
    if os.path.exists(db_path):
        os.remove(db_path)
    pragmas = [('journal_mode', 'wal'), ('cache_size', -1024 * 32)]

    return SqliteExtDatabase(db_path, pragmas=pragmas)
Exemple #20
0
def clean(db_loc):
    """
    Some fragments are duplicates, or are not included in the db, but there are still atom and pseudoatom records
    that refer to them. This is not ideal, so this script deletes these orphan records.
    :param db_loc:
    :return:
    """
    # create the database for the output
    db = SqliteExtDatabase(
        db_loc,
        pragmas={
            'cache_size': -1024 * 64,  # 64MB page-cache.
            'journal_mode':
            'wal',  # Use WAL-mode (you should always use this!).
            'foreign_keys': 0,
            'wal_autocheckpoint': 10,
        })
    # get the models
    Fragment, Heritage, PseudoAtoms, Atoms = lib_read(db)

    Fragment.create_table(safe=True)
    Heritage.create_table(safe=True)
    PseudoAtoms.create_table(safe=True)
    Atoms.create_table(safe=True)

    logger.debug("Trying to clean up the database:")
    logger.debug("Deleting missing ATOM records")
    with db.atomic():
        bad_atoms = Atoms.delete().where(
            (Atoms.frag.not_in(Fragment.select())))
        bad_atoms.execute()

    logger.debug("Deleting missing PSEUDO_ATOM records")
    with db.atomic():
        bad_patoms = PseudoAtoms.delete().where(
            (PseudoAtoms.frag.not_in(Fragment.select())))
        bad_patoms.execute()

    logger.debug("Deleting missing HERITAGE records")
    with db.atomic():
        bad_heritage = Heritage.delete().where(
            (Heritage.frag.not_in(Fragment.select())))
        bad_heritage.execute()

    logger.info("Done.")
Exemple #21
0
 def connection(self):
     if self._connection is None:
         self._connection = SqliteExtDatabase(
             self._path,
             pragmas=(
                 ('cache_size', -1024 * 64),  # 64MB page-cache.
                 ('journal_mode', 'wal'),  # Use WAL-mode (Write Ahead Log).
             ))
     return self._connection
Exemple #22
0
    def import_song_statistic_from(self, database_file):
        self.logger.info('Importing database songs statistics')
        try:
            from playhouse.sqlite_ext import SqliteExtDatabase
            other_database = SqliteExtDatabase(database_file)
            cursor = other_database.execute_sql(
                "SELECT ADDED, LAST_PLAYED, PLAYED, TITLE, ARTIST, ALBUM FROM SONG"
            )
            with database_context.atomic():
                for row in cursor.fetchall():
                    database_context.execute_sql(
                        "UPDATE SONG SET ADDED = ?, LAST_PLAYED = ?, PLAYED = ? WHERE TITLE = ? AND ARTIST = ? AND ALBUM = ?",
                        row)

            other_database.close()
        except:
            self.logger.exception(
                'Error while importing database songs statistics')
Exemple #23
0
def _open_db(path: PathOrStr):
    db.initialize(
        SqliteExtDatabase(str(path),
                          pragmas={
                              'synchronous': 0,
                              'cache_size': -1024 * 64,
                          }))
    tables = [Relation, Language, Label, Concept, Edge]
    db.create_tables(tables)
Exemple #24
0
def connect(path, spatialite_path, evn_sep=';'):
    """
    データベースへの接続
    @param path sqliteのパス
    @param spatialite_path mod_spatialiteへのパス
    @param env_sep 環境変数PATHの接続文字 WINDOWSは; LINUXは:
    """
    os.environ["PATH"] = os.environ["PATH"] + evn_sep + os.path.dirname(
        spatialite_path)
    db = SqliteExtDatabase(path)
    database_proxy.initialize(db)
    db.field_overrides = {
        'polygon': 'POLYGON',
        'point': 'POINT',
        'linestring': 'LINESTRING',
        'multipolygon': 'MULTIPOLYGON',
        'multipoint': 'MULTIPOINT',
        'multilinestring': 'MULTILINESTRING',
    }
    db.load_extension(os.path.basename(spatialite_path))
Exemple #25
0
def get_database(storage_path):
    db = SqliteExtDatabase(
        storage_path,
        pragmas=(
            ('cache_size', -1024 * 16),  # 16MB page-cache
            ('journal_mode', 'wal'),
            ('foreign_keys', 1),
        ),
        regexp_function=True,
    )
    return db
Exemple #26
0
    def __init__(self, database=None):
        if database is None:
            database = SqliteExtDatabase(':memory:')

        if HAVE_C_EXTENSION:
            register_json_contains(database)
        else:
            database.register_function(_json_contains, 'json_contains')

        self.database = database
        self.V, self.E = self.create_models()
Exemple #27
0
def get_db():
    path = get_path_db()
    if path is None:
        print(
            "\n Error - Cannot fetch database because it has not yet been configured.\n"
        )
    else:
        # peewee ORM connection to database:
        #db = SqliteDatabase(path)
        db = SqliteExtDatabase(path)
        return db
Exemple #28
0
	def __init__(self, database):
		"""Create a Database object.

		:param database: database file name
		:type database: str
		:returns:  Database

		"""

		self.database = SqliteExtDatabase('%s.db' % database)
		self.models = models
Exemple #29
0
    def init_database(self):
        # Migrate DB location
        old_db_path = os.path.join(CLIPS_DIR, "frigate.db")
        if not os.path.isfile(
                self.config.database.path) and os.path.isfile(old_db_path):
            os.rename(old_db_path, self.config.database.path)

        # Migrate DB schema
        migrate_db = SqliteExtDatabase(self.config.database.path)

        # Run migrations
        del logging.getLogger("peewee_migrate").handlers[:]
        router = Router(migrate_db)
        router.run()

        migrate_db.close()

        self.db = SqliteQueueDatabase(self.config.database.path)
        models = [Event, Recordings]
        self.db.bind(models)
Exemple #30
0
def dbInit():
    if 'CLEARDB_DATABASE_URL' in os.environ:
        PROD = True
        url = urlparse.urlparse(os.environ['CLEARDB_DATABASE_URL'])
        db = peewee.MySQLDatabase(url.path[1:],
                                  host=url.hostname,
                                  user=url.username,
                                  passwd=url.password)
    else:
        db = SqliteExtDatabase('weather.db')

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

    class CityGraph(BaseModel):
        image_url = CharField()
        city = CharField()
        title = CharField()
        date = DateField()

        class Meta:
            primary_key = CompositeKey('city', 'date')

    db.connect()
    db.create_tables([CityGraph], safe=True)

    return CityGraph
Exemple #31
0
def makedb(dbfile):
    db = SqliteExtDatabase(dbfile)
    db.connect()

    global BaseModel

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

    global UniqueString

    class UniqueString(BaseModel):
        raw = CharField(index=True)
        count = IntegerField()
        malware_count = IntegerField()
        p_malware = FloatField(index=True)

    global Entity

    class Entity(BaseModel):
        name = CharField(index=True)
        label = FloatField()

    global String

    class String(BaseModel):
        uniquestring = ForeignKeyField(UniqueString, index=True)
        entity = ForeignKeyField(Entity, index=True)
        source = CharField(index=True, null=True)

    # create database
    db.create_tables([Entity, String, UniqueString])

    return db
Exemple #32
0
    def _init_db(self, db_path):
        from playhouse.sqlite_ext import SqliteExtDatabase

        directory = os.path.dirname(db_path)
        if directory != '' and not os.path.exists(directory):
            os.makedirs(directory)

        database = SqliteExtDatabase(db_path, pragmas={
            'journal_mode': 'wal',
            'foreign_keys': 1,
            })

        self._set_db(database)
Exemple #33
0
def setup(path: str):
    db = SqliteExtDatabase(path)

    # Ensure foreign key and constraints are enforced.
    db.pragma('foreign_keys', 1, permanent=True)
    db.pragma('ignore_check_constraints', 0, permanent=True)

    # Bind to database.
    _proxy.initialize(db)
Exemple #34
0
    def __init__(self, db_path):
        pragmas = [('journal_mode', 'wal2'), ('cache_size', -1024 * 64)]

        self.db_path = os.path.join(db_path, DATASOURCE_NAME,
                                    f"{DATASOURCE_NAME}.db")
        self.db_object = SqliteExtDatabase(
            self.db_path,
            pragmas=pragmas,
            detect_types=sqlite3.PARSE_DECLTYPES)


        creds_table, status_table, stats_table, email_table,\
             email_attachment_table, email_content_table,\
             image_table, purchase_table, reservation_table, \
                 archives_table, location_table, location_approximate_table = initialize(self.db_object)
        self.datasource_name = DATASOURCE_NAME

        self.config = {
            "tables": {
                "creds_table": creds_table,
                "image_table": image_table,
                "email_table": email_table,
                "email_attachment_table": email_attachment_table,
                "email_content_table": email_content_table,
                "purchase_table": purchase_table,
                "archives_table": archives_table,
                "reservation_table": reservation_table,
                "location_table": location_table,
                "location_approximate_table": location_approximate_table,
                "stats_table": stats_table,
                "status_table": status_table
            },
            "utils": {
                "stats": stats,
                "status": status
            }
        }

        self.routes = {
            "GET": [("emails/filter", emails_filter),
                    ("images/filter", image_filter),
                    ("locations/filter", locations_filter),
                    ("delete_zip", delete_original_path),
                    ("purchases/filter", purchases_filter),
                    ("reservations/filter", reservations_filter),
                    ("attachments/filter", attachment_filter)],
            "POST": [("parse", parse), ("cancel_parse", cancel_parse),
                     ("restart_parse", restart_parse)]
        }
Exemple #35
0
    def test_get_relations(self):
        test_db = 'test.db'
        if isfile(test_db):
            remove(test_db)

        db = SqliteExtDatabase(test_db)
        db.connect()

        Subreddit, Relationship = obtain_models(db)

        s_a = Subreddit.create(name='subreddit A',
                               subs=666,
                               over18=True,
                               iconURL='https://domain/pic.jpg')
        s_b = Subreddit.create(name='subreddit B',
                               subs=777,
                               over18=False,
                               iconURL='https://domain/pic2.jpg')

        Relationship.create(a=s_a, b=s_b)

        relations_a = s_a.find_relations()

        self.assertIn(s_b, relations_a)
Exemple #36
0
#!/usr/bin/env python2

from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
import datetime
import os

db = SqliteExtDatabase(os.path.dirname(os.path.realpath(__file__))+'/corpus.db')
db.connect()

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


class Tweet(BaseModel):
    id = BigIntegerField(unique=True)
    mentioning = CharField()
    screen_name = CharField()
    text = TextField()
    created_at = DateTimeField(null=True)
    ingested_at = DateTimeField(default=datetime.datetime.now)
    classification = CharField(null=True)


#db.create_tables([Tweet])
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
import datetime
import sys, os

db = SqliteExtDatabase('my_database.db')

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

class User(BaseModel):
	username = CharField(unique=True)
	ip = CharField()

class Channel(BaseModel):
	name = CharField(unique=True)
	num = IntegerField(default=0)

class ChannelPublisher(BaseModel):
	ch_id = ForeignKeyField(Channel, related_name='channel_pub')
	pub_id = ForeignKeyField(User, related_name='publisher')

class ChannelSubscriber(BaseModel):
	ch_id = ForeignKeyField(Channel, related_name='channel_sub')
	sub_id = ForeignKeyField(User, related_name='subscriber')
	ts = IntegerField()

class Feed(BaseModel):
	ch_id = ForeignKeyField(Channel, related_name='channel_feed')
	pub_id = ForeignKeyField(User, related_name='publisher_feed')
Exemple #38
0
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
import datetime

db = SqliteExtDatabase("db.sqlite3")


class BaseModel(Model):

    class Meta:
        database = db


class User(BaseModel):
    username = CharField(unique=True, null=False)
    created_at = DateTimeField(default=datetime.datetime.now)

    class Meta:
        db_table = "users"


class Channel(BaseModel):
    channel = CharField(unique=True, null=False)
    twitch_auth = CharField(default="")
    twitchalerts_auth = CharField(default="")
    streamtip_auth = CharField(default="")
    created_at = DateTimeField(default=datetime.datetime.now)

    class Meta:
        db_table = "channels"
Exemple #39
0
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase

db = SqliteExtDatabase('store/virus_manager.db',
    threadlocals=True)

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


class ManagedMachine(BaseModel):
    image_name = TextField(unique=True)
    reference_image = TextField()
    creation_time = IntegerField()


class Infection(BaseModel):
    name = TextField()
    machine = ForeignKeyField(ManagedMachine,
        related_name='infections')

db.create_tables([ManagedMachine, Infection], True)
Exemple #40
0
from __future__ import print_function

import os

import cv2
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import Button
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
import datetime

#create db connector
os.remove('my_database.db')
db = SqliteExtDatabase('my_database.db')

#base model class to extend it
class BaseModel(Model):
    class Meta:
        database = db


#point at all rows at once
class MultiDimensionalPoint(BaseModel):
    first_pos_x = FloatField()
    first_pos_y = FloatField()
    second_pos_x = FloatField()
    second_pos_y = FloatField()
    third_pos_x = FloatField()
    third_pos_y = FloatField()
Exemple #41
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
from collections import Counter
import NLP, utiltools
import TFIDF
import re
import random
import requests
import numpy as np
import dealSQL
DBPLACE = '/Users/masaMikam/Dropbox/Project/umiA/Data/LANGUAGEsid.sqlite3'
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
database = SqliteExtDatabase(DBPLACE, autocommit=False, journal_mode='persist')
database.connect()
class BaseModel(Model):
    class Meta:
        database = database

class trigram(BaseModel):
    W1 = CharField(null=True)
    W2 = CharField(null=True)
    W3  = CharField(null=True)
    P1  = CharField(null=True)
    P2 = CharField(null=True)
    P3 = CharField(null=True)
    cnt = IntegerField(null=True)
    ok = IntegerField(null=True)
    ng = IntegerField(null=True)
    class Meta:
Exemple #42
0
# -*- coding: utf-8 -*-

from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
import datetime
from pplib.base_model import BaseM

db = SqliteExtDatabase('../data/tatoeba/tatoeba.db')


time_format = '%Y-%m-%d %H:%M:%S'


class BaseModel(Model, BaseM):
    class Meta:
        database = db


class User(BaseModel):
    username = CharField(unique=True)


class Sentence(BaseModel):

    user = CharField(null=True)  # username

    num = IntegerField(primary_key=True)
    lang = FixedCharField(8)
    text = CharField()

    create_time = DateTimeField(default=datetime.datetime.now, null=True)
#!/usr/bin/python
# encoding: utf-8
import sys
from workflow import Workflow
from peewee import *
from glob import iglob
import json
import os
from playhouse.sqlite_ext import SqliteExtDatabase, SearchField, FTSModel
import datetime
wf = Workflow()
libpath = wf.stored_data('library_location')

db = SqliteExtDatabase("quiver.db")
if os.path.exists("quiver.db"):
    os.remove("quiver.db")

# Create the database

class Note(Model):
    uuid = CharField()
    title = CharField(index = True)
    notebook = CharField(index = True)
    last_modified = DateTimeField()

    class Meta:
        database = db


class NoteIndex(FTSModel):
    uuid = CharField()
Exemple #44
0
import tornado.ioloop
from tornado.options import options
from playhouse.sqlite_ext import SqliteExtDatabase, ClosureTable
from peewee import (Model, CharField, ForeignKeyField, IntegerField,
                    BooleanField, DateTimeField, DoesNotExist, OperationalError)

import fs

log = logging.getLogger("tornado.general")

"""
connect to db
load closure module
create tables
"""
db = SqliteExtDatabase(options.db_file)
db.load_extension(options.sqlite_closure_table_so)


class File(Model):
    path = CharField()
    bytes = IntegerField()
    is_dir = BooleanField()
    modified = DateTimeField()
    size = CharField()  # redundant
    parent = ForeignKeyField('self', null=True, related_name='children')

    class Meta:
        database = db

Exemple #45
0
# -*- coding: utf-8 -*-

from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
from pplib.base_model import BaseM


db = SqliteExtDatabase('../data/jdict_v1.db')


time_format = '%Y-%m-%d %H:%M:%S'


class BaseModel(Model, BaseM):
    class Meta:
        database = db

    def dict__property(self, k):
        d = self.__dict__['_data']
        return d[k] if k in d else None


class Word(BaseModel):
    text = CharField(primary_key=True)
    kana = CharField()
    romaji = CharField(null=True)
    audio = CharField(null=True)

    translation_key = CharField()  # first alternatives or text

    tags = CharField(null=True)  # ','.join([tag1, tag2])
# -*- coding: utf-8 -*-
import sys
from datetime import datetime

from peewee import CharField, DateTimeField, Model, TextField
from playhouse.sqlite_ext import SqliteExtDatabase

db = SqliteExtDatabase('db/rss_atom_mattermost.db')
db.connect()

try:
    import html2text
except ImportError as exc:
    print('Error: failed to import module. ({}). \nInstall missing modules'
          ' using "sudo pip install -r requirements.txt"'.format(exc))
    sys.exit(1)


class RssFeed(object):
    def __init__(self, name, url, iconurl, user, channel, showname, showtitle,
                 showdescription, showurl):
        self.Name = name
        self.Url = url
        self.Iconurl = iconurl
        self.User = user
        self.Channel = channel
        self.ShowName = showname
        self.ShowTitle = showtitle
        self.ShowDescription = showdescription
        self.ShowUrl = showurl
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
import datetime


from data_models import User
from data_models import ActionType
from data_models import EncsPPC_Action

from settings_provider import SettingsProvider
from pprint import pprint

settings_provider = SettingsProvider('settings.json')
database_path = settings_provider.database_path()

db = SqliteExtDatabase(database_path)
db.connect()

db.create_tables([User, ActionType, EncsPPC_Action])

action_type_list = ['in', 'out']
for action_type_value in action_type_list:
    action_type = ActionType()
    action_type.description = action_type_value
    action_type.save()
Exemple #48
0
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
import datetime
import time
custom_db = SqliteExtDatabase('blah.db')
class BaseModel(Model):
    class Meta:
        database = custom_db


class User(BaseModel):
    name = CharField(unique=True)
    time = IntegerField()

custom_db.connect()
# custom_db.create_tables([User])

# db.connect()
try:
    charlie = User.create(name='charlie', time=0)
    charlie.save()
except:
    print "user creation error"
# User.create(name='benard').save()

try:
    print User.get(User.name == 'sally')
except DoesNotExist:
    print "Does not exist"

user = User.get(User.name == 'charlie')