Beispiel #1
0
 def get_permissions(cls, bot_id, networkauth):
     with session_scope() as session:
         permissions = session.query(cls.permissions).filter(cls.bot_id == bot_id, cls.networkauth == networkauth).scalar()
         if permissions:
             return permissions.split(',')
         else:
             return None
Beispiel #2
0
 def delete(cls, bot_id, id):
     with session_scope() as session:
         perform = session.query(cls).filter(cls.bot_id == bot_id, cls.id == id).first()
         if perform:
             session.delete(perform)
             return True
         return False
Beispiel #3
0
def _export(
        tables: models.
    TABLES_ENUM = typer.Option(None,
                               "--tables",
                               "-t",
                               help="Список таблиц в которые сделать записи",
                               case_sensitive=False),
        filename: str = typer.Option("cs_education_dump"),
):
    """WIP: Экспорт материалов"""
    def dict_factory(cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d

    with session_scope() as session:

        session.row_factory = dict_factory

        tables = session.execute(
            "SELECT name FROM sqlite_master WHERE type='table';")

        with open(f"{filename}.json", "w") as dump:
            for table_name in tables:
                results = session.execute("SELECT * FROM " +
                                          table_name["name"])
                dump.write(
                    format(results).replace(" u'", "'").replace("'", '"'))
Beispiel #4
0
 def set(cls, bot_id, key, value):
     with session_scope() as session:
         keyval = session.query(cls).filter(cls.bot_id == bot_id, cls.key == key).first()
         if keyval:
             keyval.value = value
         else:
             keyval = cls(bot_id=bot_id, key=key, value=value)
             session.add(keyval)
Beispiel #5
0
 def get_quotes(cls, bot_id, channel, quote_id=None, text=None):
     with session_scope() as session:
         query = session.query(cls.quote_id, cls.added_by_auth, cls.added_date, cls.quote).filter(cls.bot_id == bot_id, cls.channel == channel, cls.deleted == False)
         if quote_id:
             query = query.filter(cls.quote_id == quote_id)
         elif text:
             for s in text.split():
                 query = query.filter(cls.quote.like('%{}%'.format(s)))
         return query.all()
Beispiel #6
0
 def authenticate(cls, bot_id, username, password, hostmask=None):
     with session_scope() as session:
         hashed = hashlib.sha512(str(bot_id) + password).hexdigest()
         user = session.query(cls).filter(cls.bot_id == bot_id, cls.username == username, cls.password == hashed).first()
         if user:
             if hostmask:
                 user.hostmask = hostmask
             return cls.Auth(user)
         return False
Beispiel #7
0
 def add(cls, bot_id, channel, address, auth, quote):
     last_quote_id = cls.get_last_quote_id(bot_id, channel)
     if last_quote_id is None:
         last_quote_id = 0
     quote_id = last_quote_id + 1
     with session_scope() as session:
         quote = cls(bot_id=bot_id, quote_id=quote_id, channel=channel, added_by=address, added_by_auth=auth, quote=quote)
         session.add(quote)
         session.commit()
         return quote.quote_id
Beispiel #8
0
 def delete_permission(cls, bot_id, networkauth, permission):
     with session_scope() as session:
         wl = session.query(cls).filter(cls.bot_id == bot_id, cls.networkauth == networkauth).first()
         if wl:
             permissions = wl.permissions.split(',')
             if permission in permissions:
                 permissions.remove(permission)
             wl.permissions = ','.join(permissions)
             return True
         return False
Beispiel #9
0
 def add_permission(cls, bot_id, networkauth, permission):
     with session_scope() as session:
         wl = session.query(cls).filter(cls.bot_id == bot_id, cls.networkauth == networkauth).first()
         if wl:
             permissions = wl.permissions.split(',')
             if permission not in permissions:
                 permissions.append(permission)
             wl.permissions = ','.join(permissions)
         else:
             wl = cls(bot_id=bot_id, networkauth=networkauth, permissions=permission)
             session.add(wl)
Beispiel #10
0
def remove(
    id: int = typer.Argument(...),
    table: models.TABLES_ENUM = typer.Option(
        ...,
        "--table",
        "-t",
        help="Таблица в которой удалить записи",
        case_sensitive=False),
):
    """WIP: Удалить материал по ID"""
    with session_scope() as session:
        _object = getattr(models, table)
        session.delete(_object.query.filter_by(id=id))
Beispiel #11
0
def _import(
    data: typer.FileText = typer.Argument(...),
    overwrite: bool = typer.Option(
        False,
        "--overwrite",
        "-w",
        help="Перезаписать объекты, если есть такой PK"),
    tables: List[models.TABLES_ENUM] = typer.Option(
        None,
        "--tables",
        "-t",
        help="Список таблиц в которые сделать записи",
        case_sensitive=False),
):
    """
    Импорт материалов в базу

    Структура:
    {"table":
        {"column": value, "index": None}
    }\n
    index None == Создание новой записи / не None == замена текущей
    """
    _source = orjson.loads(data.read())

    with session_scope() as session:
        for table, raws in _source.items():
            if tables and table not in tables:
                # Пропустить таблицу, если список таблиц регулируется аргументами и этой таблицы там нет
                continue

            _object = getattr(models, table)
            assert _object, f"Таблицы {table} не существует"

            for _r in raws:
                _id = _r.pop("id", None)
                # Добавить проверку существования ID в базе
                # -> Если такой элемент уже есть, делать обновление
                _data = _object.model(exclude=["id"]).parse_obj(_r)
                one = session.query(_object).filter_by(id=_id).one_or_none()

                if one:
                    if not overwrite:
                        print(f"Объект {table}{_r} не записан")
                        continue
                    session.query(_object).filter(_object.id == _id).update(
                        _data.dict())
                    session.query(_object).filter(_object.id == _id).update(
                        _data.dict())
                else:
                    session.add(_object(**_data.dict()))
Beispiel #12
0
def add(table: models.TABLES_ENUM = typer.Option(
    ...,
    "--table",
    "-t",
    help="Таблица в которую добавить запись",
    case_sensitive=False),
        body: str = typer.Argument(None)):
    """WIP: Добавить материал в базу"""
    with session_scope() as session:
        # Получаем таблицу
        _table = getattr(models, table)
        # Если есть аргументы в словаре -- завершение
        if body:
            data = _table.model()(
                body)  # Выкинет исключение, а нам это и хорошо
            session.add(_table(**data.dict()))
        else:
            while True:
                # Если нет -- получаем все поля модели, просим пользователя ввести их по очереди -- завершение
                # Завершение: валидируем аргументы, сохраняем записть, возвращаем данные как они в базе
                if not repeat or not click.confirm("Добавить еще?"):
                    break
Beispiel #13
0
 def delete(self):
     with session_scope() as session:
         user = self.get_instance(session)
         if user:
             session.delete(user)
Beispiel #14
0
 def add(cls, bot_id, pline):
     with session_scope() as session:
         perform = cls(bot_id=bot_id, pline=pline)
         session.add(perform)
         session.commit()
         return perform.id
Beispiel #15
0
 def get_value(cls, bot_id, key):
     with session_scope() as session:
         return session.query(cls.value).filter(cls.bot_id == bot_id, cls.key == key).scalar()
Beispiel #16
0
 def create_defaults(cls, bot_id):
     with session_scope() as session:
         if not session.query(func.count(cls.id)).filter(cls.bot_id == bot_id).scalar():
             password = hashlib.sha512(str(bot_id) + '12345').hexdigest()
             user = cls(bot_id=bot_id, username='******', password=password, hostmask='', flags='n')
             session.add(user)
Beispiel #17
0
 def add(cls, bot_id, username, password, flags):
     with session_scope() as session:
         hashed = hashlib.sha512(str(bot_id) + password).hexdigest()
         user = cls(bot_id=bot_id, username=username, password=hashed, hostmask='', flags=flags)
         session.add(user)
         return cls.Auth(user)
Beispiel #18
0
 def get_user_by_username(cls, bot_id, username):
     with session_scope() as session:
         user = session.query(cls).filter(cls.bot_id == bot_id, cls.username == username).first()
         if user:
             return cls.Auth(user)
         return None
Beispiel #19
0
 def list_auths(cls, bot_id):
     with session_scope() as session:
         return session.query(cls.networkauth).filter(cls.bot_id == bot_id).all()
Beispiel #20
0
 def get_last_quote_id(cls, bot_id, channel):
     with session_scope() as session:
         return session.query(func.max(cls.quote_id)).filter(cls.bot_id == bot_id, cls.channel == channel).scalar()
Beispiel #21
0
 def change_password(self, newpass):
     with session_scope() as session:
         user = self.get_instance(session)
         hashed = hashlib.sha512(str(self.bot_id) + newpass).hexdigest()
         user.password = hashed
Beispiel #22
0
 def list_lines(cls, bot_id):
     with session_scope() as session:
         return session.query(cls.id, cls.pline).filter(cls.bot_id == bot_id).all()
Beispiel #23
0
 def change_flags(self, flags):
     with session_scope() as session:
         user = self.get_instance(session)
         user.flags = flags
Beispiel #24
0
 def add(cls, tweet_id, networkauth):
     with session_scope() as session:
         tweet = cls(tweet_id=tweet_id, networkauth=networkauth)
         session.add(tweet)
Beispiel #25
0
 def delete(cls, bot_id, channel, quote_id):
     with session_scope() as session:
         num = session.query(cls).filter(cls.bot_id == bot_id, cls.channel == channel, cls.quote_id == quote_id).update({'deleted': True})
         session.commit()
         return num
Beispiel #26
0
 def delete_key(cls, bot_id, key):
     with session_scope() as session:
         keyval = session.query(cls).filter(cls.bot_id == bot_id, cls.key == key).first()
         if keyval:
             session.delete(keyval)
Beispiel #27
0
 def get_user_by_hostmask(cls, bot_id, hostmask):
     with session_scope() as session:
         user = session.query(cls).filter(cls.bot_id == bot_id, cls.hostmask == hostmask).first()
         if user:
             return cls.Auth(user)
         return None
Beispiel #28
0
 def get_auth_by_tweet(cls, tweet_id):
     with session_scope() as session:
         return session.query(cls.networkauth).filter(cls.tweet_id == tweet_id).scalar()
Beispiel #29
0
 def list_users(cls, bot_id):
     with session_scope() as session:
         return session.query(cls.username, cls.hostmask, cls.flags).filter(cls.bot_id == bot_id).all()
Beispiel #30
0
def scrap_and_write():
    lst = scrap()
    with db.session_scope() as session:
        session.add_all(lst)