Beispiel #1
0
def reset_db():
    import os, psycopg2, urllib.parse as urlparse  # CHECK
    urlparse.uses_netloc.append('postgres')
    url = urlparse.urlparse(os.environ["DATABASE_URL"])
    db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname,
                            port=url.port)

    db.connect(True)
    print('CONNECTED')

    db.drop_tables([AdminPage, TargetGroup, UserPage, SenderPage])

    db.create_tables([AdminPage, TargetGroup, UserPage, SenderPage])

    return 'DB is reseted!'
Beispiel #2
0
class BaseModel(Model):
    class Meta:
        database = db


class Person(BaseModel):
    first_name = CharField()
    last_name = CharField()
    phone_number = CharField()
    email = CharField()
    birthday = DateField()


db.connect()
db.drop_tables([Person])
db.create_tables([Person])

# Populating the SQL Database
Levani = Person(first_name='Levani',
                last_name='Papashvili',
                phone_number='249-943-0303',
                email='*****@*****.**',
                birthday='11/11/1984')
Levani.save()
Charlie = Person(first_name='Charlie',
                 last_name='Smith',
                 phone_number='555-555-2524',
                 email='*****@*****.**',
                 birthday='03/09/85')
Charlie.save()
Beispiel #3
0
from model_column import AdminColumnModel
from model_table import AdminTableModel
from model_user import AdminUserModel
from peewee import PostgresqlDatabase

if __name__ == "__main__":
    database = PostgresqlDatabase('cs419', user='******')

    tables = [
        AdminColumnModel,
        AdminTableModel,
        AdminUserModel
    ]

    database.drop_tables(tables, safe=True, cascade=True)
Beispiel #4
0
class DatabaseConfig:
    """
    Instances of this class manage the configuration of tha database for the project. This includes the engine, host,
    port, username, password and database name.

    The typical work flow using this class is the following:
    A new object is created from a config dict. Then the database is init-ed (meaning the object is created)
    Then the database proxy (placeholder) for the models is connected to this database object at run time and then the
    database is actually connected to its persistent counterpiece (file for sqlite, server for mysql):

    EXAMPLE:
    database_config = DatabaseConfig.from_dict(database_dict)
    database_config.init()
    database_proxy.initialize(database_config.get())
    database_config.connect()
    database_config.create_tables() # OPTIONAL

    CHANGELOG

    Added 09.06.2019
    """
    # This dict will be used as the default base dict, when a new DatabaseConfig object is to be created from a dict,
    # which may not contain all the keys. For the keys that are not present, the default ones will stay, but will
    # otherwise be overwritten.
    DEFAULT_DICT = {
        'engine': 'sqlite',
        'host': ':memory:',
        'database': '',
        'user': '',
        'password': '',
        'port': 0
    }

    # A list of all valid engine strings
    SUPPORTED_ENGINES = ['sqlite', 'mysql', 'postgres']

    # This is a list, that contains all the model classes of this project. This list is needed to be passed
    # to the database to create all the tables
    MODELS = [User, Reward, Pack]

    # INSTANCE CONSTRUCTION
    # ---------------------

    def __init__(self, engine: str, host: str, database: str, user: str,
                 password: str, port: int) -> NoReturn:
        # This will raise an error, if the engine string is not a valid one
        self.check_engine(engine)

        self.engine = engine
        self.host = host
        self.database = database
        self.user = user
        self.password = password
        self.port = port

        # Later on this variable will contain the actual database instance
        self.instance = None

    def check_engine(self, engine: str):
        """
        This will raise a value error if the engine string is not one of the supported engines.

        CHANGELOG

        Added 09.06.2019

        :param engine:
        :return:
        """
        if engine not in self.SUPPORTED_ENGINES:
            raise ValueError('The engine "{}" is not supported'.format(engine))

    # CREATING DATABASE INSTANCE
    # --------------------------

    def init(self):
        """
        This method will create a new database object and put it into the "self.instance" variable. The type of
        database object created depends on the value of the engine string

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        # Basically I am using this dict as a "switch" statement to reduce "if"-clutter
        engine_create_methods = {
            'sqlite': self.init_sqlite,
            'mysql': self.init_mysql,
            'postgres': self.init_postgres
        }
        engine_create_methods[self.engine]()

    def init_sqlite(self):
        """
        Creates a new sqlite database object and puts it into "self.instance"
        NOTE: For the creation of a sqlite database only the path to the file is relevant. The "self.host" variable
        will be used as the sqlite string

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        self.instance = SqliteDatabase(self.host)

    def init_mysql(self):
        """
        Creates a new mysql database object and puts it into the "self.instance".

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        self.instance = MySQLDatabase(self.database,
                                      host=self.host,
                                      user=self.user,
                                      password=self.password,
                                      port=self.port)

    def init_postgres(self):
        """
        Creates a new postgrsql database object and puts it into the "self.instance"

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        self.instance = PostgresqlDatabase(self.database,
                                           host=self.host,
                                           user=self.user,
                                           password=self.password,
                                           port=self.port)

    # DATABASE OPERATIONS
    # -------------------

    def connect(self):
        """
        When a database object has already been created, this method actually connects the object in "self.instance"
        to the actual persistent database.

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        self.instance.connect()

    def create_tables(self):
        """
        If the database object is already connected and created, this method will create the tables for all the models
        of the rewardify project into this database.

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        self.instance.create_tables(self.MODELS)

    def drop_tables(self):
        """
        If the database object is already connected and created, this method will drop the tables for all the models
        of the rewardify project into this database.

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        self.instance.drop_tables(self.MODELS)

    def get(self):
        """
        returns the database object

        CHANGELOG

        Added 09.06.2019

        :return:
        """
        return self.instance

    # UTILITY METHODS
    # ---------------

    def update(self, database_dict: Dict) -> NoReturn:
        """
        Given a database dict, all the internal values will be updated according to this dict

        CHANGELOG

        Added 09.06.2019

        :param database_dict:
        :return:
        """
        for key, value in database_dict.items():
            setattr(self, key, value)

    # CLASS METHODS
    # -------------

    @classmethod
    def from_dict(cls, database_dict):
        """
        Given a dict, which contains the database config, this method will create and return a new DatabaseConfig
        object from it.
        The dict can contain any subset of the following keys, every key not used it substituted with the default item:
        - engine
        - host
        - database
        - port
        - user
        - password

        CHANGELOG

        Added 09.06.2019

        :param database_dict:
        :return:
        """
        # We will use the default dict as a base line (in case not all keys are provided by the given dict as for the
        # case of sqlite. Then we replace all possible values with the actual ones
        argument_dict = cls.DEFAULT_DICT
        argument_dict.update(database_dict)

        # Finally we can pass the arguments to the constructor by unpacking the dict
        return cls(**argument_dict)
Beispiel #5
0
from peewee import SqliteDatabase, PostgresqlDatabase, Model, CharField, DateTimeField

# SQLite database using WAL journal mode and 64MB cache.
# sqlite_db = SqliteDatabase('my_database.db')


db = PostgresqlDatabase(
    'library', user='******',
    password='******',
    host='46.30.164.249', port=5432
)


class GoogleImage(Model):

    keyword = CharField()
    image_url = CharField(max_length=1024)
    date = DateTimeField()

    class Meta:
        database = db
        table_name = 'images_from_google'


if __name__ == '__main__':
    db.connect()
    db.drop_tables([GoogleImage])
    db.create_tables([GoogleImage])