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()
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()
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()
def get_db(): db = None try: db = SessionLocal() yield db finally: db.close()
async def reset_db(): if args.init_db: db = SessionLocal() try: utils.init_db(db, args) finally: db.close()
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
def get_db(): db_session = SessionLocal() logger.debug("DB session obtained") try: yield db_session finally: db_session.close() logger.debug("DB Closed")
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()
def session_scope(): db = SessionLocal() try: yield db db.commit() except: db.rollback() raise finally: db.close()
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='У вас пока нет записанных настроек!')
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()
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()
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", )
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', )
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', )
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)
def choice_tuning(sail_firm: str, sail_model: str, wind_speed: float): db = SessionLocal() for sail in get_sails_by_wind(db, wind_speed): if sail.firm == sail_firm and sail.model == sail_model: tuning = { 'Фирма': sail.firm, 'Модель паруса': sail.model, 'Ветер': wind_speed, 'Ветер завала': str(sail.wind_min) + '-' + str(sail.wind_max), 'Завал': sail.mast_rake, 'Пребенд': sail.prebend, 'Натяжение на штаге': sail.tension, 'Дырка в степсе': sail.mast_step, 'Упор': sail.chocks, 'Длина краспиц': sail.spreraders_leng } db.close() return tuning
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
""" Bootstrap the DB if enviornment path to file is provided """ if json_file_path is not None: quotes_as_json = return_json_quotes(json_file_path) logger.debug("attempting to seed DB") db_session = SessionLocal() quoteList = schemas.QuotesList(quotes=quotes_as_json["quotes"]) if quotesCRUD.seed_db(db=db_session, quoteList=quoteList) is None: logger.info("DB Seed Unsuccessful") else: logger.info("database successfully seeded") db_session.close() @app.get("/", response_model=List[schemas.Quote]) async def quote(db: Session = Depends(get_db)): quote = jsonable_encoder(quotesCRUD.get_random_quote(db)) content = add_backend(fieldname="quotes", msg=quote) return JSONResponse(content=content) @app.get("/quotes", response_model=List[schemas.Quote]) async def list_quotes(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
from time import time from db.crud import create_regatta, get_regattas, delete_regatta from db.database import SessionLocal from parser.laser import get_data_laser from parser.fournine import get_data_49er from parser.fourseventy import get_data_470 t1 = time() data = get_data_470() + get_data_49er() + get_data_laser() db = SessionLocal() regattas = get_regattas(db) for r in regattas: if r not in data: delete_regatta(db, r.RegattaName) for regatta in data: if regatta.YachtClass == 'Laser 4.7': continue if regatta not in regattas: create_regatta(db, regatta) db.close() print(round(time() - t1, 2))
def database(): db = SessionLocal() try: yield db finally: db.close()
def get_db() -> Generator: try: db = SessionLocal() yield db finally: db.close()
def get_db(): db = SessionLocal() try: return db finally: db.close()