我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用flask.session.keys()。
def logout_user(): ''' Logs a user out. (You do not need to pass the actual user.) This will also clean up the remember me cookie if it exists. ''' print "LOGOUT CHECK" #print session.keys() try: #if 'user_id' in session: # user = User.query.get(session['user_id']) # user.current_user = False # user.save() print "Logged out: %s | %s" % (session.pop('user_id'), session.pop('user')) return True except: return False
def home(): page_init() if request.method == 'POST': inputfile = request.files['file'] if inputfile: result = file_uploaded(inputfile) if result['type'] == 'redirect': return redirect(url_for(result['target'],**result['parameters'])) elif result['type'] == 'render': params = {'blogposts':get_blogposts(5),'recents':get_recents(), 'vote':json.dumps({entry[0]:get_votes(entry[0]) for entry in get_recents()['posts']})} if 'parameters' in result: for key in result['parameters'].keys(): params[key] = result['parameters'][key] return render_template(result['target'], **params) recents = get_recents() vote = json.dumps({entry[0]:get_votes(entry[0]) for entry in recents['posts']}) return render_template("index.html", recents=recents, vote=vote, blogposts=get_blogposts(5), **page_args())
def find_claimables(): if not hasattr(g,'claimables'): sessionids = list(session.keys()) removals = ['admin','logged_in_user'] for key in removals: try: sessionids.remove(key) except ValueError: pass urls = tuple([key for key in sessionids if not key.endswith('del_token')]) if len(urls) > 0: db = get_db() cur = db.cursor() cur.execute('SELECT id, md5, del_token, url FROM playerinfo WHERE owner_id IS NULL AND url IN '+app.sqlesc,(urls,)) result = cur.fetchall() checked_results = [] for row in result: if row[1] == session[row[3]] and row[2] == session[row[3]+'del_token']: checked_results.append((row[0],row[3])) g.claimables = checked_results else: g.claimables = [] return g.claimables
def from_session(cls): if 'user' not in session.keys(): return None user_data = session.get('user') return cls(**user_data)
def make_hashable(input_json): big_string = '' for key in sorted(input_json.keys()): sub_string = '{}: {{'.format(key) if type(input_json[key]) == list: sub_string += '[' for item in input_json[key]: sub_string += '{' for sub_key in sorted(item.keys()): sub_string += '{}:{},'.format(sub_key,item[sub_key]) sub_string += '},' sub_string += ']' elif type(input_json[key]) == dict: sub_string += '{' for sub_key in sorted(input_json[key].keys()): if type(input_json[key][sub_key]) != dict: sub_string += '{}:{},'.format(sub_key,input_json[key][sub_key]) else: sub_string += '{' for sub_sub_key in sorted(input_json[key][sub_key].keys()): sub_string += '{}:{},'.format(sub_sub_key,input_json[key][sub_key][sub_sub_key]) sub_string += '},' sub_string += '},' sub_string += '}, ' big_string += sub_string return big_string
def connected(): if 'debugging' not in session.keys(): session['debugging'] = 'in' inlock.acquire() debug(session.pop('path'), output, inlock, outlock) emit('event', 'connected')
def summarize(): template_dict = make_template_dict() config_names = session['config_names'] # summary_flavors flavors_in_logs = logger.get_config_values_from_log('flavor') summary_flavors = make_requested(request, 'summary_flavors', default=flavors_in_logs, session=session) if request.args.getlist('summary_flavors-new') and summary_flavors == []: return 'Summary requires at least 1 flavor' # groupby_config_name if 'groupby_config_names' in session.keys(): del session['groupby_config_names'] groupby_config_name = make_requested(request, 'groupby_config_name', default=config_names[0]) if request.args.getlist('groupby_config_names-new') and groupby_config_name is None: return 'Barplot Grouping requires 1 config_name' # imgs log_df = logger.make_log_df(summary_flavors) if len(log_df) != 0: imgs = figs_to_imgs(*[make_summary_bar_fig( log_df, config_names, groupby_config_name, eval_name, logger.eval_name_range_dict[eval_name]) for eval_name in AppConfigs.EVAL_NAMES]) imgs += figs_to_imgs(make_summary_table_fig(log_df, config_names, groupby_config_name)) imgs_desc = 'Log Summary' else: imgs = [] imgs_desc = 'No models logged' return render_template('summarize.html', template_dict=template_dict, imgs_desc=imgs_desc, imgs=imgs, summary_flavors=summary_flavors, flavors_in_logs=flavors_in_logs, groupby_config_name=groupby_config_name, config_names=config_names)
def display_data(url): page_init() deletable = None db = get_db() cur = db.cursor() cur.execute('SELECT '+database_fields+' FROM playerinfo WHERE url='+app.sqlesc+'',(url,)) data = cur.fetchall() if len(data) != 1: g.error = _('There is nothing here... is this URL correct?') if str(url) != 'favicon.ico': cur.execute('INSERT INTO errors (ip, time, notes) VALUES ('+app.sqlesc+','+app.sqlesc+','+app.sqlesc+')',(request.environ['REMOTE_ADDR'],time.time(),str(len(data))+' cur.fetchall() for url:'+str(url))) db.commit() return render_template("error.html", **page_args()) else: cur.execute('UPDATE playerinfo SET views=views+1 WHERE url='+app.sqlesc+'',(url,)) db.commit() datadict = {} for k, key in enumerate(sorted(database_structure_dict.keys())): if key != 'farm_info': datadict[key] = data[0][k] claimable = False deletable = False if datadict['owner_id'] == None: if url in session and url+'del_token' in session and session[url] == datadict['md5'] and session[url+'del_token'] == datadict['del_token']: if logged_in(): claimable = True else: deletable = True elif logged_in() and str(datadict['owner_id']) == str(get_logged_in_user()): deletable = True # other_saves, gallery_set = get_others(datadict['url'],datadict['date'],datadict['map_url']) other_saves, gallery_set = get_others(datadict['url'],get_date(datadict),datadict['map_url']) for item in ['money','totalMoneyEarned','statsStepsTaken','millisecondsPlayed']: if item == 'millisecondsPlayed': datadict[item] = "{:,}".format(round(float((int(datadict[item])/1000)/3600.0),1)) else: datadict[item] = "{:,}".format(datadict[item]) datadict['animals'] = None if datadict['animals']=='{}' else json.loads(datadict['animals']) datadict['portrait_info'] = json.loads(datadict['portrait_info']) friendships = sorted([[friendship[11:],datadict[friendship]] for friendship in sorted(database_structure_dict.keys()) if friendship.startswith('friendships') and datadict[friendship]!=None],key=lambda x: x[1])[::-1] kills = sorted([[kill[27:].replace('_',' '),datadict[kill]] for kill in sorted(database_structure_dict.keys()) if kill.startswith('statsSpecificMonstersKilled') and datadict[kill]!=None],key=lambda x: x[1])[::-1] if datadict['imgur_json']!=None: datadict['imgur_json'] = json.loads(datadict['imgur_json']) # passworded = True if datadict['del_password'] != None else False # passworded=passworded, removed from next line claimables = find_claimables() vote = json.dumps({url:get_votes(url)}) if logged_in() == False and len(claimables) > 1 and request.cookies.get('no_signup')!='true': flash({'message':'<p>'+_("It looks like you have uploaded multiple files, but are not logged in: if you <a href='{}'>sign up</a> or <a href='{}'>sign in</a> you can link these uploads, enable savegame sharing, and one-click-post farm renders to imgur!")+'</p>'.format(url_for('signup'),url_for('login')),'cookie_controlled':'no_signup'}) return render_template("profile.html", deletable=deletable, claimable=claimable, claimables=claimables, vote=vote,data=datadict, kills=kills, friendships=friendships, others=other_saves, gallery_set=gallery_set, **page_args())
def btns(model_name): template_dict = make_template_dict() timepoints = [n for n, saved_mb_name in enumerate(load_saved_mb_names_from_ba_traj_df(model_name))] # model timepoint = make_requested(request, 'timepoint', default=timepoints[-1], session=session) if request.args.getlist('timepoints-new') and timepoint is None: return 'Changing timepoint requires 1 selection' else: print('timepoint', timepoint) timepoint = int(timepoint) if timepoint > timepoints[-1]: # in case model doesn't have timepoint matching session timepoint timepoint = timepoints[-1] # mb_name mb_name = load_saved_mb_names_from_ba_traj_df(model_name)[timepoint] # btn_names btn_name_info_dict = make_btn_name_info_dict(model_name) btn_names = sorted(btn_name_info_dict.keys()) # request if request.args.get('btn_name'): btn_name = request.args.get('btn_name') imgs_desc, needs_field_input = btn_name_info_dict[btn_name] if not needs_field_input: model = Model(model_name, timepoint=timepoint) model.eval_name_range_dict = logger.eval_name_range_dict figs = btn_name_figs_fn_dict[btn_name](model) imgs = figs_to_imgs(*figs) return render_template('imgs.html', template_dict=template_dict, model_name=model_name, mb_name=mb_name, timepoint=timepoint, imgs=imgs, imgs_desc=imgs_desc) else: return redirect(url_for('field', model_name=model_name, btn_name=btn_name)) else: return render_template('btns.html', template_dict=template_dict, btn_names=btn_names, model_name=model_name, mb_name=mb_name, timepoint=timepoint, timepoints=timepoints)
def generate(model_name): template_dict = make_template_dict() timepoints = [n for n, saved_mb_name in enumerate(load_saved_mb_names_from_ba_traj_df(model_name))] phrase = None # model timepoint = make_requested(request, 'timepoint', default=timepoints[-1], session=session) if request.args.getlist('timepoints-new') and timepoint is None: return 'Changing timepoint requires 1 selection' else: timepoint = int(timepoint) model = Model(model_name, timepoint=timepoint) # task_id task_btn_str = make_requested(request, 'task_btn_str', default='Predict next terms', session=session) if request.args.getlist('task_btn_strs-new') and task_btn_str is None: return 'Changing task_btn_str requires 1 selection' task_names = ['predict'] + model.task_names task_name = AppConfigs.TASK_BTN_STR_TASK_NAME_DICT[task_btn_str] task_id = task_names.index(task_name) # task_btn_strs task_btn_strs = [task_btn_str for task_btn_str in sorted(AppConfigs.TASK_BTN_STR_TASK_NAME_DICT.keys()) if AppConfigs.TASK_BTN_STR_TASK_NAME_DICT[task_btn_str] in task_names] # form input_str = 'Type phrase here' form = make_form(model, request, input_str, 'term') # make output_dict output_dict = {} if form.validate(): phrase = form.field.data terms = phrase.split() for num_samples in AppConfigs.NUM_SAMPLES_LIST: output_dict[num_samples] = generate_terms(model, terms, task_id, num_samples=num_samples) return render_template('generate.html', template_dict=template_dict, model_name=model_name, mb_name=model.mb_name, timepoints=timepoints, # not model.timepoints because it includes one without rnn_input timepoint=model.timepoint, form=form, phrase=phrase, output_dict=output_dict, num_samples_list=AppConfigs.NUM_SAMPLES_LIST, task_btn_strs=task_btn_strs)