def login(): if request.method == 'POST': #get form fields username = request.form['username'] password_candidate = request.form['password'] result = Users.query.filter_by(username=username).first() if result: if sha256_crypt.verify(password_candidate, result.password): session['logged_in'] = True session['username'] = username flash('You are now logged in', 'success') return redirect(url_for('dashboard')) else: error = 'Invalid Login' return template('login.html', error=error) else: error = 'Username Not Found' return template('login.html', error=error) return template("login.html")
def approveUser(ID, accept): if not ObjectId.is_valid(ID): return False if ID == str(session['user']['_id']): return False result = db.users.update_one({'_id' : ObjectId(ID), 'confirmed' : True, 'clinic' : session['user']['clinic']}, {'$set' : {'approved' : accept}}) if result.modified_count == 1 or accept == False: info = db.users.find_one({'_id' : ObjectId(ID)}) if not info: return False #cover all of our bases if accept: userMsg = Message('Account Approved', #app title sender = ('Example Administrator', '*****@*****.**'), recipients = [(info['first'] + ' ' + info['last'], info['email'])]) userMsg.body = template('finalUser.txt', user = info, accept = True) userMsg.html = template('finalUser.html', user = info, accept = True) else: userMsg = Message('Account Removed', #app title sender = ('Example Administrator', '*****@*****.**'), recipients = [(info['first'] + ' ' + info['last'], info['email'])]) userMsg.body = template('finalUser.txt', user = info, accept = False) userMsg.html = template('finalUser.html', user = info, accept = False) deletion = db.users.delete_one({'_id' : ObjectId(ID)}) if deletion.deleted_count == 0: return False mail.send(userMsg) return True #something messed up return False
def login(): if request.method == 'POST': #get form fields username = request.form['username'] password_candidate = request.form['password'] #connect the database # connection = engine.connect() #fetch the row result = Users.query.filter_by(username=username).first() # stmt = select([users]).where(users.columns.username == username) # result = connection.execute(stmt).fetchone() # connection.close() if result: if sha256_crypt.verify(password_candidate, result.password): session['logged_in'] = True session['username'] = username flash('You are now logged in', 'success') return redirect(url_for('dashboard')) else: error = 'Invalid Login' return template('login.html', error=error) else: error = 'Username Not Found' return template('login.html', error=error) return template("login.html")
def dashboard(): # Connect the database # connection = engine.connect() # Get articles article_results = Articles.query.all() # stmt = select([articles]) # result_proxy = connection.execute(stmt) # article_results = result_proxy.fetchall() practice_results = Practices.query.all() # stmt = select([practices]) # result_proxy = connection.execute(stmt) # practice_results = result_proxy.fetchall() # Close connection # connection.close() if article_results and practice_results: return template('dashboard.html', articles=article_results, practices=practice_results) elif article_results and not practice_results: msg = 'No Practices Found' return template('dashboard.html', articles=article_results, msg=msg) elif not article_results and practice_results: msg = 'No Articles Found' return template('dashboard.html', practices=practice_results, msg=msg) else: msg = 'No Articles And Practices Found' return template('dashboard.html', msg=msg)
def feedback(self): from werkzeug.datastructures import CombinedMultiDict form = FeedbackForm(CombinedMultiDict((request.files, request.form))) if request.method == "GET": return template("support/feedback.html.j2", form=form) elif request.method == "POST": if not form.validate_on_submit(): return template("support/feedback.html.j2", form=form) attachments = [] if form.feedback_file.data: attachments = [form.feedback_file.data] MailSender().send_email( subject="[ketocalc] [{}]".format(form.option.data), sender="ketocalc", recipient_mails=["*****@*****.**"], text_body="Message: {}\n Send by: {} [user: {}]".format( form.message.data, form.email.data, current_user.username ), html_body=None, attachments=attachments, ) flash("Vaše připomínka byla zaslána na vyšší místa.", "success") return redirect(url_for("DashboardView:index"))
def post(): video_id = request.args.get("video") video = find_by_id(video_id)[0] tags = video.get("tags") if tags is None: return template('post.html', video=video) else: tagstring = tags_to_tagstring(tags) return template('post.html', video=video, tagstring=tagstring)
def gutenberg(): book_results = Books.query.all() if book_results: return template('gutenberg.html', books=book_results) else: msg = 'No Books Found' return template('gutenberg.html', msg=msg)
def translated(book_id): result = Books.query.filter_by(id=book_id).first() if result: return template('translated.html', result=result) else: msg = 'No Books Found' return template('translated.html', msg=msg)
def dashboard(): book_results = Books.query.all() if book_results: return template('dashboard.html', books=book_results) else: msg = 'No Books Found' return template('dashboard.html', msg=msg)
def createUser(info, group = None, code = None): userExist = db.users.find_one({'email' : info['email']}) if userExist: return False #user previously exists if not code: #new group must be created vaultID = vault.createClinic(group) if not vaultID: return False newClinic = db.clinics.insert_one({ 'name' : group, 'vault' : vaultID}) if not newClinic: return False code = str(newClinic.inserted_id) #you created it info['owner'] = True info['approved'] = True else: #verify that desired clinic exists if not ObjectId.is_valid(code): return false oldClinic = db.clinics.find_one({ '_id' : ObjectId(code)}) if not oldClinic: return False #joining something info['owner'] = False info['approved'] = False info['confirmed'] = False info['clinic'] = ObjectId(code) hash = pbkdf2_sha256.encrypt(info['password'], rounds = 100000, salt_size = 10) info['password'] = hash #store password in an encrypted, salted form user = db.users.insert_one(info) if not user: return False userMsg = Message('Your ' + title + ' Account', #app title sender = ('Example Administrator', '*****@*****.**'), recipients = [(info['first'] + ' ' + info['last'], info['email'])]) userMsg.body = template('newUser.txt', user = info, ID = user.inserted_id) userMsg.html = template('newUser.html', user = info, ID = user.inserted_id) mail.send(userMsg) if not info['owner']: owner = db.users.find_one({'clinic' : ObjectId(code)}) appMsg = Message('Signup Notification', #approval queue sender = ('Example Administrator', '*****@*****.**'), recipients = [(owner['first'] + ' ' + owner['last'], owner['email'])]) appMsg.body = template('approveUser.txt', owner = owner, user = info) appMsg.html = template('approveUser.html', owner = owner, user = info) mail.send(appMsg) #email validation? return True
def admin(): if "logged_in" in session and session["logged_in"] != True: return template("index.html") else: with connection.cursor() as cursor: sql = "SELECT * FROM users" cursor.execute(sql) results = cursor.fetchall() nafn = session.get("nafn") print(results) print(nafn) return template("admin.html", results=results, nafn=nafn)
def article(article_url): #fetch the row result = Articles.query.filter_by(url=article_url).first() # stmt = select([articles]).where(articles.columns.id == article_id) # result_proxy = connection.execute(stmt) # result = result_proxy.fetchone() # connection.close() if result: return template('article.html', article=result) else: msg = 'No Articles Found' return template('article.html', msg=msg)
def pdf(): option = request.args.get('option') initial_date = datetime.datetime.strptime(request.args.get('initial_date'), "%Y-%m-%d") final_date = datetime.datetime.strptime(request.args.get('final_date'), "%Y-%m-%d") final_date = final_date + datetime.timedelta(days=1) initialDate = initial_date.strftime("%d/%m/%Y") finalDate = final_date.strftime("%d/%m/%Y") if option == "user": user = request.args.get('user') title = u"Lista de domínios acessados pelo cliente " + user title2 = u"Período: " + initialDate + " - " + finalDate fields = (u"URL", u"Data", u"Hora", u"Bytes", u"Duração", u"Resultado", u"MIME") values = Request.getDomainsByClientPDF(user, initial_date, final_date) tmplt = template("PDF.jinja2", values=values, title=title, title2=title2, fields=fields) elif option == "domain": domain = request.args.get('domain') title = u"Lista de usuários que acessaram o domínio " + domain title2 = u"Período: " + initialDate + " - " + finalDate fields = (u"Cliente", u"Data", u"Hora", u"Bytes", u"Duração", u"URL", u"Resultado", u"MIME") values = Request.getClientsByDomainPDF(domain, initial_date, final_date) tmplt = template("PDF.jinja2", values=values, title=title, title2=title2, fields=fields) elif option == "comunication": user = request.args.get('user') domain = request.args.get('domain') title = u"Comunicação entre o cliente " + user + u" e o domínio " + domain title2 = u"Período: " + initialDate + " - " + finalDate fields = (u"URL", u"Data", u"Hora", u"Bytes", u"Duração", u"Método", u"Resultado", u"MIME") values = Request.getComunicationDomainClientPDF(domain, user, initial_date, final_date) tmplt = template("PDF.jinja2", values=values, title=title, title2=title2, fields=fields) else: title = u"Requisições negadas" title2 = u"Período: " + initialDate + " - " + finalDate fields = (u"Domínio", u"Cliente", u"Data", u"Hora", u"Resultado") values = Request.getDeniedPDF(initial_date, final_date) print(values) tmplt = template("PDF.jinja2", values=values, title=title, title2=title2, fields=fields) pdf = pdfkit.from_string(tmplt, False) response = Response(response=pdf, status=200, mimetype="application/pdf") # write to PDF return response
def list(self, list_name): filter_manager = GeneViewFilters() widgets = make_widgets(filter_manager, True) return template( 'gene/list.html', list_name=list_name, widgets=widgets, filter_manager=filter_manager )
def autocomplete_proteins(self, limit=20): """Autocompletion API for search Advanced Proteins Search.""" filter_manager = SearchViewFilters() # TODO: implement on client side pagination? features = filter_manager.get_value('Feature.name') query = filter_manager.get_value('Search.query') content = {} if query: entries = search_proteins(query, limit, filter_manager, features) content = { 'query': query, 'results': [{ 'value': gene.name, 'html': template('search/results/gene.html', gene=gene) } for gene in entries], } from views.filters import FiltersData response = { 'content': content, 'filters': FiltersData(filter_manager).to_json() } return jsonify(response)
def add_article(): form = ArticleForm(request.form) if request.method == 'POST' and form.validate(): url = form.url.data chapter = form.chapter.data title = form.title.data body = form.body.data #insert the data result = Articles(url=url, chapter=chapter, title=title, body=body) db.session.add(result) db.session.commit() # stmt = insert(articles).values(chapter=chapter, title=title, body=body) # result_proxy = connection.execute(stmt) # Commit to DB # mysql.connection.commit() #Close connection # connection.close() flash('Article Created', 'success') return redirect(url_for('dashboard')) return template('add_article.html', form=form)
def stod(nafn,company): listi = stadir()[company] for i in listi: if i["nafn"] == nafn: dic = i break return template("stod.html",nafn=dic["nafn"],lat=dic["geo"]["lat"],lon=dic["geo"]["lon"],company = company, bensin=dic["bensin"],diesel=dic["diesel"])
def home(): # Importaði render_template sem "template" fyrir þægindi karfa = [] fjoldi = 0 if "karfa" in session: karfa = session["karfa"] fjoldi = len(karfa) return template("index.html", vorur=vorur, fjoldi=fjoldi)
def edit_book(id): result = Books.query.filter_by(id=id).first() # Get form form = BookForm(request.form) # Populate article form fields form.url.data = result.url form.title.data = result.title form.author.data = result.author form.body.data = result.body if request.method == 'POST' and form.validate(): url = request.form['url'] title = request.form['title'] author = request.form['author'] body = request.form['body'] # Execute book = Books.query.filter_by(id=id).first() book.url = url book.title = title book.author = author book.body = body db.session.add(book) db.session.commit() flash('Book Updated', 'success') return redirect(url_for('dashboard')) return template('edit_book.html', form=form)
def dashboard(): active_user = current_user.name start_time = time.time() if 'monthVisit' in request.form.keys(): monthYear = request.form['monthVisit'] else: monthYear = None now = datetime.datetime.now() currentYear = now.year currentMonth = now.month if monthYear is not None: pieces = monthYear.split("-") month = int(pieces[1]) year = int(pieces[0]) else: month = currentMonth year = currentYear initial_year = datetime.datetime(year,1,1) final_year = datetime.datetime(year+1,1,1) initial_date = datetime.datetime(year,month,1) print(initial_date) if month < 12: final_date = datetime.datetime(year,month+1,1) else: final_date = datetime.datetime(year+1,1,1) domainDoughnutChart = Request.getTopDomainDoughnut(initial_date, final_date) print("pós graph1: " + str(time.time() - start_time)) userDoughnutChart = Request.getTopUsersDoughnut(initial_date, final_date) print ("pós graph2: " + str(time.time() - start_time)) monthChart = Request.getBytesRequestsByMonth(initial_year, final_year) print ("pós graph3: " + str(time.time() - start_time)) dailyChart = Request.getBytesRequestsByDay(initial_date, final_date) print("pós graph4: " + str(time.time() - start_time)) pieChart = VW_content_types.getTypesChart(year, month) print ("pós graph5: " + str(time.time() - start_time)) resultRequestChart = VW_result_codes.getResultsChart(year, month) print ("pós graph6: " + str(time.time() - start_time)) colors = ["rgba(39, 44, 51,1)","rgba(39, 44, 51,0.9)","rgba(39, 44, 51,0.8)","rgba(39, 44, 51,0.7)","rgba(39, 44, 51,0.6)","rgba(39, 44, 51,0.5)","rgba(39, 44, 51,0.4)","rgba(39, 44, 51,0.3)","rgba(39, 44, 51,0.2)","rgba(39, 44, 51,0.1)"] colors2 = ["rgba(238, 108, 77,1)","rgba(238, 108, 77,0.9)","rgba(238, 108, 77,0.8)","rgba(238, 108, 77,0.7)","rgba(238, 108, 77,0.6)","rgba(238, 108, 77,0.5)","rgba(238, 108, 77,0.4)","rgba(238, 108, 77,0.3)","rgba(238, 108, 77,0.2)","rgba(238, 108, 77,0.1)"] colors3 = ["#E5FFDE", "#634B66", "#BBCBCB", "#9590A8", "#FFB997", "#7C898B", "#D6DBB2", "#759FBC", "#FFBA49", "#EF5B5B"] params = {'active_user': active_user, 'domaindatadoughnut': domainDoughnutChart, 'userDoughnutChart': userDoughnutChart, 'datapie': pieChart, 'dailyChart':dailyChart, 'monthChart':monthChart, 'resultRequestChart':resultRequestChart, 'colors': colors, 'colors2': colors2, 'colors3': colors3, 'valuesToQuery':monthYear, 'month': month, 'year': year} return template ('welcome.jinja2', **params)
def loginsite(): if "logged_in" in session and session["logged_in"] == True: redirect("/") if request.method == "POST": if "logged_in" in session and session["logged_in"]: return "þú ert logged in núþegar!" else: if request.method == "POST": name = request.form["name"] password = request.form["password"] sql = f"SELECT * FROM users WHERE user_name = '{name}' AND user_password = '******'" try: with connection.cursor() as cursor: cursor.execute(sql) results = cursor.fetchone() if results == None: return "rangt lykilorð eða notendanafn" else: session["logged_in"] = True session["nafn"] = results["user_name"] return redirect(url_for("home")) except pymysql.OperationalError: return "Database tenging ekki náð" # Þetta lætur þig vita ef eitthvað er að tengingunni else: return template("login.html")
def create_contact_form(): args = request.args pass_args = ['feature', 'title'] return Markup(template( 'cms/contact_form.html', **{key: args.get(key, '') for key in pass_args} ))
def show(self, refseq, position, alt): protein = Protein.query.filter_by(refseq=refseq).first_or_404() """ mutation = Mutation.query.filter_by( protein=protein, position=int(position), alt=alt ).first_or_404() """ mutation, _ = get_or_create( Mutation, protein=protein, # setting id directly is easier than forcing update outside session protein_id=protein.id, position=int(position), alt=alt ) datasets, user_datasets = prepare_datasets(mutation) return template( 'mutation/show.html', mutation=mutation, protein=protein, datasets=datasets, user_datasets=user_datasets )
def resetPassword(email): user = db.users.find_one({'email' : email}) if not user: return False #bad email password = randomWord(10) hash = pbkdf2_sha256.encrypt(password, rounds = 100000, salt_size = 10) result = db.users.update_one({'email' : email}, {'$set' : {'password' : hash}}) if result.modified_count != 1: return False passMsg = Message('Password Reset', #app title sender = ('Example Administrator', '*****@*****.**'), recipients = [(user['first'] + ' ' + user['last'], user['email'])]) passMsg.body = template('resetPass.txt', user = user, password = password) passMsg.html = template('resetPass.html', user = user, password = password) mail.send(passMsg) return True
def frettirB(): frettir = frett cnt = 0; i = 4; for i in frett: cnt += 1 end return template("frettir.tpl", frett= frettir[id])
def karfa(): karfa = [] summa = 0 if "karfa" in session: karfa = session["karfa"] fjoldi = len(karfa) # Fj vara í körfu for i in karfa: summa += int(i[3]) print(karfa) return template("karfa.html", karfa=karfa, tom=False, fjoldi=fjoldi, summa=summa) else: return template("karfa.html", karfa=karfa, tom=True)
def practice(practice_id): # connection = engine.connect() result = Practices.query.filter_by(id=practice_id).first() # stmt = select([practices]).where(practices.columns.id == practice_id) # result_proxy = connection.execute(stmt) # result = result_proxy.fetchone() # connection.close() if request.method == 'POST': #get form fields choice = request.form['choice'] return template("practice.html", practice=result, choice=choice) return template("practice.html", practice=result)
def oniichan_index(): """ serve index page """ if util.is_logged_in(): with util.get_session_user_or_abort(404) as user: return redirect(user.url()) return template("index.html", title="oniichan engine")
def login(): if current_user.is_authenticated: return redirect("/welcome") username = request.form['username'] password = request.form['password'] print("user", username, "password", password) user_login = User.sign_in(username, password) if user_login: login_user(user_login) return redirect('/welcome') elif user_login == False: params = {"username":username,"password":"","login_error":u"Senha incorreta. Tente novamente."} return template('login.jinja2', **params) else: params = {"username":username,"password":"","login_error":u"Usuário não cadastrado em sistema."} return template('login.jinja2', **params)
def chapter(chapter_id): #connect the database # connection = engine.connect() #fetch the row results = Articles.query.filter_by(chapter=chapter_id).all() # stmt = select([articles]).where(articles.columns.chapter == chapter_id) # result_proxy = connection.execute(stmt) # results = result_proxy.fetchall() # Close connection # connection.close() if results: return template('chapter.html', articles=results) else: msg = 'No Articles Found' return template('chapter.html', msg=msg)
def user_domain(client): active_user = current_user.name client = cgi.escape(client) values = Request.getDomainsByClient(client) title = u"Domínios acessados pelo usuário " + str(client) fields = (u"Posição", u"Domínio", "Bytes", u"Duração", u"Requisições") return template ('domainsByClient.jinja2', active_user=active_user, values=values, title=title, fields=fields, client=client)
def domain_user(domain): active_user = current_user.name domain = cgi.escape(domain) values = Request.getClientsByDomain(domain) title = u"Usuários que acessaram o domínio " + str(domain) fields = (u"Posição", u"Cliente", "KBytes", u"Duração (s)", u"Requisições") return template ('clientsByDomain.jinja2', active_user=active_user, values=values, title=title, fields=fields, domain=domain)
def representation_data(self, refseq): protein, filter_manager = self.get_protein_and_manager(refseq) data = SequenceRepresentation(protein, filter_manager).as_json() data['mutation_table'] = template('protein/mutation_table.html', mutations=data['mutations'], filters=filter_manager, protein=protein, value_type=data['value_type']) data['tracks'] = template('protein/tracks.html', tracks=data['tracks']) response = { 'content': data, 'filters': ProteinFiltersData(filter_manager, protein).to_json() } return jsonify(response)
def dashboard(): #user is logged out now if 'user' not in session: return redirect('/') patients = helpers.getPatientData() doctors = [i for i in helpers.getDoctorData() if i['email'] != session['user']['email']] #you approved = [i for i in doctors if i['approved']] pending = [i for i in doctors if not i['approved']] return template('dashboard.html', #filled in below clinic = session['user']['clinicName'], code = session['user']['clinicCode'], first = session['user']['first'], owner = session['user']['owner'], last = session['user']['last'], patients = patients, approved = approved, pending = pending, title = title)
def index(): FK.template(index.hmtl)
def index(name='Earth'): return template('index.html',name=name)
def index(): return template("index.html")
def welcome_page(): return template("welcome.html")
def wine_list(): return template("wine-list.html")
def wine_details(): return template("wine-details.html")
def index(): if 'user' in session: #logged in return redirect('/dashboard') return template('index.html', title = title)
def drag(): return template('drag.html')
def confirmation(ID): worked, ownership, clinic = helpers.confirmUser(ID) return template('confirmation.html', title = title, worked = worked, ownership = ownership, clinic = clinic,)
def home(): return template('demo.html')
def index(): return template('index.html')
def jsonp(): return template('jsonp.html')