def paginator(view_type): skip = request.args.get("skip", default=0, type=int) limit = request.args.get("limit", default=10, type=int) if not all([isinstance(skip, int), isinstance(limit, int), not skip < 0, not limit < 0]): return make_response(jsonify({ "message": f"Incorrect [skip] and [limit] request params"}), 401) try: with Recommend(db) as r: if not view_type in r.preview_type_pipelines: raise ValueError( f"View type error. U have to use one of following endpoints: " f"{tuple(r.preview_type_pipelines.keys())}") resp = r.get_previews("recipes", pipeline=r.pipeline(view_type, skip, limit)) previews = r.get_all_previews(collection='recipes', req={ 'id': { '$in': r.id_finder(resp) } }, group=r.preview_fields) for i, preview in enumerate(previews): for item in resp: if item["id"] == preview["id"]: previews[i]["metric"] = item["metric"] previews = {"previews": previews, "sort_option": r.sort_options[view_type]} return make_response(jsonify(previews), 200) except Exception as e: logger.error(f"Oops, something happen wrong: {e}") return make_response(jsonify({"message": f"Oops, something happen wrong: {e}"}), 500)
def _change(): r = request.get_json(force=True) try: old_password, new_password = r["old"], r["new"] except: logger.error(f"Incorrect request parameters set. Expected: old, new. " f"Gotten: {','.join(r.keys())}") return make_response(jsonify({"message": f"Incorrect request parameters set. Expected: old, new. " f"Gotten: {','.join(r.keys())}"}), 401) if not check_password_hash(current_user.password, old_password): return make_response(jsonify({"message": "Incorrect old password"}), 401) try: User.query.filter(User.id == current_user.id).update( {"password": generate_password_hash(new_password, method="sha256")}) sqlite_db.session.commit() except Exception as e: logger.error(f"Error during password updating: {e}") return make_response(jsonify({"message": f"Error during password updating: {e}"}), 500) resp = make_response(jsonify({"message": "Password has benn changed"}), 200) resp.set_cookie(str(current_user.id), current_user.password) return resp
def confirm(): try: confirm_token = request.args.get("token") if not confirm_token: raise ValueError("there is no token in the request params.") user_email = decode_token(confirm_token)["identity"] if not user_email: raise ValueError("unsuccessful email extraction from token.") user = User.query.filter(User.email == user_email).first() if not user: raise ValueError(f"unknown user with email {user_email}.") if user.confirmed: raise ValueError(f"account with {user_email} has been already confirmed.") User.query.filter(User.email == user.email).update({"confirmed": 1}) sqlite_db.session.commit() except Exception as e: logger.error(f"Account confirm error: {e}") return make_response(render_template("token_error.html", error=f"Account confirm error: {e}"), 401) new_users_logger.info(f'Новый пользователь: {user.email}', alert=True) return make_response(render_template("confirm_successful_status.html", user=user.name, email=user.email), 200)
def send_async_email(app, msg): with app.app_context(): try: mail.send(msg) except ConnectionRefusedError: logger.error(InternalServerError("[MAIL SERVER] not working")) raise InternalServerError("[MAIL SERVER] not working")
def page(): skip = request.args.get("skip", default=0, type=int) limit = request.args.get("limit", default=10, type=int) if not all([isinstance(skip, int), isinstance(limit, int), not skip < 0, not limit < 0]): return make_response(jsonify({ "message": f"Incorrect [skip] and [limit] request params"}), 401) try: with Recommend(db) as r: try: favorites = r.get_previews('favorite', pipeline=[ {"$match": {"user": current_user.id}}, {"$group": {"_id": {"recipe": "$recipe"}}} ]) except Exception as e: logger.error(f'Ошибка при выборе любимых блюд: {e}') favorites = [] if len(favorites): # TODO раскомментировать. тут будут отдаваться рекоммендации от нашего алгоритма recommendations = r.find_similar(rk2t, t2rk, kdtree, vectors, favorites, skip, limit) else: recommendations = r.get_previews("recipes", pipeline=r.pipeline('recommendations', skip, limit)) tops_dict = { "recommendations": recommendations, "most_popular": r.get_previews("recipes", pipeline=r.pipeline('most_popular', skip, limit)), "fastest": r.get_previews("recipes", pipeline=r.pipeline('fastest', skip, limit)), "biggest": r.get_previews("recipes", pipeline=r.pipeline('biggest', skip, limit)), "optimal": r.get_previews("recipes", pipeline=r.pipeline('optimal', skip, limit)), } tops = {} for top_type, resp in tops_dict.items(): previews = r.get_all_previews(collection='recipes', req={ 'id': { '$in': r.id_finder(resp) } }, group=r.preview_fields) for i, preview in enumerate(previews): for item in resp: if item["id"] == preview["id"]: previews[i]["metric"] = item["metric"] tops[top_type] = {"previews": previews, "sort_option": r.sort_options[top_type]} return make_response(jsonify(tops), 200) except Exception as e: logger.error(f"Oops, something happen wrong: {e}") return make_response(jsonify({"message": f"Oops, something happen wrong: {e}"}), 500)
def _info(): if not sorted(request.args) == sorted(["t", "s", "i", "fn", "fp", "n" ]): return make_response( jsonify({ "message": f"Incorrect request parameters set. Expected: t, s, fn, i, fp, n. " f"Gotten:{','.join(request.args)}" }), 401) bill_info_req = f"https://proverkacheka.nalog.ru:9999/v1/inns/*/kkts/*/fss/{request.args.get('fn')}" \ f"/tickets/{request.args.get('i')}?" \ f"fiscalSign={request.args.get('fp')}&sendToEmail=no" info_status = requests.get(bill_info_req, headers=bills_headers, auth=(PHONE_NUMBER, BILL_PASS)) if info_status.status_code == 200: bill = info_status.json() try: bill_id, message = dump_bill(current_user.id, bill) except Exception as e: logger.error(f'Ошибка записи чека в базу данных: {e}') return make_response( str(ValueError(f'Ошибка записи чека в базу данных: {e}')), 500) return make_response(jsonify({ "message": message, "id": bill_id }), 200) else: return make_response( jsonify({ "message": f'Error: {info_status.content.decode()}. Probably bill has not been verified.' }), info_status.status_code)
def reset(): try: reset_token = request.args.get("token") if not reset_token: raise ValueError("there is no token in the request params.") user_id = decode_token(reset_token)["identity"] if not user_id: raise ValueError("unsuccessful id extraction from token.") if db.find_all("reset_token", req={"user": user_id, "token": reset_token}): raise ValueError("token has been already in used.") user = User.query.filter(User.id == user_id).first() if not user: raise ValueError("Unknown user id.") new_password = randomStringDigits() User.query.filter(User.id == user_id).update( {"password": generate_password_hash(new_password, method="sha256")}) sqlite_db.session.commit() db.easy_add("reset_token", document={"user": user_id, "token": reset_token}) send_email("[TasteAssistant] Reset Your Password", sender="*****@*****.**", recipients=[user.email], text_body=new_password, html_body=render_template("reset_pass.html", user=user.name, password=new_password) ) except Exception as e: logger.error(f"Password reset error: {e}") return make_response(render_template("token_error.html", error=f"Password reset error: {e}"), 401) return make_response(render_template("reset_successful_status.html", user=user.name, email=user.email), 200)
def signup(): r = request.get_json(force=True) try: r["email"], r["name"], r["password"] except: logger.error(f"Incorrect request parameters set. Expected: email, name, password. " f"Gotten:{','.join(r.keys())}") return make_response(jsonify({ "message": f"Incorrect request parameters set. Expected: email, name, password. " f"Gotten:{','.join(r.keys())}"}), 401) email, name, password = r["email"].lower(), r["name"], r["password"] user = User.query.filter(or_(User.email == email)).first() # if this returns a user, then the email already exists in database if user: return make_response(jsonify({ "message": f"User with email {email} already exists."}), 401) # create new user with the form data. Hash the password so plaintext version isn"t saved. new_user = User(email=email, name=name, password=generate_password_hash(password, method="sha256"), confirmed=0) sqlite_db.session.add(new_user) sqlite_db.session.commit() confirm_token = create_access_token(str(new_user.email)) url = request.host_url + f"confirm?token={confirm_token}" send_email("[TasteAssistant] Confirm signup", sender="*****@*****.**", recipients=[new_user.email], text_body=url, html_body=render_template("confirm_user_create.html", url=url, user=new_user.name) ) return make_response(jsonify({"message": "Successful signup. Please confirm your signup with email."}), 200)
def search(): sort_type = bool(request.args.get("type", default=0, type=int)) query_string = request.args.get("q", default="", type=str) skip = request.args.get("skip", default=0, type=int) limit = request.args.get("limit", default=10, type=int) try: if not query_string: previews = elastic.find_all(skip, limit) else: if not sort_type: previews = elastic.easy_query(query_string, skip, limit) else: # TODO uncomment previews = [ ] #elastic.intelligence_query(query_string, skip, limit) previews = {"previews": previews, "sort_option": 1} return make_response(jsonify(previews), 200) except Exception as e: logger.error(f"Oops, something happen wrong in search method: {e}") return make_response( jsonify({"message": f"Oops, something happen wrong: {e}"}), 500)
def _bill(bill): if not bill: return make_response( jsonify({"message": f"Incorrect request params."}), 401) try: bill = db.find_one('bills', {"checksum": bill}) except Exception as e: logger.error(f'Ошибка при обращении к базе данных {str(e)}') make_response( jsonify( { "message": f'Ошибка при обращении к базе данных {str(e)}' }, 500)) if not bill: return make_response(jsonify({"message": "BIll not found."}), 404) response = { "price": bill['bill']['document']['receipt']['totalSum'], "components": list( map( lambda x: { 'name': x.get('name'), 'price': x.get('price'), 'quantity': x.get('quantity'), 'sum': x.get('sum') }, bill['bill']['document']['receipt']['items'])), "timestamp": bill['bill']['document']['receipt']['dateTime'] } return make_response(response, 200)