コード例 #1
0
def get_db():
    db = None
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()
コード例 #2
0
def get_web_text(req_id: int) -> None:
    """
    Function that processes URL requests of pending statuses.

    :param req_id: Integer ID of request
    """
    db = SessionLocal()
    db_request = crud.get_request(db, req_id=req_id)
    try:
        if db_request.status not in [
                Statuses.Queued.name, Statuses.Error.name
        ]:
            return

        db_request = crud.update_request_status(db, models.Statuses.Processing,
                                                db_request)

        document = _scrape_web_text_body(db_request.path)

        if document:
            extract_and_store_entities(req_id=req_id, text=document)

        db_request = crud.update_request_status(db, models.Statuses.Success,
                                                db_request)

    except Exception as e:
        logging.error(traceback.format_exc())
        crud.update_request_status(db, models.Statuses.Error, db_request)
    finally:
        db.close()
コード例 #3
0
def get_monster_id(user_id: int, session: Session = SessionLocal()):
    return (
        session.query(models.Monster)
        .filter(models.Monster.owner_id == user_id)
        .first()
        .id
    )
コード例 #4
0
async def process_description(message: Message, state: FSMContext):
    description = message.text
    async with state.proxy() as data:
        data['description'] = description

    db = SessionLocal()
    tuning = create_tuning(db, message, data)
    db.close()
    await message.answer(fmt.text(
        fmt.text(fmt.hunderline("Фирма лодки:"), data['boat']),
        fmt.text(fmt.hunderline("Фирма паруса:"), data['sail_firm']),
        fmt.text(fmt.hunderline("Модель паруса:"), data['sail_model']),
        fmt.text(fmt.hunderline("Место:"), data['place']),
        fmt.text(fmt.hunderline("Ветер:"), data['wind'], 'kt'),
        fmt.text(fmt.hunderline("Порывы:"), data['gusts'], 'kt'),
        fmt.text(fmt.hunderline("Высота волн:"), data['wave_height'], 'm'),
        fmt.text(fmt.hunderline("Длина волн:"), data['wave_length']),
        fmt.text(fmt.hunderline("Вес экипажа:"), data['crew_weight'], 'kg'),
        fmt.text(fmt.hunderline("Завал:"), data['mast_rake'], 'm'),
        fmt.text(fmt.hunderline("Пребенд:"), data['prebend'], 'mm'),
        fmt.text(fmt.hunderline("Натяжение на штаге:"), data['tension']),
        fmt.text(fmt.hunderline("Дырка степса:"), data['mast_step']),
        fmt.text(fmt.hunderline("Упор:"), data['chocks']),
        fmt.text(fmt.hunderline("Длина краспиц:"), data['spreraders_leng'],
                 'mm'),
        fmt.text(fmt.hunderline("Качество завала:"), data['quality']),
        fmt.text(fmt.hunderline("Описание:"), data['description']),
        sep="\n"),
                         parse_mode="HTML",
                         reply_markup=tuning_inline_kb(tuning.id))
    await message.answer(
        'Настройка записана. Просмотр, изменение и удаление настройки выполняется в команде /show.'
        'Для продолжения работы с ботом введите /help.')
    await state.finish()
コード例 #5
0
def extract_and_store_entities(req_id: int, text: str) -> None:
    db = SessionLocal()

    try:
        docs = nlp(text)
        sentences = list(docs.sents)

        for sent in sentences:
            sent_entities = {}
            for ent in sent.ents:
                if ent.label_ in NAMED_ENTITY_LABELS:
                    ent_text = ent.text.strip()
                    if ent_text not in sent_entities:
                        sent_entities[ent_text] = EntityCreate(
                            name=ent_text, ent_type=ent.label_)

            if sent_entities:
                db_sent = crud.create_sentence(db,
                                               req_id=req_id,
                                               sentence=sent.text)
                count = crud.create_entities(db,
                                             db_sent=db_sent,
                                             entities=list(
                                                 sent_entities.values()))

    finally:
        db.close()
コード例 #6
0
def check_user_credentials(user: schemas.UserLogin, session: Session = SessionLocal()):
    db_user = (
        session.query(models.User).filter(models.User.username == user.username).first()
    )
    if not db_user:
        return
    return user.username == db_user.username and user.password == db_user.password
コード例 #7
0
def get_user_stats(user_id: int, session: Session = SessionLocal()):
    user = session.query(models.User).filter(models.User.id == user_id).first()
    return {
        "id": int(user.id),
        "health": int(user.health),
        "hits": int(user.hits),
        "strength": int(user.strength),
    }
