def edit_item(item_name): form = MyForm() item = Item.query.filter_by(name=item_name).one() user_id = login_session['user_id'] if item.user_id != user_id: error = "You don't have the permission to do so." url = url_for('show_item', category_name=item.category.name, item_name=item.name) return render_template('prompt.html', prompt=error, url=url), 401 if form.validate_on_submit(): item.name = form.name.data item.description = form.description.data item.category_name = form.category.data db.session.add(item) db.session.commit() flash("The item was successfully edited.") return redirect(url_for('homepage')) if request.method == 'GET': form.name.data = item.name form.description.data = item.description form.category.data = item.category.name else: if not (form.name.data and form.description.data): flash("You have to fill name and description about the item.") else: flash("Name is only allowed to have letters and spaces.") return render_template('add_or_edit_item.html', item=item, form=form)
def contact(): myform = MyForm() if request.method == 'POST': if myform.validate_on_submit(): # Note the difference when retrieving form data using Flask-WTF # Here we use myform.firstname.data instead of request.form['firstname'] firstname = myform.firstname.data lastname = myform.lastname.data email = myform.email.data subject = myform.subject.data message = myform.message.data msg = Message(subject, sender=(firstname + ' ' + lastname, email), recipients=["*****@*****.**"]) msg.body = message mail.send(msg) flash('You have successfully filled out the form', 'success') return redirect(url_for("home")) #flash_errors(myform) """Render website's contact page.""" return render_template('contact.html', form=myform)
def add_item(): form = MyForm() if form.validate_on_submit(): name = form.name.data description = form.description.data category_name = form.category.data try: item = Item.query.filter_by(name=name).one() flash("The item already exists.") return render_template('add_or_edit_item.html', add=True, form=form) except NoResultFound: category = Category.query.\ filter_by(name=category_name).\ one() user = User.query.filter_by(id=login_session['user_id']).one() new_item = Item(name=name, description=description, category=category, user=user) db.session.add(new_item) db.session.commit() flash("The new item was successfully added.") return redirect(url_for('homepage')) if request.method == "POST": if not (form.name.data and form.description.data): flash("You have to fill name and description about the item.") else: flash("Name is only allowed to have letters and spaces.") return render_template('add_or_edit_item.html', add=True, form=form)
def index(): form = MyForm() if request.method == 'POST': if form.validate_on_submit(): country = request.form['country'] return redirect(url_for('get_day', country=country)) return render_template('index.html', form=form)
def contact(): form = MyForm() if form.validate_on_submit() and request.methon == "POST": msg = Message(form.subject.data, sender = (form.name.data, form.address.data) ,recipients =[""]) msg.body = form.message.data mail.send(msg) flash("Message was sucessfully sent") return redirect(url_for('/')) return render_template('contact.html', form=form)
def data_form_bd(): potsoma = 0 print('entrou readbd') form = MyForm() if form.validate_on_submit(): print('entrou no if do form') data_inicio = form.data_inicio.data data_fim = form.data_fim.data hora_inicio = form.hora_inicio hora_final = form.hora_final dias = abs((data_fim - data_inicio).days) tempo = int(dias) * (60 * 12 * 24) print('SUBMIT') print(data_inicio) print(data_fim) print(dias) try: conn = psycopg2.connectcon = psycopg2.connect(host='localhost', database='teste', user='******', password='******') cur = conn.cursor() print('BANCO CONECTADO!') except (Exception, psycopg2.Error) as error: print("Error while connecting to PostgreSQL", error) finally: conn = psycopg2.connect(host='localhost', database='teste', user='******', password='******') cur = conn.cursor() cur.execute( "select potencia FROM consumo WHERE (data_event BETWEEN %s AND %s)", (data_inicio, data_fim)) data_dif = cur.fetchall() #print(data_dif) cur.close() conn.close() vet = [] for i in data_dif: a = str(i).strip("('").strip("')',") b = float(a) vet.append(b) potsoma = sum(vet) potsoma = round(potsoma, 3) potsoma = potsoma / tempo print('potsoma= ', potsoma) @socketio.on('potsoma2') def enviapotbd(pot2): print('entrei na funcao envia') print(pot2) emit('potsoma2', potsoma) else: print('FALHA NA VALIDACAO DO FORMULARIO!') return render_template('grafico.html', form=form)
def index(): form = MyForm() if form.validate_on_submit(): results = { 'email' : form.email.data, 'password' : form.password.data, 'freeform' : form.freeform.data, 'radios' : form.radios.data, 'selects' : form.selects.data } return render_template('results.html', **results) return render_template('index.html', form=form)
def contact(): form = MyForm() if form.validate_on_submit(): person_name = form.name.data person_email = form.email_address.data person_subject = form.subject.data person_msg = form.textarea.data msg = Message(person_subject, sender=(person_name, person_email), recipients=['*****@*****.**']) msg.body = person_msg flash('Message sent successfuly') return redirect(url_for('home')) return render_template('contact.html', form=form)
def contact(): cform = MyForm() if request.method == 'POST': if cform.validate_on_submit(): name = cform.name.data email = cform.email.data subject = cform.subject.data message = cform.message.data msg = Message(subject, sender=(name, email), recipients=["*****@*****.**"]) msg.body = message mail.send(msg) flash('Message Sent successfully', 'success') return redirect(url_for('home')) """Render the website's contact page.""" return render_template('contact.html', form=cform)
def login(): error = None form = MyForm() if request.method == 'POST': cur = mysql.connection.cursor() uid = request.form['uname'] password = request.form['psw'] if len(uid) in range(9, 12) and uid[:4] in ['6200', '9780']: try: user = cur.execute("SELECT COUNT(1) FROM player WHERE user_id = %s;", [uid]) if cur.fetchone()[0]: cur.execute("SELECT password FROM player WHERE user_id = %s;", [uid]) # FETCH THE PASSWORd for row in cur.fetchall(): if bool(re.match(str(row[0]), str(password))): #check_password_hash(spass, password): flash('welcome student ', uid) session['logged_in'] = True session['user'] = uid session['usertype'] = 'student' return redirect(url_for('home', uid=uid)) else: flash("Wrong password, Try again") return redirect(url_for("login")) else: flash('User does not exist. Please contact your lecturer') return redirect(url_for("login")) except ValueError: flash('Format was wrong, Enter again') return redirect(url_for("login")) elif re.match('^(1000)\d{4}', uid): print 'lecturer' try: user = cur.execute('SELECT COUNT(1) from lecturer where lect_id = %s;', [uid]) if cur.fetchone()[0]: cur.execute("SELECT password FROM lecturer WHERE lect_id = %s;", [uid]) # FETCH THE HASHED PASSWORD for row in cur.fetchall(): if bool(re.match(str(row[0]), str(password))): # check_password_hash(lpass, password): session['logged_in']= True session['user'] = uid session['usertype'] = 'lecturer' return render_template('lecthome.html', lecturer = user) else: flash("Wrong password") return redirect(url_for("login")) else: flash('User does not exist. Please contact admin') return redirect(url_for("login")) except ValueError: flash('Error') return redirect(url_for("login")) flash('Format was wrong, Enter again') return redirect(url_for("login")) return render_template('login.html', form = form)
def profile(): """Should be able to view profile""" form = MyForm() if request.method == 'POST' and form.validate(): userid = genrateid(form.fname.data, form.lname.data) created_on = timenow() photo = form.photo.data filename = secure_filename(photo.filename) photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) photo = photo.filename users = User(userid, form.fname.data, form.lname.data, form.sex.data, form.email.data, form.address.data, form.bio.data, photo, created_on) db.session.add(users) db.session.commit() flash('You have been successfully added!') return redirect(url_for('allusers')) return render_template('profile.html', form=form)
def add_person(): form = MyForm() if request.method == "POST": # print(form.data['status']) # print(form.data['statusPro']) # print(form.data['statusPur']) print("增加人员: ") user = NewUser() user.name = request.form["name"] authority = form.data['status'] + "" + form.data[ 'statusPro'] + "" + form.data['statusPur'] user.authority = authority print(user.name, user.pwd, user.authority) cc_add_account(user.name, user.pwd, user.authority) add_message = "添加成功" return render_template('add_person.html', add_message=add_message, form=form) return render_template('add_person.html', form=form)
def submit(): form = MyForm() if form.validate_on_submit(): session['file_contents'] = form.name.data return redirect('/analysis') return render_template('submit.html', form=form)
def home(): global suffix_gen, counter, first_enter, server_suffix suffix = "uninitial" form = MyForm() # checks if url from form is legal if form.validate() == False: if not first_enter and form.long_url._value != '': flash('Illegal URL, try again') first_enter = False return render_template('home.html', form=form) else: try: url = request.form['long_url'] with sql.connect('urls_database.db') as con: cur = con.cursor() cur.execute( "SELECT * FROM urls WHERE long_url='{}'".format(url)) rec = cur.fetchone() # for bonus task 1 cur.execute( "INSERT INTO requests (request_time, long_url) VALUES (datetime('now'),'{}')" .format(url)) if rec is not None: # long_url exists suffix = rec[1] else: # url doesn't in db yet try: while True: suffix = tuple2string(next(suffix_gen)) # verify that suffix is unique if suffix in server_suffix: continue if cur.execute( "SELECT * FROM urls WHERE url_suffix='{}'". format(suffix)).fetchone() is None: break except StopIteration: counter += 1 suffix_gen = product(chars, repeat=counter) while True: suffix = tuple2string(next(suffix_gen)) if suffix in server_suffix: continue # verify that suffix is unique if cur.execute( "SELECT * FROM urls WHERE url_suffix='{}'". format(suffix)).fetchone() is None: break cur.execute( "INSERT INTO urls (long_url, url_suffix) VALUES ('{}','{}')" .format(url, suffix)) con.commit() except Exception as e: con.rollback() return "error: {}".format(e) finally: first_enter = True con.close() return redirect('http://localhost:5000/result={}'.format(suffix))