Exemple #1
0
    def test_db_url(self):
        db = connect('sqlite:///:memory:')
        self.assertTrue(isinstance(db, SqliteDatabase))
        self.assertEqual(db.database, ':memory:')

        db = connect('sqliteext:///foo/bar.db')
        self.assertTrue(isinstance(db, SqliteExtDatabase))
        self.assertEqual(db.database, 'foo/bar.db')

        db = connect('sqlite:////this/is/absolute.path')
        self.assertEqual(db.database, '/this/is/absolute.path')

        db = connect('sqlite://')
        self.assertTrue(isinstance(db, SqliteDatabase))
        self.assertEqual(db.database, ':memory:')
Exemple #2
0
def get_router(directory, database, verbose=0):
    from peewee_migrate import LOGGER
    from peewee_migrate.compat import exec_in
    from peewee_migrate.router import Router

    logging_level = VERBOSE[verbose]
    config = {}
    try:
        with open(os.path.join(directory, 'conf.py')) as cfg:
            exec_in(cfg.read(), config, config)
            database = config.get('DATABASE', database)
            logging_level = config.get('LOGGING_LEVEL', logging_level).upper()
    except IOError:
        pass

    if isinstance(database, string_types):
        database = connect(database)

    LOGGER.setLevel(logging_level)

    try:
        return Router(database, migrate_dir=directory)
    except RuntimeError as exc:
        LOGGER.error(exc)
        return sys.exit(1)
Exemple #3
0
    def __init__(self, url, bare_fields=False):
        if isinstance(url, Database):
            self._url = None
            self._database = url
            self._database_path = self._database.database
        else:
            self._url = url
            parse_result = urlparse(url)
            self._database_path = parse_result.path[1:]

            # Connect to the database.
            self._database = connect(url)

        self._database.connect()

        # Introspect the database and generate models.
        self._introspector = Introspector.from_database(self._database)
        self._models = self._introspector.generate_models(
            skip_invalid=True,
            literal_column_names=True,
            bare_fields=bare_fields)
        self._migrator = SchemaMigrator.from_database(self._database)

        class BaseModel(Model):
            class Meta:
                database = self._database
        self._base_model = BaseModel
        self._export_formats = self.get_export_formats()
        self._import_formats = self.get_import_formats()
 def load(self, url):
     """New database session"""
     try:
         base = db_url.connect(url)
         self.initialize(base)
     except RuntimeError:
         UI.display('Failed loading database at {}'.format(url))
Exemple #5
0
    def __init__(self, migrate_dir, **options):

        LOGGER.setLevel(options.get('LOGGING', 'WARNING'))

        if not op.exists(migrate_dir):
            LOGGER.warn('Migration directory: %s does not exists.', migrate_dir)
            md(migrate_dir)

        config = {}
        if op.exists(op.join(migrate_dir, 'conf.py')):
            with open(op.join(migrate_dir, 'conf.py')) as f:
                exec_in(f.read(), config, config)
            for key in config:
                if not key.startswith('_'):
                    options[key] = config[key]
        else:
            LOGGER.warn('Configuration file `conf.py` didnt found in migration directory')

        self.migrate_dir = migrate_dir

        self.db = options.get('DATABASE')
        if not isinstance(
                self.db, (SqliteDatabase, MySQLDatabase, PostgresqlDatabase)) and self.db:
            self.db = connect(self.db)

        try:
            assert self.db
            self.proxy.initialize(self.db)
            assert self.proxy.database
        except (AttributeError, AssertionError):
            LOGGER.error("Invalid database: %s", self.db)
            sys.exit(1)
        except Exception:
            pass
        self.db.create_tables([MigrateHistory], safe=True)
    def setup(self, app):
        """ Initialize the application. """

        app.config.setdefault('PEEWEE_CONNECTION', self.connection)
        self.connection = app.config.get('PEEWEE_CONNECTION')
        self.database = connect(self.connection)
        self.proxy.initialize(self.database)
