def place_order(): user_id = flask_jwt_extended.get_jwt_identity() cart_list = db_session.query( models.Cart).filter(models.Cart.user_id == user_id).all() try: address_id = request.form["address"] created_at = datetime.datetime.now() for cart in cart_list: create_order = models.Orders( order_id=address_id, user_id=user_id, product_id=cart.product_id, status='pending', created_at=created_at, ) db_session.add(create_order) db_session.flush() except Exception as e: print(e) return redirect(url_for("view.cart")) try: db_session.commit() except Exception as e: print(e) db_session.rollback() return redirect(url_for("view.cart")) return redirect(url_for("view.orders"))
def registration(username, password, name, surname): hashed_password = hashlib.sha512(password.encode('utf-8')).hexdigest() u = User(username, hashed_password, name, surname) db_session.add(u) db_session.commit() return u
def cli(ctx): """Data ingestion of all covid-19 va data""" ctx.log("Ingesting Covid-19 Virginia Cases...") with open("data/VDH-COVID-19-PublicUseDataset-Cases.csv", newline="", encoding="utf-8-sig") as csvfile: reader = csv.DictReader(csvfile) for row in reader: report_date = row.get("Report Date") fips = capwords(row.get("FIPS", "").lower()) locality = row.get("Locality", "").upper() health_district = capwords(row.get("Health District", "").lower()) total_cases = capwords(row.get("Total Cases", "").lower()) db_session.add( VaCovid( report_date=report_date, fips=fips, locality=locality, health_district=health_district, total_cases=total_cases, )) db_session.commit() ctx.log("Done...")
def start(message): user = User.query.filter_by(telegram_id=message.from_user.id).first() if user is None: user = User(telegram_id=message.from_user.id, username=message.from_user.username) db_session.add(user) db_session.commit() bot.send_message(message.chat.id, constants.MESSAGE_HELLO)
def add_to_cart(product_id): user_id = flask_jwt_extended.get_jwt_identity() try: if product_id != "0": add_to_cart = models.Cart(user_id=user_id, product_id=product_id) db_session.add(add_to_cart) db_session.flush() db_session.commit() except Exception as e: print(e) return redirect(url_for("view.cart"))
def fetch_car(): json_data = request.json make = json_data.get('make') model = json_data.get('model') if not make: return {'error': 'Make is required'}, 400 elif not model: return {'error': 'Model is required'}, 400 make, model = make.lower(), model.lower() url = GET_MODELS_FOR_MAKE_URL.format(make=make) with requests.get(url) as resp: status_code = resp.status_code if status_code != 200: return { 'error': f'API error, response status code {status_code}' }, 400 json_resp = resp.json() data = json_resp['Results'] df = pd.DataFrame(data) result_df = df.loc[df['Model_Name'].str.lower() == model] if len(result_df) == 0: error_message = "Model doesn't exist" return {'error': error_message}, 400 result_data = result_df.iloc[0] make = result_data.Make_Name model = result_data.Model_Name try: car = Car(make=make, model=model) db_session.add(car) db_session.commit() logger.info(f'Inserted {make} {model}') return {'status': 'OK'} except sqlalchemy.exc.IntegrityError: error_message = 'Make and Model already exist in the Database' logger.error(error_message) return {'error': error_message}, 400 except Exception as e: logger.error(e, exc_info=True) return {'error': str(e)}, 500
def save(self): """ 保存对象到数据库 :return: """ try: db_session.add(self) db_session.commit() except: db_session.rollback() raise finally: db_session.close() model_saved.send(app._get_current_object()) return self
def add_score(): form = NewScoreForm() rooms = Room.query.all() form.room_id.choices = [(str(r.id), r.room_name) for r in rooms] if request.method == 'POST': if form.validate_on_submit(): visited_room = VisitedRooms(form.room_id.data, current_user.id, form.date.data, form.escape_time.data) db_session.add(visited_room) db_session.commit() return redirect(url_for('score_view.score_list')) else: if 'date' in form.errors: add_error(form.date, 'Zły format daty.') elif 'escape_time' in form.errors: add_error(form.escape_time, 'Zły format czasu ucieczki.') return render_template('add_score.html', is_logged=current_user.is_authenticated, user=current_user, form=form)
def add_address(): try: user_id = flask_jwt_extended.get_jwt_identity() address_name = request.form["address_name"] first_name = request.form["first_name"] last_name = request.form["last_name"] email = request.form["email"] phone_number = request.form["phone_number"] address = request.form["address"] country = request.form["country"] state = request.form["state"] city = request.form["city"] postal_code = request.form["postal_code"] add_address = models.UserAddress(address_name=address_name, user_id=user_id, first_name=first_name, last_name=last_name, email=email, phone_number=phone_number, address=address, country=country, state=state, city=city, postal_code=postal_code) db_session.add(add_address) db_session.flush() except Exception as e: print(e) return redirect(url_for("view.checkout")) try: db_session.commit() address_id = add_address.id except Exception as e: print(e) db_session.rollback() return redirect(url_for("view.checkout")) return redirect(url_for("view.cart"))
def registration(): try: name = request.form["name"] email = request.form["email"] password_hash = request.form["password"] user_type_id = 1 created_at = datetime.datetime.now() create_user = models.User( name=name, email=email, password_hash=ph.hash(password_hash), email_validated=False, user_type_id=user_type_id, created_at=created_at, ) db_session.add(create_user) db_session.flush() except Exception as e: print(e) print("failed to create user") return redirect(url_for("view.register")) try: db_session.commit() res = verification_mail.send_mail(create_user.id, create_user.name, create_user.email, email_type="new-user") if not res: print("invalid email or server failed to send verification mail") return redirect(url_for("view.register")) return redirect(url_for("view.user")) except Exception as e: print(e) print("failed to store user in database") db_session.rollback() return redirect(url_for("view.register"))
def create_configuration(args): try: data = bytes_to_json(args) columns = get_columns(data["sql_query"]) config = DagRunConfig(dag_id=int(data["dag_id"]), sql_query=data["sql_query"], db_connector=data["db_connector"], filename=data["filename"], columns=columns) db_session.add(config) db_session.commit() return { "status": True, "code": 200, "message": "Configuration successfully created" } except: raise return { "status": False, "code": 500, "message": "Configuration not created" }
def send_mail(id, handle, email, email_type): try: the_token = ph.hash(str(handle))[35:] tomorrow = datetime.now() + timedelta(days=1) if email_type == "new-user": print("set new-user token") validation_token = models.ValidationToken(token=the_token, created_at=tomorrow, user_id=id) db_session.add(validation_token) if email_type == "reset-user": print("set reset-user token") user = db_session.query(models.ValidationToken).filter(models.ValidationToken.user_id == id).one_or_none() user.created_at = tomorrow user.token=the_token db_session.commit() except Exception as e: print(e) print("[ ERROR ] failed to add validation_token") return False try: print("sending verification email...") the_token = the_token.replace("/", "_") if email_type == "new-user": pass html = f""" <html> <body> <a href="http://127.0.0.1:5000/validate_user/{the_token}"> click here </a> </body> </html>""" html = f""" <!DOCTYPE html> <html> <body> <div style="background-color:#eee;padding:10px 20px;"> <h2 style="font-family:Georgia, 'Times New Roman', Times, serif;color#454349;">FlyBuy Verification</h2> </div> <div style="padding:20px 0px"> <a href="http://127.0.0.1:5000/validate_user/{the_token}"> click here </a> </div> </div> </body> </html> """ port = 465 # For SSL sender_email = "*****@*****.**" password = "******" message = MIMEMultipart("alternative") message["Subject"] = "User Account Validation" message["From"] = sender_email message["To"] = email part2 = MIMEText(html, "html") message.attach(part2) context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, email, message.as_string()) if email_type == "reset-user": msg = MIMEText(u'<html><body><a href="127.0.0.1:5000/reset_pass/{the_token}">click here</a></body></html>','html') body = f"""Hello, {handle} follow this link to validate your email \n {msg}""" subject = "User Account Validation" except Exception as e: print(e) print("[ ERROR ] Sending Mail failed") return False print("[ SUCCESS ] check your email") return True