示例#1
0
class Database(object):
    def __init__(self, app):
        self.app = app
        self.create_database()
        self.register_connection_handlers()

        self.Model = self.get_model_class()

    def create_database(self):
        self.database = PostgresqlDatabase(self.app.config['database_name'])

    def get_model_class(self):
        class BaseModel(Model):
            class Meta:
                db = self.database

        return BaseModel

    def _db_connect(self):
        self.database.connect()

    def _db_disconnect(self, exc):
        if not self.database.is_closed():
            self.database.close()

    def register_connection_handlers(self):
        self.app.before_request(self._db_connect)
        self.app.teardown_request(self._db_disconnect)
示例#2
0
class Database:
    def __init__(self, app=None):
        if app:
            self.init_app(app)

    def init_app(self, app):
        self.app = app
        self.load_db({
            'user': app.config.get('DATABASE_USERNAME'),
            'password': app.config.get('DATABASE_PASSWORD'),
            'host': app.config.get('DATABASE_HOST', 'localhost'),
            'port': app.config.get('DATABASE_PORT', '5432')
        })
        self.register_handlers()
        self.Model = self.get_model_class()

    def load_db(self, config):
        self.db = PostgresqlDatabase(self.app.config['DATABASE'], **config)

    def get_model_class(self):
        class BaseModel(Model):
            @classmethod
            def get_or_404(cls, *args, **kwargs):
                try:
                    return cls.get(*args, **kwargs)
                except cls.DoesNotExist:
                    abort(404)

            def __str__(self):
                try:
                    return self.name
                except AttributeError:
                    return str(self._get_pk_value())

            class Meta:
                database = self.db

        return BaseModel

    def connect_db(self):
        self.db.connect()

    def close_db(self, exc):
        if not self.db.is_closed():
            self.db.close()

    def register_handlers(self):
        self.app.before_request(self.connect_db)
        self.app.teardown_request(self.close_db)
示例#3
0
class Database:
    def __init__(self, databaseName, user, password, host, port):
        self.database = PostgresqlDatabase(databaseName,
                                           user=user,
                                           password=password,
                                           host=host,
                                           port=port)

    def getDatabase(self):
        return self.database

    def establishConnection(self):
        self.database.connect()

    def closeConnetion(self):
        self.database.close()

    def createTables(self, arrOfTables):
        with self.database:
            print(self.database)
            self.database.create_tables(arrOfTables)
示例#4
0
def get_user_by_authid(authid: str, db: PostgresqlDatabase) -> User:
    attempts = 0
    user = None
    while attempts <= 2 and user is None:
        try:
            user = User.get(User.authid == authid)
        except DoesNotExist:
            cherrypy.response.cookie["authid"] = authid
            cherrypy.response.cookie["authid"]["expires"] = 0
            raise cherrypy.HTTPError(status=401, message="Bad authid")
        except (InterfaceError, OperationalError) as e:
            print(str(e))
            attempts+= 1
            db.close()
            db.connect()
    if user is None:
        print("Couldnt connect and find user in thread", threading.get_ident())
        print('after', attempts, 'attempts')
        exit(1)
        raise cherrypy.HTTPError("DB connection error")
    else:
        print("Got user", user.name, "after", attempts, "attempts")
        return user
示例#5
0
class Base(Model):
    class Meta:
        database = db


class Annotation(Base):
    url = CharField(index=True)
    data = TextField()
    created = DateTimeField(index=True)

    def __str__(self):
        return '<Annotation {url} {data}>'.format(url=self.url, data=self.data)

    def serialize(self):
        data = json.loads(self.data)
        data['id'] = self.id
        data['created'] = self.created.strftime('%b %d %H:%M'),
        return data


def init_tables():
    # db.drop_tables([Annotation], safe=True)
    db.create_tables([Annotation], safe=True)


if __name__ == '__main__':
    db.connect()
    init_tables()
    db.close()