Exemple #7
0
 def run(self):
     log.debug('Starting daemon: {0}'.format(
         dict(host=self.host,
              server=self.server,
              interval=self.interval,
              dburl=self.dburl)))
     st = SpeedTest(host=self.server)
     while(True):
         log.debug('Starting speed test')
         startTime = utils.current_time_millisec()
         stats = dict(server=st.host,
                      ping=st.ping(),
                      download=st.download(),
                      upload=st.upload())
         endTime = utils.current_time_millisec()
         log.debug('Speed test completed: {0}'.format(stats))
         db.initialize(connect(self.dburl))
         db.create_tables([SpeedtestModel], safe=True)
         SpeedtestModel.create(host=self.host,
                               startTime=startTime,
                               endTime=endTime,
                               **stats)
         db.close()
         log.debug('Database updated')
         log.debug('Going to sleep for {:d} seconds'.format(self.interval))
         time.sleep(self.interval)
Exemple #8
0
def get_router(directory, database, verbose=0):
    from peewee_migrate import LOGGER
    from peewee_migrate.compat import exec_in
    from peewee_migrate.router import Router

    logging_level = VERBOSE[verbose]
    config = {}
    migrate_table = 'migratehistory'
    ignore = schema = None
    try:
        with open(os.path.join(directory, 'conf.py')) as cfg:
            exec_in(cfg.read(), config, config)
            database = config.get('DATABASE', database)
            ignore = config.get('IGNORE', ignore)
            schema = config.get('SCHEMA', schema)
            migrate_table = config.get('MIGRATE_TABLE', migrate_table)
            logging_level = config.get('LOGGING_LEVEL', logging_level).upper()
    except IOError:
        pass

    if isinstance(database, string_types):
        database = connect(database)

    LOGGER.setLevel(logging_level)

    try:
        return Router(database, migrate_table=migrate_table, migrate_dir=directory,
                      ignore=ignore, schema=schema)
    except RuntimeError as exc:
        LOGGER.error(exc)
        return sys.exit(1)
Exemple #9
0
def db():
    from playhouse.db_url import connect

    database = connect('sqlite:///:memory:')
    yield database
    if not database.is_closed():
        database.close()
Exemple #10
0
def test_migrator_postgres():
    """
    Ensure change_fields generates queries and
    does not cause exception
    """
    import peewee as pw
    from playhouse.db_url import connect
    from peewee_migrate import Migrator

    # Monkey patch psycopg2 connect
    import psycopg2
    from .mocks import postgres
    psycopg2.connect = postgres.MockConnection

    database = connect('postgres:///fake')

    migrator = Migrator(database)
    @migrator.create_table
    class User(pw.Model):
        name = pw.CharField()
        created_at = pw.DateField()

    assert User == migrator.orm['user']

    # Date -> DateTime
    migrator.change_fields('user', created_at=pw.DateTimeField())
    migrator.run()
    assert 'ALTER TABLE "user" ALTER COLUMN "created_at" TYPE TIMESTAMP' in database.cursor().queries
    
    # Char -> Text
    migrator.change_fields('user', name=pw.TextField())
    migrator.run()
    assert 'ALTER TABLE "user" ALTER COLUMN "name" TYPE TEXT' in database.cursor().queries
Exemple #11
0
def init_db(database_url):
    """
        This function initializes the global database with the given url.
    """
    # utility function to parse database urls
    from playhouse.db_url import connect
    # initialize the peewee database with the appropriate engine
    db.initialize(connect(database_url))
def test_migrator():
    import peewee as pw
    from playhouse.db_url import connect
    from peewee_migrate import Migrator

    database = connect('sqlite:///:memory:')
    migrator = Migrator(database)

    @migrator.create_table
    class Customer(pw.Model):
        name = pw.CharField()

    assert Customer == migrator.orm['customer']

    @migrator.create_table
    class Order(pw.Model):
        number = pw.CharField()
        uid = pw.CharField(unique=True)

        customer = pw.ForeignKeyField(Customer)

    assert Order == migrator.orm['order']
    migrator.run()

    migrator.add_columns(Order, finished=pw.BooleanField(default=False))
    assert 'finished' in Order._meta.fields
    migrator.run()

    migrator.drop_columns('order', 'finished', 'customer', 'uid')
    assert 'finished' not in Order._meta.fields
    migrator.run()

    migrator.add_columns(Order, customer=pw.ForeignKeyField(Customer, null=True))
    assert 'customer' in Order._meta.fields
    migrator.run()

    migrator.rename_column(Order, 'number', 'identifier')
    assert 'identifier' in Order._meta.fields
    migrator.run()

    migrator.drop_not_null(Order, 'identifier')
    assert Order._meta.fields['identifier'].null
    assert Order._meta.columns['identifier'].null
    migrator.run()

    migrator.add_default(Order, 'identifier', 11)
    assert Order._meta.fields['identifier'].default == 11
    migrator.run()

    migrator.change_columns(Order, identifier=pw.IntegerField(default=0))
    assert Order.identifier.db_field == 'int'
    migrator.run()

    Order.create(identifier=55)
    migrator.sql('UPDATE "order" SET identifier = 77;')
    migrator.run()
    order = Order.get()
    assert order.identifier == 77