コード例 #8
0
async def db_session_middleware(request: Request, call_next):
    response = Response("Internal server error", status_code=500)
    try:
        request.state.db = SessionLocal()
        response = await call_next(request)
    finally:
        request.state.db.close()
    return response
コード例 #9
0
ファイル: main.py プロジェクト: laddhashreya2000/danaher-kmr
async def reset_db():
    if args.init_db:
        db = SessionLocal()
        try:
            utils.init_db(db, args)

        finally:
            db.close()
コード例 #10
0
def insert_db():
    r = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=' +
                     scheduler_coin + '&vs_currencies=usd')
    if r.status_code == 200:
        db = SessionLocal()
        price = float(r.json()[scheduler_coin]['usd'])
        create_coin = crud.create_coin(db=db, coin=scheduler_coin, price=price)
        db.close()
        return create_coin
コード例 #11
0
def get_db():

    db_session = SessionLocal()
    logger.debug("DB session obtained")
    try:
        yield db_session
    finally:
        db_session.close()
        logger.debug("DB Closed")
コード例 #12
0
def session_scope():
    db = SessionLocal()
    try:
        yield db
        db.commit()
    except:
        db.rollback()
        raise
    finally:
        db.close()
コード例 #13
0
async def process_all_tunings(message: Message):
    user_id = message['from'].id
    db = SessionLocal()
    data = show_all_personal_tunings(db, user_id)
    db.close()
    inline_kb = all_tunings_inline_kb(data)
    if data:
        await message.reply(text='Ваши настройки: ', reply_markup=inline_kb)
    else:
        await message.reply(text='У вас пока нет записанных настроек!')
コード例 #14
0
def get_task_by_id(task_id, user_id: int):
    db: Session = SessionLocal()
    task = db.query(
        task_model.Task).filter(task_model.Task.id == task_id).filter(
            task_model.Task.user_id == user_id)

    if not task:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail='Task not found')
    return task
コード例 #15
0
async def process_issue(message: Message, state: FSMContext):
    async with state.proxy() as data:
        data['issue'] = message.text
    db = SessionLocal()
    crud.create_issue(db, data['issue'], message)
    db.close()
    await message.answer(
        'Благодарим за предоставленную информацию, мы рассмотрим её в ближайшее время!'
    )
    await state.finish()
コード例 #16
0
def delete_task_by_id(task_id: str, user_id: int):
    db: Session = SessionLocal()
    task = db.query(
        task_model.Task).filter(task_model.Task.id == task_id).filter(
            task_model.Task.user_id == user_id)
    if not task.first():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
    task.delete(synchronize_session=False)
    db.commit()
    return status.HTTP_200_OK
コード例 #17
0
def create_task(request: taskSchema.SimpleTask, user_id: int):
    db: Session = SessionLocal()
    new_task = task_model.Task(title=request.title,
                               description=request.description,
                               completed=request.completed,
                               user_id=user_id)
    db.add(new_task)
    db.commit()
    db.refresh(new_task)

    return new_task
コード例 #18
0
async def process_filter(message: Message, state: FSMContext):

    async with state.proxy() as data:
        data['filter'] = message.text
    db = SessionLocal()
    dat = find_personal_tunings_by_filter(db, data['filter'],
                                          message.from_user.id)
    db.close()
    filtered_tunings_kb = filtered_tunings_inline_kb(data['filter'], dat)
    await message.reply(text='Доступные настройки: ',
                        reply_markup=filtered_tunings_kb)
    await state.finish()
コード例 #19
0
async def startup_event():
    """
    Startup event to "abruptly stopped" Requests to Error status.
    """
    db = SessionLocal()
    try:
        err_count = crud.update_requests_status(
            db, [models.Statuses.Queued, models.Statuses.Processing],
            models.Statuses.Error)
        logger.info(f"Updated {err_count} requests to Error state.")
    finally:
        db.close()
コード例 #20
0
async def process_callback_tuning(callback_query: CallbackQuery):
    tuning_id = callback_query.data[2:]
    if tuning_id.isdigit():
        tuning_id = int(tuning_id)
    db = SessionLocal()
    tuning = find_tuning_by_id(db, tuning_id)
    db.close()
    await bot.send_message(
        callback_query.from_user.id,
        return_tuning_text(tuning),
        reply_markup=tuning_inline_kb(tuning_id),
        parse_mode="HTML",
    )
コード例 #21
0
async def process_callback_delete(callback_query: CallbackQuery):
    tuning_id = callback_query.data[6:]
    if tuning_id.isdigit():
        tuning_id = int(tuning_id)
    db = SessionLocal()
    delete_tuning_by_id(db, tuning_id)
    db.close()

    await bot.send_message(
        callback_query.from_user.id,
        'Настройка удалена',
        parse_mode='HTML',
    )
