def getInnerInfoView(infoid=None): if not session.has_key('UserId'): code = request.args.get('code') agentid = request.args.get('state') if code == None or agentid == None: return render_template('common/error.html', title=u'错误', message=u'无法确认您的身份或者session过期,请刷新页面重试') ret = getPsnInfoByCode(code, agentid) if ret.has_key('UserId'): session['UserId'] = ret['UserId'] else: return render_template('common/error.html', title=u'错误', message=u'无法确认您的身份或者session过期,请刷新页面重试') news = session_inner.query(kfile).filter(kfile.id == infoid).all() if len(news) > 0: newsBodys = convert_result_to_chinese(news, kfile) newsBody = newsBodys[0] if newsBody['fatherid'] in newsFolderExt: newsBody['content'] = u'该栏目的信息请您在PC端登陆内网查看!' else: newsBody = None innerhit = wx_session.query(InnerNews_hits).filter(InnerNews_hits.id == infoid).first() if innerhit == None: innerhit = InnerNews_hits() innerhit.id = infoid innerhit.hits = 1 wx_session.merge(innerhit) else: innerhit.hits += 1 wx_session.merge(innerhit) wx_session.commit() return render_template('weixin/qy/innernewsView.html', newsBody=newsBody, username=session['UserId'], hits=innerhit.hits)
def get(self, tournament_key): #Contextual variables used by all tournament types. context = self.get_context() context['tournament_key'] = tournament_key tournament = actions.get_tournament_by_key(tournament_key) context['num_players'] = str(tournament.num_players) context['tournament'] = tournament admin_list = [] is_a_owner = False if context['user'] is not None: admin_list = [actions.get_user_by_id(admin_key.id()) for admin_key in tournament.admins] owners = [tournament.owner.key().id()] owners.extend([admin.key().id() for admin in admin_list]) is_a_owner = context['user'].key().id() in owners if tournament: if tournament.perms == tournament.PRIVATE and is_a_owner or tournament.perms != tournament.PRIVATE: if tournament.type == models.Tournament.ROUND_ROBIN: #Setup context for Round Robin tournament context['full_page_content'] = True context['round_robin_rounds'] = actions.get_round_robin_rounds(tournament) context['standings'] = actions.get_round_robin_standings(tournament) return render_template('view_round_robin.html', **context) else: #Setup context for bracket-style tournaments context['full_page_content'] = True return render_template('view_tournament.html', **context) return flask.abort(404)
def getVote(schema_id=None, openid=None): if openid == None or openid == '': if session.has_key('openid'): openid = session.get('openid') else: return render_template('vote/error.html', title=u'错误', message=u'无法确认您的微信身份') session['openid'] = openid rs = checkOpenid(openid) psnname = '' mobile = '' bz = '' isregisted = False if rs['resultCode'] == 0: psnname = rs['psnname'] mobile = rs['mobile'] isregisted = True psn_detail = wx_session.query(Vote_psn_detail).filter( and_(Vote_psn_detail.schema_id == schema_id, Vote_psn_detail.openid == openid)).all() if len(psn_detail) != 0: psnname = psn_detail[0].psnname mobile = psn_detail[0].mobile bz = psn_detail[0].bz schema = wx_session.query(Vote_schema).filter_by(id=schema_id).one() if schema == None: return render_template('vote/error.html', title=u'错误', message=u'您选择的投票不存在') items = wx_session.query(Vote_item, Vote_action.item_id).outerjoin(Vote_action, and_(Vote_action.item_id == Vote_item.id, Vote_action.openid == openid)).filter( and_(Vote_item.schema_id == schema.id)).all() return render_template('vote/mobi/vote.html', schema=schema, openid=openid, items=items, psnname=psnname, mobile=mobile, bz=bz, isregisted=isregisted)
def getVoteByQYH(schema_id=None, openid=None): if not session.has_key('UserId'): code = request.args.get('code') agentid = request.args.get('state') if code == None or agentid == None: return render_template('common/error.html', title=u'错误', message=u'无法确认您的身份或者session过期,请刷新页面重试') ret = getPsnInfoByCode(code, agentid) if ret.has_key('UserId'): session['UserId'] = ret['UserId'] else: return render_template('common/error.html', title=u'错误', message=u'无法确认您的身份或者session过期,请刷新页面重试') # session['UserId'] = '105001' psn_detail = wx_session.query(Vote_psn_detail).filter( and_(Vote_psn_detail.schema_id == schema_id, Vote_psn_detail.openid == session['UserId'])).all() bz = '' if len(psn_detail) != 0: bz = psn_detail[0].bz schema = wx_session.query(Vote_schema).filter_by(id=schema_id).one() if schema == None: return render_template('vote/error.html', title=u'错误', message=u'您选择的投票不存在') stmt_ps = wx_session.query(Vote_action.item_id, func.count('*').label("ps")).filter( Vote_action.schema_id == schema_id).group_by(Vote_action.item_id).subquery() items = wx_session.query(Vote_item, Vote_action.item_id, stmt_ps.c.ps).outerjoin(stmt_ps, stmt_ps.c.item_id == Vote_item.id).outerjoin( Vote_action, and_(Vote_action.item_id == Vote_item.id, Vote_action.openid == session[ 'UserId'])).filter( and_(Vote_item.schema_id == schema.id)).all() return render_template('vote/mobi/qy/vote.html', schema=schema, userid=session['UserId'], items=items, bz=bz)
def qa_request(task_id=None): if task_id is None: return render_template('qa.html', request_obj=None) task = db.tasks.find_one({'task_id': int(task_id)}) if task is None: return render_template('qa.html', request_obj=None) html_parser = HTMLParser() hits = task['hits'] requests = [] for hit_id in hits.keys(): hit = db.hits.find_one(ObjectId(hit_id)) unescaped = html_parser.unescape(hit['html']) data = {'fragment': unescaped, 'index': hit_id, 'solved': hits[hit_id]['solved'], 'quality': hits[hit_id]['quality'], 'response': hits[hit_id]['response'], 'task_id': task_id} requests.append(data) request_obj = { 'finished': task['finished'], 'reply':task['reply'] if task['finished'] else '', 'requests': requests} return render_template('qa.html', request_obj = request_obj)
def on_submit(self): if self.band.tracks.count() == 5: raise AjaxException(u'Es dürfen nur maximal 5 Demo-Songs hochgeladen werden.') else: uploaded_files = flask.request.files.getlist("audioFile[]") success = [] fail = [] for uploaded_file in uploaded_files: if self.band.tracks.count() == 5: fail.append(uploaded_file.filename) continue # TODO check file ext track = Track() track.trackname = uploaded_file.filename track.band_id = self.band.id track_filename = str(self.band.id) + '_' + str(uuid4()) + '.' try: track.filename = trackPool.save(uploaded_file, name=track_filename) success.append(uploaded_file.filename) db.session.add(track) db.session.commit() except UploadNotAllowed: fail.append(uploaded_file.filename) return {'track': render_template("track_item.html"), 'check_tab': render_template('check.html'), 'fail': fail, 'success': success}
def catch_all(path): response_info = responses.get(path) method = request.method if not response_info: status_code = 404 response = make_response(render_template('error_404.txt', path=path)) response.headers['Content-Type'] = 'text/plain' elif method not in response_info.keys(): status_code = 405 response = make_response(render_template('error_405.txt', path=path, method=method)) response.headers['Content-Type'] = 'text/plain' else: response_meta = responses[path][method] status_code = response_meta['status_code'] resp = response_meta['response'] if response_meta['response'] else {} response = make_response( json.dumps( resp, indent=2, separators=(',', ':'), sort_keys=True )) response.headers['Content-Type'] = 'application/json' return response, status_code
def reject_booking(bid): b = Booking.objects(id=bid).first() if request.method == 'GET': return render_template('booking_reject.html', booking=b) else: result = b.reject(request.form['reason']) return render_template('booking_reject.html', result=result)
def login_user(self, user_id, password): """ Endpoint representing the transition from the initial dialogue to the main menu. """ if user_id == "" or password == "": # If user_id or password is missing, show the dialogue again with an error message return render_template("initial_dialogue.html", error = "FieldMissing") elif not self.authentication_service_proxy.user_exists(user_id = user_id): # If user_id does not exist, show the dialogue again with an error message return render_template("initial_dialogue.html", error = "WrongPasswordOrUser") else: # User exists, check if the password is correct (in which case a user token string is received user_token = self.authentication_service_proxy.check_user_password(user_id = user_id, password = password) if user_token: # Login successful, save some data in the session object, and go to main menu session["user_id"] = user_id session["user_token"] = user_token # To make sure that the cache is cleared and no case is selected, delete cookie information about case id. session.pop("case_id", None) # Add the user to the case db if it is not already there return self.main_menu_transition() else: # If the wrong password was entered, show the dialogue again with an error message return render_template("initial_dialogue.html", error = "WrongPasswordOrUser")
def rest_passwd(): """ 通过email取回密码 """ if request.method == 'GET': form = RecoverPasswordForm(next=request.args.get('next', None)) else: form = RecoverPasswordForm(next=request.args.get('next', None)) if form.validate_on_submit(): # 获取指定的表单数据 email = request.form.get('email', None) username, new_pwd = UserService.rest_pwd_by_email(email) if username and new_pwd: send_new_pwd(username, email, new_pwd) return render_template("account/rest_passwd_success.html", email=email, username=username, form=form) else: print "error: %s %s" % (username, new_pwd) flash(_("Cause an error"), "failed") elif form.errors: for error_name, error_value in form.errors.iteritems(): print "error: %s %s" % (error_name, error_value) flash(_("Cause an error"), "failed") return render_template("account/rest_passwd.html", form=form)
def handle_foursquare_push(): checkin_info = request.form.getlist('checkin')[0] checkin_json = json.loads(checkin_info) logger.info('Recieved Push', checkin_json) venue_id = checkin_json['venue']['id'] logger.info("Venue ID {}".format(venue_id)) foursquare_user_id = checkin_json['user']['id'] logger.info("User Checkin with id [{}]".format(foursquare_user_id)) if venue_id not in app.config['ALLOWED_VENUES']: logger.info("Venue {} is not registered for this program".format( venue_id)) return render_template('error.html') user = User.query.filter_by( foursquare_id=foursquare_user_id).order_by(desc(User.id)).first() # user = User.query.filter_by(foursquare_id=76462465).first() if not user: logger.info("User {} with id {} does not exist".format( user, foursquare_user_id)) return render_template('error.html') if user.credit_url: logger.info("User {} with id {} has already redeemed".format( user.email, foursquare_user_id)) return render_template('error.html') response = app.lcp_client.do_credit(user) user.credit_url = response['links']['self']['href'] user.save() _send_email(user.email, response['amount']) return redirect(url_for('thanks'))
def _send_email(email, amount): sg = sendgrid.SendGridClient( app.config['SENDGRID_USERNAME'], app.config['SENDGRID_PASSWORD'] ) message = sendgrid.Mail() message.add_to(email) message.set_subject('You just received {} points!'.format(amount)) message.set_html( render_template( 'checkin_email.html', email=email, amount=amount ) ) message.set_text( render_template( 'checkin_email.txt', email=email, amount=amount ) ) message.set_from(app.config['MAIL_DEFAULT_SENDER']) sg.send(message)
def show_bookmark(): # Check whether current user is authenticated before saving any variables if current_user.is_authenticated: userid = current_user.user_id favhtml = "favlist_web.html" favlist = get_mysql_userfavorite(userid) if not favlist: videolist = get_db_videolist() favhtml = "favlist_notfound_web.html" response = make_response( render_template(favhtml,videolist=videolist, cdnroot=current_app.config['CDN_ROOT'])) else: response = make_response( render_template(favhtml, cdnroot=current_app.config['CDN_ROOT'], clientid=current_app.config['CLIENT_ID'], APPLICATION_NAME=current_app.config['APPLICATION_NAME'], favlist=favlist)) response.headers['Content-Type'] = 'text/html' return response else: #if the user is not authenticated, redirect it to login page #After login, redirect user back to same page return redirect(url_for('auth.login', next='/bookmark'))
def htm_settings(): settings = [] if 'user_mail' in session: user = User.get(User.mail == session['user_mail']) if request.method == 'POST': # and form.validate(): form = SettingsForm(request.form) set = RunSettings.select().where(RunSettings.id == int(request.form['name'].split('form-')[1])).get() set.json_string = json.dumps(form.data) set.save() flash('Конфигурация сохранена') try: res = RunSettings.select().where(RunSettings.user == user.get_id()) for set in res: # print(json.loads(set.json_string)) f = SettingsForm() if set.json_string != "": f = SettingsForm.from_json(json.loads(set.json_string), skip_unknown_keys=True) settings.append({"id": set.id, "data": f}) except RunSettings.DoesNotExist: print("RunSettings empty") return render_template("htmSettings.html", settings=settings) else: return render_template("basic.html")
def register(): """ Registration form """ from lib.forms.registration import RegistrationForm from lib.database import db_session form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): from models import Team team = Team(form.team_name.data, form.institution.data, form.team_members.data, md5(form.password.data).hexdigest()) db_session.add(team) # trying to add to db try: db_session.flush() except: form.team_name.errors.append(u'Команда с таким названием уже зарегистрирована.') else: # if success, generate TEAM_ID team.generate_team_id() db_session.commit() # store session session['team_id'] = team.team_id return render_template('registration_success.html', team_id = team.team_id, active_register = True) return render_template('registration.html', form = form, active_registration = True)
def get(self, id=None): client = Client.query.get(id) if client: return render_template("client_update.html", client=client) else: return render_template("page_404.html")
def getMenus(): if not session.has_key('openid'): return render_template('common/error.html', title=u'错误', message=u'无法确认您的微信身份或者session过期,请刷新页面重试') openid = session['openid'] rs = checkOpenid(openid) if rs['resultCode'] != 0: return redirect(url_for('getRegister', openid=openid)) return render_template('weixin/menus.html', openid=openid)
def search_polis(): form = HumanForm() if request.method == 'POST': if form.is_submitted(): uncorrect_polis_list, polis = polis_helper.get_polises_by_fio(form.fam.data, form.im.data, form.datr.data.strftime('%d.%m.%Y')) return render_template('search_polis.html', form=form, polis=polis, uncorrect_polis_list=uncorrect_polis_list) else: return render_template('search_polis.html', form=form)
def create_user(): username = request.form['username'] password = request.form['password'] response = controller.create_user(username, password) if response: return render_template('register.html', msg = "Could not register user") else: return render_template('login_page.html')
def upload_image(): if request.method == 'GET': return render_template('file_send.html') if request.method == 'POST': file = request.files['file'] filename = secure_filename(file.filename) s3.Object(BUCKET_NAME, filename).put(Body=file.read()) return render_template('generic.html', title='Uploaded', body='Uploaded file')
def get(self): context = self.get_context() tournament_id = request.args.get('id') tournament = actions.get_tournament_by_id(int(tournament_id)) admin_list = [actions.get_user_by_id(admin_key.id()) for admin_key in tournament.admins] html_to_show = "" owners = [tournament.owner.key().id()] owners.extend([admin.key().id() for admin in admin_list]) # if event belongs to our user allow them to edit else redirect them if context['user'].key().id() in owners: # preload our forms with data form = forms.EditTournament() form.name.data = tournament.name form.date.data = tournament.date form.location.data = tournament.location form.tournament_security.data = tournament.perms form.type.data = tournament.type form.order.data = tournament.order form.win_method.data = str(tournament.win_method) tournaments = actions.get_linked_tournaments(tournament) matches = [] matches.extend(actions.get_matches_by_tournament(tournament)) participants = [] participants_by_match = {} for match in matches: found_participants = actions.get_participants_by_match(match) participants.extend(found_participants) while(len(found_participants)<2): found_participants.append({'name':'To Be Determined'}) participants_by_match[match] = found_participants matches.sort(key=attrgetter('round')) participants.sort(key=attrgetter('seed')) context['tournament'] = tournament context['linked_tournaments'] = tournaments context['matches'] = matches context['participants'] = participants context['participants_by_match'] = participants_by_match context['admins'] = admin_list context['form'] = form html_to_show = render_template('edit_tournament.html', **context) else: html_to_show = render_template('home.html',**context)# need to redirect to another page return html_to_show
def show_graph(type): data_file = url_for('static', filename='output.tsv') if type == 'd3': return render_template("time_series_d3.html", js=url_for('static', filename="d2.v2.min.js"), data_file=data_file) elif type == "dygraph": js=url_for('static', filename="dygraph-combined.js") return render_template('time_series.html', data_file = data_file, js = js) elif type == "google": return render_template('time_series_google.html')
def enc(): if request.method == "GET": return render_template("enc.html") key = request.form["key"].strip() xml = request.form["xml"].strip() encrypted = jbelt.enc(xml, base64.b64decode(key)) return render_template("dec.html", xml=prettify(encrypted), button_label=u"Зашифровать")
def home(): number_form = NumberForm() if number_form.validate_on_submit(): user_number = int(request.form['number']) result = get_result(user_number, magic_number) return render_template('home.html', form=number_form, result=result) return render_template('home.html', form=number_form)
def login(): username = request.form['username'] password = request.form['password'] login_successful = controller.authorize_user(username, password); if login_successful: image_info = controller.fetch_images() return render_template('home_page.html', username = username, image_info = image_info) else: return render_template('login_page.html', msg = "Incorrect username and/or password!!")
def handle_subtitles(): u""" Handler function for root url. It shows the page in with an empty form in the case of a 'GET' request and. In the case of a 'POST' request, returns the repaired subtitles file when the form validates and successfully repairs it. When any step fails, returns the page with the form containing the error messages. """ if request.method == "GET": # in the case of a 'GET' request, gets an instance of the form and renders the page with it subtitle_form = SubtitleUploadForm() return render_template('app.html', subtitle_form=subtitle_form) elif request.method == "POST": # in the case of a 'POST' request, gets an instance of the form populated with the request parameters on the # request and initializes auxiliary variables as None subtitle_form = SubtitleUploadForm(request.form) error = None filename = None result_content = None if subtitle_form.validate(): # if the form contains valid data try: # reads uploaded file content file_data = request.files[subtitle_form.subtitle_file.name].read() # gets its filename filename = request.files[subtitle_form.subtitle_file.name].filename # and gets from the form the value in seconds to add or subtract from the time pattern matches seconds = int(request.form['adjustment']) if verify_file(file_data, filename): # if the file content and its extension are compatible with the expectations, calls function to # proceed with the file repairing and stores its results (repaired string with file content) result_content = fix_file(file_data, seconds) else: # otherwise, creates the error message to be shown to the user error = "File is not in the expected format and/or does not contain expected content." except (AttributeError, KeyError): # with any error occurs, composes another erro message to be shown to the user error = "Something went wrong on your submission, please again to submit a valid file." if error: # if there is an error message, add it to the form errors and render the page with the form containing # the errors to be shown subtitle_form.errors['subtitle_file'] = error return render_template('app.html', subtitle_form=subtitle_form) else: # otherwise, returns the repaired file as an attachment response = make_response(result_content) response.headers["Content-Disposition"] = "attachment; filename={0}".format("fixed_" + filename) return response # renders the page again with the form erros if form does not validate return render_template('app.html', subtitle_form=subtitle_form)
def dpt(): if request.method == "GET": db.create_all() db.session.commit() return render_template("dpt.html") elif request.method == "POST": params = request.get_json() oDpt = clsDpt(params['idDpt'],params['nombreDpt']) oDpt.addMe() return render_template("dpt.html")
def user(): if request.method == "GET": db.create_all() db.session.commit() return render_template("role.html") elif request.method == "POST": params = request.get_json() oRole = clsRole(params['idRol'],params['nombreRol']) oRole.addMe() return render_template("role.html")
def home(): keygen_form = KeygenForm() if keygen_form.validate_on_submit(): user_key = escreen_keygen.generate_key(request.form['pin'], request.form['app'], request.form['uptime'], int(request.form['duration'])) return render_template('home.html', form=keygen_form, user_key=user_key) '''Render page using Jinja2 template''' return render_template('home.html', form=keygen_form)
def process_images(): if request.method == 'GET': filenames = list(filter(lambda x: not x.startswith('logs'), map(lambda x: x.key, list(bucket.objects.all())))) return render_template('files.html', files=filenames) elif request.method == 'POST': log_sdb('webapp', 'Files to process', request.form.getlist('file')) for file in request.form.getlist('file'): queue.send_message(MessageBody=file) return render_template('generic.html', title='', body="Processing")
def get(self): return render_template('login.html', form=LoginForm())
def index(): #form = submitForm.subForm() return render_template("index.html")
def index(): return render_template("index.html")
def profile(user: Dict): return render_template("profile.html", user=user)
def login(): # Store the URL of the page that redirected here and store # it so we can redirect to it after authentication set_redirect_url() return render_template("login.html")
def show_quotes(): quote_objects = quote_data_access.get_quotes() #Render quote_objects "server-side" using Jinja 2 template system return render_template('quotes.html', app_data=app_data, quote_objects=quote_objects)
def main(): return render_template('index.html', app_data=app_data)
def index(): return render_template("index.html", users=list_users(), script=True)
def show_quotes_ajax(): #Render quote_objects "server-side" using Jinja 2 template system return render_template('quotes_ajax.html', app_data=app_data)
def index(): return render_template("upload.html")
def change_type(fleet_id: int) -> Any: groups = db.session.query(WaitlistGroup).all() return render_template("fleet/takeover/change-group-form.html", fleetID=fleet_id, groups=groups)
def list(): mylist = de.myselect() return render_template('examlist.html', mylist=mylist)
def home(): hackers = Hacker.objects.all() return render_template('home.html', hackers=hackers)
def index(): return render_template('index.html')
def get(self): return render_template('base/main.html')
def page_not_found(e): return render_template('404.html'), 404