Exemple #13
0
    def test_db_url(self):
        db = connect('sqlite:///:memory:')
        self.assertTrue(isinstance(db, SqliteDatabase))
        self.assertEqual(db.database, ':memory:')

        db = connect('sqlite:///:memory:', journal_mode='MEMORY')
        self.assertTrue(('journal_mode', 'MEMORY') in db._pragmas)

        db = connect('sqliteext:///foo/bar.db')
        self.assertTrue(isinstance(db, SqliteExtDatabase))
        self.assertEqual(db.database, 'foo/bar.db')

        db = connect('sqlite:////this/is/absolute.path')
        self.assertEqual(db.database, '/this/is/absolute.path')

        db = connect('sqlite://')
        self.assertTrue(isinstance(db, SqliteDatabase))
        self.assertEqual(db.database, ':memory:')
Exemple #14
0
def cli(ctx):
    cmd = ctx.invoked_subcommand

    if cmd in ('songfinish', 'server'):
        config = get_config()
        ctx.obj = config['server'] if cmd == 'server' else config['client']

        if 'database' in ctx.obj:
            database = connect(ctx.obj['database'])
            create_database(database)
Exemple #15
0
    def __init__(self, token, plugins=[], no_command=None, db_url=None):
        self._token = token
        self.tg = TelegramBot(token)
        self._last_id = None
        self.cmds = {}
        self.pcmds = {}
        self._no_cmd = no_command
        self._msgs = {}
        self._plugins = plugins

        if no_command is not None:
            if not isinstance(no_command, TGPluginBase):
                raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(no_command).__name__)

        for p in self._plugins:

            if not isinstance(p, TGPluginBase):
                raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(p).__name__)

            for cmd in p.list_commands():

                if not isinstance(cmd, TGCommandBase):
                    raise NotImplementedError("%s does not subclass tgbot.TGCommandBase" % type(cmd).__name__)

                if cmd in self.cmds or cmd in self.pcmds:
                    raise Exception(
                        "Duplicate command %s: both in %s and %s"
                        % (cmd.command, type(p).__name__, self.cmds.get(cmd.command) or self.pcmds.get(cmd.command))
                    )

                if cmd.prefix:
                    self.pcmds[cmd.command] = cmd
                else:
                    self.cmds[cmd.command] = cmd

        if db_url is None:
            self.db = connect("sqlite:///:memory:")
            models.database_proxy.initialize(self.db)
            self.setup_db()
        else:
            self.db = connect(db_url)
            self.db.autorollback = True
            models.database_proxy.initialize(self.db)
Exemple #16
0
def init_proxy(dbURL):
    '''Instantiate proxy to the database

    :param dbURL: the url describing connection parameters
        to the choosen database. The url must have format explained in the `Peewee url documentation
        <http://peewee.readthedocs.org/en/latest/peewee/playhouse.html#db-url>`_.

        examples:
         * sqlite: ``sqlite:///my_database.db``
         * postgres: ``postgresql://postgres:my_password@localhost:5432/my_database``
         * mysql: ``mysql://user:passwd@ip:port/my_db``
    '''
    db_proxy.initialize(db_url.connect(dbURL))
    return db_proxy
Exemple #17
0
def init_database(url: str=None):
    """
    Initializes database connection.
    See https://peewee.readthedocs.org/en/latest/peewee/database.html?highlight=url#connecting-using-a-database-url
    for info on URL format.

    Url defaults to 'sqlite:///hatbot.sqlite'.

    Please note that psycopg2 package has to be installed if we want to use PostgreSQL engine.

    :param url: str describing type and parameters of connection
    """
    global database, database_url
    assert database_url is None, 'database should be initialized exactly once'

    from playhouse import db_url
    database.initialize(db_url.connect(url or 'sqlite:///hatbot.sqlite'))
    database.connect()
    database_url = url