コード例 #22
0
def create_user(user: schemas.UserCreate, session: Session = SessionLocal()):
    db_user = models.User(**user.dict())
    session.add(db_user)
    msg = {"status": "success", "msg": f"user {user.username} created"}
    try:
        session.commit()
        session.refresh(db_user)
    except Exception:
        session.rollback()
        msg = {"status": "error", "msg": f"username {user.username} already taken"}
    finally:
        session.close()
        return msg
コード例 #23
0
ファイル: db_populator.py プロジェクト: AmeyMore98/movie_api
def pouplate_db_from_json():
    """Populates imdb.db file from imdb.json
    """
    print("Reading JSON file...")
    with open('./imdb.json', 'r') as f:
        json_data = json.load(f)

    print("Creating DB Session")
    db = SessionLocal()

    for item in json_data:
        movie = movie_schema.MovieCreate(**item, popularity=item['99popularity'])
        print("Inserting: {}".format(movie.name))
        MovieHandler.create_movie(db, movie=movie)
コード例 #24
0
def create_user(request: userSchemas.User):
    db: Session = SessionLocal()
    new_user = userModels.User(name=request.name,
                               email=request.email,
                               password=auth.oauth2.bcrypt(request.password))

    try:
        db.add(new_user)
        db.commit()
        db.refresh(new_user)
    except IntegrityError:
        db.rollback()
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
    return new_user
コード例 #25
0
def update_task_by_id(task_id: int, request: taskSchema.SimpleTask,
                      user_id: int):
    db: Session = SessionLocal()
    task = db.query(
        task_model.Task).filter(task_model.Task.id == task_id).filter(
            task_model.Task.user_id == user_id).one_or_none()
    if task is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)

    task.description = request.description
    task.title = request.title
    task.completed = request.completed
    db.commit()
    db.refresh(task)
    return status.HTTP_200_OK
コード例 #26
0
def update_health_stats(
    user_id: int,
    monster_health: int,
    user_health: int,
    session: Session = SessionLocal(),
):
    session.query(models.Monster).filter(models.Monster.owner_id == user_id).update(
        {"health": monster_health}
    )
    session.query(models.User).filter(models.User.id == user_id).update(
        {"health": user_health}
    )
    try:
        session.commit()
    except Exception:
        session.rollback()
    finally:
        session.close()
コード例 #27
0
def create_user_monster(
    monster: schemas.MonsterCreate, user_id: int, session: Session = SessionLocal()
):
    db_monster = models.Monster(**monster.dict(), owner_id=user_id)
    session.add(db_monster)
    msg = {"status": "success", "msg": f"monster {monster.monstername} created"}
    try:
        session.commit()
        session.refresh(db_monster)
    except Exception:
        session.rollback()
        msg = {
            "status": "error",
            "msg": f"can not create monster {monster.monstername}",
        }
    finally:
        session.close()
        return msg
コード例 #28
0
async def process_callback_filttun(callback_query: CallbackQuery):
    tuning = callback_query.data[2:]

    fil = tuning.split('!filter')
    fil_name = fil[1]
    fil_value = fil[0]
    db = SessionLocal()

    tuning = find_tunings_by_filter(db, fil_name, fil_value,
                                    callback_query.from_user.id)
    db.close()
    inline_kb = all_tunings_inline_kb(tuning)
    await bot.send_message(
        callback_query.from_user.id,
        'Доступные настройки: ',
        reply_markup=inline_kb,
        parse_mode='HTML',
    )
コード例 #29
0
async def process_filter_tunings(message: Message):
    user_id = message['from'].id
    db = SessionLocal()

    filters = choice_filters_for_tuning(show_personal_tuning(db, user_id))
    db.close()
    markup = ReplyKeyboardMarkup(resize_keyboard=True,
                                 selective=True,
                                 one_time_keyboard=True)
    if filters:
        await ShowTuning.filter.set()
        for filt in filters:
            markup.add(filt)
        await message.reply("Как вы хотите подобрать настройку?",
                            reply_markup=markup)
    else:
        markup.add("Показать все мои настройки")
        await message.reply('У вас слишком мало настроек, лучше показать все',
                            reply_markup=markup)
コード例 #30
0
ファイル: auth.py プロジェクト: roeeyn/TodoNotes
async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_email: str = payload.get("sub")
        if user_email is None:
            raise credentials_exception
        token_data = TokenData(email=user_email)
    except PyJWTError:
        raise credentials_exception
    db = SessionLocal()
    user = get_user_by_email_or_username(db, email=token_data.email)
    db.close()
    if user is None:
        raise credentials_exception
    return user