def database(request):
    """
    A fixture for setting up and tearing down SQLite, MySQL, and PostgreSQL
    databases using ``playhouse.db_url.connect``.

    TODO:
        Figure out how to teardown MySQL and PostgreSQL databases.

    Note:
        ``playhouse.db_url.connect`` requires four forward slashes in the SQLite
        URI for some reason.
    """
    database = connect(request.param)

    yield database

    if 'sqlite' in request.param:
        parsed_uri = urlparse(request.param)
        os.remove(parsed_uri.path)
Exemple #19
0
    def __init__(self, url):
        self._url = url
        parse_result = urlparse(url)
        self._database_path = parse_result.path[1:]

        # Connect to the database.
        self._database = connect(url)
        self._database.connect()

        # Introspect the database and generate models.
        self._introspector = Introspector.from_database(self._database)
        self._models = self._introspector.generate_models()
        self._migrator = SchemaMigrator.from_database(self._database)

        class BaseModel(Model):
            class Meta:
                database = self._database
        self._base_model = BaseModel
        self._export_formats = self.get_export_formats()
def manage(api, db_url, **connect_params):
    exclude = connect_params.pop('exclude', None)
    engine_instance = connect(db_url, **connect_params)

    hug_api = hug.API(api)

    @hug.request_middleware(api=hug_api)
    def process_data(request, response):
        if exclude is None or not exclude(request, 'request'):
            engine_instance.connect()

    @hug.response_middleware(api=hug_api)
    def process_data(request, response, resource):
        if exclude is None or not exclude(request, 'response'):
            engine_instance.close()

    class DatabaseModel(Model):
        class Meta:
            database = engine_instance

    engine_instance.Model = DatabaseModel

    return engine_instance
import config
from peewee import Model
from playhouse.db_url import connect
from playhouse.pool import PooledMySQLDatabase
db_mysql = connect(config.BACKEND_MYSQL)

# PooledMySQLDatabase
#db = PooledMySQLDatabase(
#    'seebugticket',
#    max_connections=32,
#    stale_timeout=300,  # 5 minutes.
#    user='******',
#    password='******'
#)
class BaseModel(Model):
    class Meta:
        database = db_mysql
Exemple #22
0
# coding:utf-8

import peewee
from playhouse.db_url import connect

DATABASE_URL = "sqlite:///database"
db = connect(DATABASE_URL)


class BaseModel(peewee.Model):
    class Meta:
        database = db
Exemple #23
0
def DATABASE_INIT(db_uri=None):
    if db_uri is None:
        db_uri = CFG.get('config:toybox:DATABASE_URI')
    return connect(db_uri)
#!/usr/bin/env python

import os

from peewee import *
from playhouse import db_url

db = db_url.connect(os.environ.get('DATABASE_URL', 'sqlite:///tparkinson.db'))

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


class Properties(BaseModel):
    park_name = CharField(null=True)
    park_address = CharField(null=True)
    park_county = CharField(null=True)
    geo_location = CharField(null=True)
    park_info = CharField(null=True)
    total_lots = DecimalField(null=True)
    water = CharField(null=True)
    waste = CharField(null=True)
    owning_entity = CharField(null=True)
    owner_info = CharField(null=True)
    other_contact_info = CharField(null=True)
    city = CharField(null=True)
    state = CharField(null=True)
    zipcode = CharField(null=True)
    msa = CharField(null=True)
Exemple #25
0
from peewee import *
from playhouse.db_url import connect

from config import data

# mysql_db = MySQLDatabase('library', user='******', passwd='pass') Local

mysql_db = connect("mysql://{user}:{passwd}@{host}:3306/{db}".format(**data))

class BaseModel(Model):

	class Meta:
		database = mysql_db

class Book(BaseModel):

    author = CharField()
    title = TextField()

if __name__ == '__main__':

	Book.create_table()
Exemple #26
0
#!/usr/bin/env python

# importy zewnetrzne
import peewee
from playhouse.db_url import connect


db = connect('mysql://*****:*****@db4free.net:3306/hakier_baza')

class BazaModel(peewee.Model) :
    class Meta :
        database = db
Exemple #27
0
 def _test_scheme():
     connect('missing:///')
Exemple #28
0
from peewee import *
from playhouse.db_url import connect

db = connect("mysql://*****:*****@localhost:3306/studybuddy")


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


class Uploader(BaseModel):
    username = CharField(null=False, default="unknown")
    email = CharField(null=False, unique=True)
    password = CharField(null=False)


class University(BaseModel):
    name = CharField(default="unknown")


class Course(BaseModel):
    name = CharField(default="unknown")
    subject = CharField(default="unknown")
    school = ForeignKeyField(University)


class Rating(BaseModel):
    relevant_yes = IntegerField(default=1)
    useful_yes = IntegerField(default=1)
    total_useful_votes = IntegerField(default=1)
  -s                     store in database
  --database-url=DB_URL  the database url to connect to (mysql://user:passwd@ip:port/my_db)
"""

from datetime import datetime
from docopt import docopt
from RPi import GPIO
from peewee import *
from playhouse.db_url import connect

arguments = docopt(__doc__)
verbose = arguments['-v']
storeToDB = arguments['-s']
databaseUrl = arguments['--database-url'] or 'sqlite:///default.db'

database = connect(databaseUrl)

inputNumbers = [4, 7, 8, 9, 10, 11, 14, 15, 17, 18, 22]

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

class Data(BaseModel):
    type = CharField()
    value = IntegerField()
    created_at = DateTimeField()

def setup_gpio():

    GPIO.setwarnings(False)
Exemple #30
0
from datetime import datetime
from livefeed import config
import peewee
from playhouse.db_url import connect

db = connect(config.DATABASE_URL)

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

class Feed(BaseModel):
    feed_id = peewee.PrimaryKeyField()
    uri = peewee.TextField(unique=True, null=False)
    title = peewee.TextField(unique=True, null=True)
    active = peewee.BooleanField(null=False, default=False)

class Item(BaseModel):
    feed = peewee.ForeignKeyField(Feed, related_name='items',
            on_delete='CASCADE')
    link = peewee.TextField(null=False, unique=True)
    title = peewee.TextField(null=False);
    published = peewee.DateTimeField(formats='%Y-%m-%d %H:%M:%S',
            default=datetime.now)
    body = peewee.TextField(null=True)
Exemple #31
0
def connect_database():
  return connect(os.environ.get('DATABASE_URL') or f'sqlite:///db/{environment}.sqlite')
Exemple #32
0
 def __init__(self, **options):
     """Initialize the plugin."""
     self.config = dict(self.defaults, **options)
     self.models = {}
     self.database = db_url.connect(self.config['url'],
                                    **self.config['connection_params'])
Exemple #33
0
from flask.ext.seasurf import SeaSurf
from peewee import SqliteDatabase
from playhouse.db_url import connect

app = Flask(__name__, static_folder='../static', template_folder='../templates')
csrf = SeaSurf(app)

import config
from models import proxy
app.config.from_object(config.Parameters)

if app.debug is True:
  db = SqliteDatabase(app.config['DB_DEBUG_LOCATION'])
  proxy.initialize(db)
else:
  db = connect(app.config['DB_PROD_LOCATION'])
  proxy.initialize(db)

@app.before_request
def open_database():
  proxy.connect()

@app.teardown_request
def close_database(exc):
  proxy.close()

import admin
import loan_pay

if app.debug is True:
  import logging
Exemple #34
0
import datetime

from peewee import *
from flask_bcrypt import generate_password_hash
from flask_login import UserMixin

import os

from playhouse.db_url import connect

if 'ON_HEROKU' in os.environ:
    DATABASE = connect(os.environ.get('DATABASE_URL'))
else:
    DATABASE = SqliteDatabase('budgetapp.sqlite')


class User(UserMixin, Model):
    id = PrimaryKeyField(null=False)
    first_name = CharField()
    last_name = CharField()
    email = CharField()
    password = CharField()
    balance = CharField(default='00,00')
    created_at = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = DATABASE

    @classmethod
    def create_user(cls, first_name, last_name, email, password, **kwargs):
        try: