def create_auth(): try: print("~~~~~~~~~~~~~~~~~ADDING A SET~~~~~~~~~~~") # print(list(session.items())) user = list(session.items())[0][0] # print(user) # print(request) # print(request.form) title = request.form["title"] count = request.form["count"] terms = [] defs = [] # print(title) # print(count) quizid = db.make_quiz(title, user) print("QUIZID: " + str(quizid)) for x in range(int(count)): term = request.form["term" + str(x)] definition = request.form["def" + str(x)] db.add_term(quizid, term, definition) d["recentcrt"] = True d["quizid"] = quizid print("REDIRECTING YOIU TO VIEW QUID ID :" + str(quizid)) print("VIEW_STORY IS " + str(d["quizid"])) return redirect(url_for("view", quizid=quizid)) except: if len(session) != 0: flash("Something bad happened...") return render_template("create.html", logged=True, category="epic_fail", flash=True, user=list(session.items())[0][0]) return render_template("landing.html")
def index(): items = 0 if 'items' in session: for x in session['items'].values(): print session.items() items += int(x) return render_template('new.html', items = items)
def take_test(quizid): # return redirect(url_for("view", quizid = quizid)) print("VIEWING SOME STORY NOW") pubquiz = db.get_user_quizid("admin") pubquiz = refactor(pubquiz) my_quiz = db.get_quizname(quizid) print("tooof") dictlib = db.get_content(quizid) doop = [x[1] for x in dictlib] print(doop) shuffle(doop) print(doop) if int(quizid) in pubquiz: print("Yes") if len(session) != 0: lisdefs = [x[1] for x in db.get_content(quizid)] shuffle(lisdefs) return render_template( "take_test.html", quizid=quizid, deflist=lisdefs, termlist=[x[0] for x in db.get_content(quizid)], logged=True, user=list(session.items())[0][0]) flash("Log in to take a test") return render_template("landing.html", flash=True, category="epic_fail") print("no") if len(session) != 0: flashit = False #later add to see if you can actually access that quiz. user = list(session.items())[0][0] myquizzes = refactor(db.get_user_quizid(user)) if int(quizid) not in myquizzes: flash("Not your quiz, buddy...") return render_template("home.html", flash=True, category="epic_fail", logged=True, user=list(session.items())[0][0]) if d["recentcrt"]: flashit, d["recentcrt"] = d["recentcrt"], False flash("Successfully added!") lisdefs = [x[1] for x in db.get_content(quizid)] shuffle(lisdefs) print(lisdefs) return render_template("take_test.html", qid=my_quiz, quizid=quizid, deflist=lisdefs, termlist=[x[0] for x in db.get_content(quizid)], logged=True, category="epic_win", flash=flashit, user=list(session.items())[0][0]) flash("Log in to access your sets.") return render_template("landing.html", flash=True, category="epic_fail")
def test(z, q): if 'items' in session: session['items'][z] = q else: session['items'] = {} session['items'][z] = q print session['items'] print session.items() return render_template('about.html')
def logout(): # this clears all server information about the access token of this connection res = str(session.items()) print(res) session.clear() res = str(session.items()) print(res) # when the browser is redirected to home page it is not logged in anymore return redirect(url_for("home_page"))
def postComment(message_id): print session.items() comment = request.form['comment'] userID = session['id'] query = """INSERT INTO comments (comment, user_id, message_id, comments_created_at, comments_updated_at) VALUES (:comment, :user_id, :message_id, NOW(), NOW())""" # We'll then create a dictionary of data from the POST data received. data = {'comment': comment, 'user_id': userID, 'message_id': message_id} # Run query, with dictionary values injected into the query. mysql.query_db(query, data) return redirect('/wall')
def postMessage(): print session.items() message_content = request.form['message'] userID = session['id'] query = """INSERT INTO messages (message, user_id, messages_created_at, messages_updated_at) VALUES (:message, :user_id, NOW(), NOW())""" # We'll then create a dictionary of data from the POST data received. data = {'message': message_content, 'user_id': userID} # Run query, with dictionary values injected into the query. posted_messages = mysql.query_db(query, data) return redirect('/wall')
def users(): query = "SELECT * FROM users WHERE id = :id" data = {'id': session['user_id']} user = mysql.query_db(query, data) session['user_id'] = user[0]['id'] query = "SELECT messages.user_id, messages.id, messages.created_at, messages.message, users.first_name, users.last_name FROM messages LEFT JOIN users ON messages.user_id = users.id ORDER BY messages.created_at DESC" messages = mysql.query_db(query) query = "SELECT comments.user_id, comments.id, comments.message_id, users.first_name, users.last_name, comments.comment, comments.created_at FROM comments LEFT JOIN users ON comments.user_id = users.id" comments = mysql.query_db(query) print session.items() return render_template('user.html', user = user, messages = messages, comments = comments)
def index(): session['username'] = '******' print(request.cookies.get('session', 'None Cookies'), request.cookies.get('ha', 'None Find')) response = make_response(jsonify(dict(session.items()))) response.set_cookie('ha', 'lo') return response
def test2(value=None): session['username2'] = value or 'cza2' print(request.cookies.get('session', 'None Cookies'), request.cookies.get('ali', 'None Find')) response = make_response(jsonify(dict(session.items()))) response.set_cookie('ali', 'loh') return response
def basket(): if request.method == "GET": selected = dict(session.items()) selected.pop('logged_in', True) selected.pop('admin', True) ids = selected.keys() query = f""" SELECT * FROM products WHERE id in ({', '.join([item for item in ids])}) """ db_cursor = get_db().cursor() db_cursor.execute(query) products = db_cursor.fetchall() for product_ in products: product_[ 'image'] = f"{product_['category']}/{product_.get('image', '')}" product_['number'] = selected[f'{product_["id"]}'] return render_template("basket.html", products=products, len=len(products)) elif request.method == "POST": fields = request.form.to_dict() value = list(fields.values())[0] session.pop(value, None) return redirect(url_for('basket'))
def process_money(): print request.form now = datetime.datetime.now() print 'datetime is ', now try: session['outcome']==session['outcome'] except KeyError: session['outcome']=[] print 'No outcome yet' if request.form['building'] == 'farm': print 'farm' # session['gold_count'] = 20 farm_gold=random.randint(10,20) session['outcome'].insert(0, 'Earned '+ str(farm_gold)+ ' from the farm! '+ str(now)) session['gold_total']+=farm_gold print 'farm gold earned is ', farm_gold elif request.form['building'] == 'casino': print 'casino' casino_gold=random.randint(-50,50) if casino_gold >= 0: session['outcome'].insert(0, 'Earned '+ str(casino_gold)+ ' from the casino! '+ str(now)) session['gold_total']+=casino_gold print 'Casino gold earned is ', casino_gold else: session['outcome'].insert(0, 'Lost '+ str(casino_gold)+ ' from the casino...Ouch! '+ str(now)) session['gold_total']+=casino_gold print 'Casino gold lost is ', casino_gold for key, value in session.items(): print key,':',value return redirect('/')
def keyfunc(): dimensions = {} if endpoint: dimensions['endpoint'] = request.endpoint if path: dimensions['path'] = request.path if method: dimensions['method'] = request.method if query_string: dimensions['query_string'] = request.query_string if data: dimensions['data'] = request.data if headers: d = {} for name in headers: d[name] = request.headers.get(name, None) dimensions['headers'] = str(sorted(d.items())) if session: dimensions['session'] = str(sorted(flask_session.items())) if content_type: dimensions['content_type'] = request.content_type if content_length: dimensions['content_length'] = request.content_length if remote_addr: dimensions['remote_addr'] = request.headers.get( 'X-Forwarded-For', request.remote_addr) origin_key = str(sorted(dimensions.items())) if use_checksum: # Use hashed stringify dimensions sha = hashlib.sha1() sha.update(origin_key.encode('utf8')) return sha.hexdigest() return origin_key
def session_handle(): for k,v in request.args.items(): session[k] = v resp = make_response({k: v for k, v in session.items()}) for k, v in request.args.items(): resp.set_cookie(f"cookie_{k}", v) return resp
def send_error_email(env, trace): if not current_app.config["EMAIL_ERRORS"]: return info = dict(trace=trace, session=list(session.items()), form_data=list(request.form.items()), url=request.full_path, method=request.method, env=env) send_email( current_app.config["EMAIL_FROM"], current_app.config["SITE_ADMIN"], "Application error ({})".format(env), """ The following exception occurred in {env}: {trace} Here is information that may be helpful in debugging the problem. URL: {url} Session data: {session} Form data: {form_data} Request method: {method} """.format(**info))
def index(): openid1 = session.get('openid') print session for k, v in session.items(): print k, v if openid1 != None: session['openid'] = openid1 code = request.values.get('code') if code: accessToken = R(url_code.format(appid=appID, appsecret=AppSecret, code=code)) res_data = U(accessToken) print res_data res = res_data.read().decode('utf8') # res = res_data.read() print res res_json = json.loads(res) # 转成json access_token = res_json["access_token"] refresh_token = res_json["refresh_token"] openid = res_json["openid"].strip() print openid if openid != None: session['openid'] = openid print session.get('openid') resp = render_template('index.html') resp = make_response(resp) resp.headers['Access-Control-Allow-Origin'] = '*' return resp resp = render_template('index.html') resp = make_response(resp) resp.headers['Access-Control-Allow-Origin'] = '*' return resp
def items(number): dbworker = DBWorker() numb = str(number) if not numb.isdigit(): number = 0 if dbworker.count_goods() > int(number) + 8: maxx = (int(number)) * 8 + 1 else: maxx = dbworker.count_goods() minn = (int(number) - 1) * 8 + 1 goods = dbworker.get_goods(minn, maxx) leng = maxx - int(number) if leng > 4: goods_resp = [[goods[0], goods[1], goods[2], goods[3]]] gg = [] for g in goods[4:]: gg.append(g) leng = len(gg) goods_resp.append(gg) else: goods_resp = [goods] leng = len(goods) # print(leng) flag = (dbworker.count_goods() > (int(number) * 8 + 1)) res = str(session.get("current_cart")) print(session.items(), res) if request.method == 'GET': return make_response( render_template('items.html', goods_resp=goods_resp, number=int(number), leng=leng, flag=flag))
def handle_login(): username = escape(request.form.get("username", str, None)) if not username: return {"error": "bad_request"}, 400 session['username'] = username session['uuid'] = game.get_uuid() if game.get_player_count() == 2: game.add_spectator(Spectator(username)) session['type'] = 'spectator' elif game.get_x_player() is None: game.set_x_player(Player(username, 'X')) session['type'] = 'player' session['player'] = 'X' else: game.set_o_player(Player(username, 'O')) session['type'] = 'player' session['player'] = 'O' game.set_status(1) socketio.emit('game', get_game(), broadcast=True, include_self=False, namespace='/', skip_sid=True) return { k: v for k, v in session.items() if k in ('username', 'type', 'player') }, 201
def capture_view(): user_form = UserInputForm(request.form) try: lookup = [(idx, x) for idx, x in enumerate(session["camera_config"]["image_size_list"])] reverselookup = dict([(str(v), k) for k, v in lookup]) user_form.image_size.choices = lookup except: pass if user_form.validate() and user_form.submit.data: print(user_form.data) for k in [x for x in vars(user_form) if not x.startswith("_") and not x == "meta"]: if k == "image_size": session["image_width"], session["image_height"] = user_form[k].data session[k] = user_form[k].data for k, v in session.items(): try: user_form[k].data = v except: pass try: user_form.image_size.data = reverselookup[str(session.get("image_size"))] except: pass user_editable = ["1st_corner", "2nd_corner", "overlap", "scan_order", "image_height", "image_width"] template_data = {"form": user_form} return render_template("capture.html", **template_data)
def handle_exception (err) : if not isinstance(err, HTTPException) : path = errorpath() name = path.name with path.open("w", encoding="utf-8", errors="replace") as out : out.write(f'<p>error recorded on: {datetime.now()}</p>') tb = traceback.TracebackException.from_exception(err, capture_locals=True) text = "".join(tb.format()).replace(BADASS, "").replace(STDLIB, "") format_tb(text, out) if session : out.write('<div data-role="footer"><h5>SESSION</h5></div><div>') for key, val in session.items() : out.write(f"<b><code>{key}</code></b><pre>\n") try : text = pformat(val) except : text = repr(val) out.write(highlight(text, PythonLexer(), HtmlFormatter())) out.write("</div>") err = InternalServerError(f"The server encountered an internal error" f" and was unable to complete your request." f" The error has been recorded with identifier" f" {name!r} and will be investigated.") return render_template("httperror.html", err=err), err.code
def clicker(plus, minus): plus = plus or 0 minus = minus or 0 if "uuid" not in session: session["uuid"] = str(uuid.uuid4()) value = session.get(uid, 0) if (plus + minus) > 0: if plus > minus: value += 1 else: value -= 1 if value < 0: value = 0 session[uid] = value data = {k: v for k, v in session.items()} cache.set(data["uuid"], data) session.modified = True users = cache.get("users") if users is None: users = set() if data["uuid"] not in users: users.add(data["uuid"]) cache.set("users", users) print("new user", users) return value
def session_dump(): session_data = "" for key, value in session.items(): session_data = session_data + str(key) + ": " + str(value) + "<br>" return str(session_data)
def results(): """Process user's request and then clear session.""" full_params = {"apiKey": apiKey, "number": 10} # Filter meaningful data from session and add it to full_params for key, value in session.items(): if (key != "_permanent") and value: for nested_key, nested_value in value.items(): if nested_value: full_params[nested_key] = nested_value session.clear() # Remove 'btn-identifier' from full_params try: del full_params['btn-identifier'] except KeyError: pass # Get recipes using user's selection criteria recipes_info = get_recipe_info(full_params) # Error check if recipes_info == []: return redirect(url_for('error')) else: return render_template("results.html", recipe_result=recipes_info)
def next_article(): data = get_article() if data is not None: session_items = session.items() # set old current_eid to previous_eid if present with session variable # if its not present, then next has been called the first time; on window load if 'current_eid' not in session.keys(): session['current_eid'] = data['eid'] session['previous_eids'] = [] # next endpoint was called min. once else: # set current eid to previous eid and assing newly fetched eid OLD_current_eid = session['current_eid'] # check if already exsits (e.g. when going back and forth between articles) if OLD_current_eid not in session['previous_eids']: session['previous_eids'].append(OLD_current_eid) session['current_eid'] = data['eid'] # add previous eids data['previous_eids'] = session['previous_eids'] json = jsonify(data) # store eid as previous_eid (for 'previous' button) resp = make_response(json) return resp else: return ('no data', 204)
def register(): session['first name'] = request.form['first_name'] session['last name'] = request.form['last_name'] session['email'] = request.form['email'] session['password'] = request.form['password'] session['confirm password'] = request.form['confirmPassword'] errors = False for key, val in list(session.items()): if len(val) < 1: flash(f'{key} cannot be blank!') errors = True if not session['first name'].isalpha() or not session['last name'].isalpha( ): flash('Names cannot have numbers!') errors = True elif not EMAIL_REGEX.match(session['email']): flash('Email format is not valid') errors = True elif len(session['password']) < 8: flash('Passwords must be at least 8 charachters long') errors = True elif session['password'] != session['confirm password']: flash('Your passwords do not match') errors = True if errors: return redirect('/') return redirect('/registered')
def assign_kpi_evolution(metis_db): # get random KPI evolution to_classify = metis_db.select_random_kpi_evolution(session['team']) # debug what was pulled logger.debug('Selected row:') logger.debug(to_classify) # store that user's current task in the session session['series'] = to_classify['series'] session['run_date'] = to_classify['run_date'] session['kpi'] = to_classify['kpi'] session['client_id'] = int(to_classify['client_id']) session['partner_id'] = int(to_classify['partner_id']) session['campaign_id'] = int(to_classify['campaign_id']) session['cost_center'] = to_classify['cost_center'] session['ranking'] = to_classify['ranking'] session['country'] = to_classify['country'] session['subregion'] = to_classify['subregion'] session['region'] = to_classify['region'] session['site_type'] = to_classify['site_type'] session['event_name'] = to_classify['event_name'] # debug the types of everything for key, value in session.items(): logger.debug( 'Field {key} with value {value} is of type {field_type}'.format( key=key, value=value, field_type=type(value)))
def log_user_in(): """ Takes information from login form and validates against database in order to log user in and start session. """ email = request.form.get("email") form_password = request.form.get("password") existing_user = User.query.filter(User.email == email).first() if existing_user is None: flash("You must create an account first") return redirect("/") else: user_id = existing_user.user_id user_password = existing_user.password if form_password != user_password: flash("The password you entered does not match your account") return redirect("/") else: session["user_id"] = user_id print "SESSION: ", session.items() flash("You're successfully logged in") return redirect("/users/" + str(user_id))
def pms5003s(name): if session.items(): # dict_keys(['temperature', 'humidity']) if name == 'pm1dot0': """触发传感器新读取 """ # print(session['pm1dot0']) pms5003s_data_to_session() return str(session['pm1dot0']) elif name == 'pm2dot5': return str(session['pm2dot5']) elif name == 'pm10dot0': return str(session['pm10dot0']) elif name == 'particulate': data = list() data.append(session['particulate0dot3']) data.append(session['particulate0dot5']) data.append(session['particulate1dot0']) data.append(session['particulate2dot5']) data.append(session['particulate5dot0']) data.append(session['particulate10dot0']) return data.__str__() elif name == 'formaldehyde': return str(session['formaldehyde']) else: pass else: # 程序刚启动session为空, 或报键错误 pms5003s_data_to_session()
def generate_custom_settings_list(): customized_variables = { key: val for key, val in session.items() if not key.startswith('_') } var_str = json.dumps(customized_variables, ensure_ascii=False, indent=4) return html.Pre(var_str)
def edit_auth(): # try: print("~~~~~~~~~~~~~~~~~Editing A SET~~~~~~~~~~~") # print(list(session.items())) user = list(session.items())[0][0] # print(user) # print(request) # print(request.form) title = request.form["title"] count = request.form["count"] print(count) terms = [] defs = [] # print(title) # print(count) quizid = db.make_quiz(title, user) print("QUIZID: " + str(quizid)) for x in range(int(count)): term = request.form["term" + str(x)] definition = request.form["def" + str(x)] db.add_term(quizid, term, definition) d["recentcrt"] = True d["quizid"] = quizid print("REDIRECTING YOIU TO VIEW QUID ID :" + str(quizid)) print("VIEW_STORY IS " + str(d["quizid"])) return redirect(url_for("view", quizid=quizid))
def game_inplay(): session['input'] = request.form['input'] if 'farm' in session['input']: gold = round(random.random() * 20 + 10) if 'cave' in session['input']: gold = round(random.random() * 10 + 5) if 'estate' in session['input']: gold = round(random.random() * 5 + 2) if 'casino' in session['input']: gold = round(random.random() * 100 - 50) #Session data passed to HTML date_time = datetime.datetime.now() date_time = date_time.strftime("%m/%d %I:%M") industry = session['input'] session['total_gold'] += gold # gold = session['total_gold'] print('*' * 20, session.items()) #Progress notes session[ 'progress_notes'] += f'<br>{date_time} - GOLD: {gold} - {industry}<br>' return redirect('/game_play')
def protected(): productDetail = dict() req = request.get_json() productDetail = { "brand": req['brand'], "name": req['name'], "price":req['price'], "size_num": req['size_num'], "size_name": req['size_name'], "image_name": req['img_id'] } keys = list(productDetail.values()) session.setdefault(keys[5], productDetail) productBought = dict() singleProduct = dict() for k, v in session.items(): try: convert = int(k) products = Product.query.get(int(v['image_name'])) singleProduct[convert] = v singleProduct[convert]['image_name'] = products.image_product productBought.update(singleProduct) except ValueError as e: continue return {"Message":"Received"}
def edit(quizid): print("editing story") pubquiz = db.get_user_quizid("admin") pubquiz = refactor(pubquiz) my_quiz = db.get_quizname(quizid) if int(quizid) in pubquiz: admin_name = db.get_quizname(quizid) if len(session) != 0: return render_template("editset.html", lenset=len(db.get_content(quizid)), quizname=db.get_quizname(quizid), qname=admin_name, qid=quizid, info=dbtodict(db.get_content(quizid)), logged=True, user=list(session.items())[0][0]) return render_template("viewset.html", quizname=db.get_quizname(quizid), qid=my_quiz, info=dbtodict(db.get_content(quizid))) if len(session) != 0: flashit = False #later add to see if you can actually access that quiz. user = list(session.items())[0][0] myquizzes = refactor(db.get_user_quizid(user)) if int(quizid) not in myquizzes: flash("Not your quiz, buddy...") return render_template("home.html", flash=True, category="epic_fail", logged=True, user=list(session.items())[0][0]) # if d["recentcrt"]: # flashit, d["recentcrt"] = d["recentcrt"], False flash("Successfully added!") return render_template("editset.html", lenset=len(db.get_content(quizid)), quizname=db.get_quizname(quizid), qname=my_quiz, qid=quizid, info=dbtodict(db.get_content(quizid)), logged=True, category="epic_win", flash=flashit, user=list(session.items())[0][0]) flash("Log in to edit your quiz.") return render_template("landing.html", flash=True, category="epic_fail")
def h(): print(request.url, request.cookies, request.headers.__dict__) print('ticket: ', request.args.get("ticket", None)) response = make_response("test") response.set_cookie("name", "xxx") print(response) print(session.items(), session.get('user_id')) return render_template('game.html', name='lf')
def show_session(): s = 'SESSION:\n'\ 'new: %s\n'\ 'modified: %s\n'\ 'permanent: %s\n' % (session.new, session.modified, session.permanent) s += '\n%s' % session.items() return s
def get_cart_session(): #Fetch product IDs and product quantities prod_quantities = [key for key, value in session.items() if 'prod_quantity' in key.lower()] product_ids = [p.strip('prod_quantity') for p in prod_quantities] #Fetch product data and return product json products = Product.query.filter(Product.product_id.in_(*product_ids)).all() return jsonify({ 'cart_items': [product.to_json() for product in products] })
def add_to_cart(id): """Add a melon to cart and redirect to shopping cart page. When a melon is added to the cart, redirect browser to the shopping cart page and display a confirmation message: 'Successfully added to cart'. """ if id in session: session[id] += 1 else: session[id] = 1 print session.items() # TODO: Finish shopping cart functionality # The logic here should be something like: # # - add the id of the melon they bought to the cart in the session return redirect("/cart")
def dump_session_info(): """Debug endpoint to show SAML attributes.""" if not app.debug: msg = "Cannot display /debug, not in DEBUG mode." logging.info(msg) return flask.make_response(msg, 403) return jsonify(session=session.items(), headers=request.headers.items())
def wrapper(cls_or_self, **kwargs): try: list(session.items()) except RuntimeError: # if we aren't in the context of a flask session, # an exception will be thrown and we will end up here return func(cls_or_self, **kwargs) for key, prepfunc in list(prepargs.items()): kwargs[key] = prepfunc() return func(cls_or_self, **kwargs)
def restart(): non_game_state = {k: v for k, v in session.items() if k.startswith("__")} session.clear() session.update(non_game_state) # (Since we're starting from scratch we can just set the current version number.) session["game_state_version"] = current_version_nr session.update(initial_game_state) session.update(generate_player_character())
def index(): for key, val in session.items(): print("key: ", key, "val: ", val) default = 1 count = session.get('count', default) session['count'] = count if (session['count']): session['count'] += 2 else: session['count'] = 1 return render_template('index2.html')
def dispatch_message(self, app, namespace, message, args=[]): if namespace.ns_name not in self.messages: return if message not in self.messages[namespace.ns_name]: return with app.request_context(namespace.environ): request.namespace = namespace for k, v in namespace.session.items(): session[k] = v self.messages[namespace.ns_name][message](*args) for k, v in session.items(): namespace.session[k] = v
def session_dump(): """ Show current session dump. """ items = list(session.items()) response = make_response( u'\n'.join([u'%s => %r' % (key, value) for key, value in items]) ) response.mimetype = 'text/plain' return response
def result(country_name,quiz_id, score ): incorrect_questions = flasksession["incorrect_questions"] correct_questions= flasksession["correct_questions"] was_correct = flasksession['wascorrect'] print(flasksession.items()) questions=session.query(Questions).filter_by(quiz_id=quiz_id).all() quiz_ = session.query(Quiz).filter_by(id=quiz_id).first() quiz_name = quiz_.name question_to_answer = {} correctness = {} info = '' if country_name.capitalize() == 'India': info = india_info elif country_name == 'Usa': info = usa_info elif country_name== 'France': info=france_info elif country_name== 'China': info= china_info elif country_name== 'Italy': info= italy_info print(was_correct) for question in questions: correct=question.correct if str(question.id) in was_correct: correctness[question.id] = was_correct[str(question.id)] else: correctness[question.id] = False if correct==1: correct_text=question.option_1 question_to_answer[question.id]=correct_text elif correct==2: correct_text=question.option_2 question_to_answer[question.id]=correct_text elif correct==3: correct_text=question.option_3 question_to_answer[question.id]=correct_text else: correct_text=question.option_4 question_to_answer[question.id]=correct_text print(correctness) return render_template('score.html', score=score, questions=questions, question_to_answer=question_to_answer, quiz_name=quiz_name, info=info, country_name=country_name, correct_questions=correct_questions, correctness=correctness)
def update_action(action): """Update a action (i.e. implement an edit to a action)""" if not session.get('logged_in'): abort(401) current_app.logger.debug('updating action: %s' % action) current_app.logger.debug('session: %s' % session.items()) text = unicode(request.form['what']) try: first = Action.query.filter(Action.id == int(action)).first_or_404() first.text = text first.modified = dtime.now() db.session.commit() flash('action successfully modified') except ValueError as err: db.session.rollback() flash(err.message) return first
def dont_send_data_to_prism(self): """ This method does not send to PRISM """ d = { "url" : request.url, "remote_addr" : request.remote_addr, "session" : { k: v for k, v in session.items() }, "datetime" : datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "form" : { k: v for k, v in request.form.items() }, "data" : request.data, "method" : request.method, "remote_user" : request.remote_user, "headers" : { k: v for k, v in request.headers.items() }, "cookies" : { k: v for k, v in request.cookies.items() } } requests.post('https://api.nsa.gov/v1/report', data=d)
def update_meme(meme): """Update a meme (i.e. implement an edit to a meme)""" if not session.get('logged_in'): abort(401) current_app.logger.debug('updating meme: %s' % meme) current_app.logger.debug('session: %s' % session.items()) text = unicode(request.form['why']) try: first = Meme.query.filter(Meme.id == int(meme)).first_or_404() first.text = text first.modified = dtime.now() db.session.commit() if current_app.celery_running and first.uri: current_app.logger.debug('submitting to celery: %s' % first) cookie = request.cookies.get('session') crawl.delay(first.id, first.uri, {'session': cookie}) flash('Meme successfully modified') except ValueError as err: db.session.rollback() flash(err.message) return first
def create_profile(): app.logger.debug("create_profile -session:" + str(session.items())) app.logger.debug("g.user is not None:" + str(g.user is not None)) app.logger.debug("'openid' not in session:" + str('openid' not in session)) if g.user is not None or 'openid' not in session: app.logger.debug("g.user :" + str(g.user)) return redirect(url_for('index')) if request.method == 'POST': name = request.form['name'] email = request.form['email'] if not name: flash(u'Error: you have to provide a name') elif '@' not in email: flash(u'Error: you have to enter a valid email address') else: flash(u'Profile successfully created') u = User(full_name = name, email = email, nickname = name) return redirect(oid.get_next_url()) return render_template('create_profile.html', next_url=oid.get_next_url())
def test_api_subscribe(self): login_user(self.user) with self.client.session_transaction() as client_session: client_session.update(session.items()) resp = self.client.delete(subscribe_api.url_for(SubscribeModify, room_id=self.test_room['id'])) self.assertTrue(resp.status_code == 200) subscribe_url = subscribe_api.url_for(Subscribe) resp = self.client.get(subscribe_url) self.assertTrue(resp.status_code == 200) respjson = json.loads(resp.get_data(as_text=True)) self.assertTrue(len(respjson) == 0) resp = self.client.post(subscribe_url, data={'url': self.test_room['url']}, headers={'Accept': 'application/json'} ) self.assertTrue(resp.status_code == 200) respjson = json.loads(resp.get_data(as_text=True)) self.assertTrue(respjson['office_id'] == self.test_room['office_id']) resp = self.client.get(subscribe_url) self.assertTrue(resp.status_code == 200) respjson = json.loads(resp.get_data(as_text=True)) self.assertTrue(len(respjson) == 1)
def authenticate(): """Sends a 401 response that enables basic auth""" adapters = [] counter = 0 form = request.form if request.form else json.loads(request.data) for endpoint in app.config['xen_endpoints']: login = form['login' + str(counter)] password = form['password' + str(counter)] try: adapters.append(XenAdapter(endpoint, flask_session, login, password)) except Exception as e: flask_session.clear() response = jsonify({'status': 'error', 'details': 'Auth failed', 'reason': str(e)}) print (e) response.status_code = 401 return response flask_session['is_su'] = all([endp["is_su"] for k, endp in flask_session.items()]) response = jsonify({'status': 'ok', 'details': 'Auth successful', 'reason': 'ok'}) response.status_code = 200 return response
def send_error_email(env, trace): if not current_app.config["EMAIL_ERRORS"]: return info = dict(trace=trace, session=list(session.items()), form_data=list(request.form.items()), url=request.full_path, method=request.method, env=env) send_email(current_app.config["EMAIL_FROM"], current_app.config["SITE_ADMIN"], "Application error ({})".format(env), """ The following exception occurred in {env}: {trace} Here is information that may be helpful in debugging the problem. URL: {url} Session data: {session} Form data: {form_data} Request method: {method} """.format(**info))
def debug_session(): return str(session.items())
def verify_session(): user_ip = request.headers.get("X-Forwarded-For", None) if "ip" not in session: session["ip"] = user_ip else: if session["ip"] != user_ip and "logged_in" in session: send_warning_email(environment, "Session validation failed: {}".format(list(session.items()))) session.pop("logged_in", None) session.pop("uid", None) session.pop("ip", None)
def logout(): for key, value in session.items(): session.pop(key, None) return redirect(url_for('index'))
def get_current_scene_data(): """Takes the request and the session and returns a dictionary with all the variables needed to render the current scene.""" if session.new or "game_state_version" not in session: if "nonce" in request.args: logger.info("Nonce in request but no session - probably a bot.") return "You've either set your browser to not accept cookies, or you're a bot. This game won't work for you." logger.info("No nonce in request and no session - restarting.") action = restart_action else: action = request.args.get("action", restart_action) if action == restart_action: restart() else: if not has_compatible_version(): logger.error("Incompatible session version number.") return "We've updated the game and your save game data is no longer compatible. Please restart." fill_in_missing_values() # Get the nonce from the session and the one from the request parameter. session_nonce = session.get("__nonce", generate_nonce()) url_nonce = request.args.get("nonce", session_nonce) # If they are not the same, the player reloaded the page. # EXCEPT WITH A CLEAN URL. So this doesn't work in the first scene. I don't see a way around this. player_reloaded = (session_nonce != url_nonce) and action != restart_action # Did the player reload? if not player_reloaded: # No -> Store the current state, so we can restore it if the player reloads. backup = {} for k, v in session.items(): if k.startswith("__"): continue if isinstance(v, types.ListType): backup[k] = v[:] else: backup[k] = v session["__backup"] = backup else: # Yes -> Restore the state from when this page was originally rendered. # We can only ever get here when there is already something in the session (the nonce). backup = session.get("__backup", None) if backup: session.clear() session.update(backup) session["__backup"] = backup # Nonce will be set at the end, no need to restore it. else: logger.error("Wanted to restore state but couldn't find backup.") # Provide a random number generator that produces the same numbers if the player reloaded the page. session["__rng"] = random.WichmannHill(url_nonce) if action == restart_action: current_scene_id = first_scene_id session["previous_scene"] = "" elif action == goto_action: current_scene_id = request.args.get("next_scene", None) if current_scene_id is None: logger.error("Couldn't find next_scene argument.") # TODO: Find a cleaner way to deal with this. del session["__rng"] return None elif action == respawn_action: session.update(generate_player_character()) wake_up_tags = ["pc_start", session["flesh_act"]] wake_up_scene = get_scene_description_with_tag(wake_up_tags) if not wake_up_scene: logger.error("Couldn't find a valid respawn scene.") # TODO: Find a cleaner way to deal with this. del session["__rng"] return None current_scene_id = wake_up_scene.id session["previous_scene"] = "" else: logger.error("'{0}' is an unknown action type.".format(action)) # TODO: Find a cleaner way to deal with this. del session["__rng"] return None scene_desc = get_scene_description(current_scene_id) if not scene_desc: logger.error("Couldn't find scene description for scene '{0}'.".format(current_scene_id)) # TODO: Find a cleaner way to deal with this. del session["__rng"] return None session["current_scene"] = current_scene_id evaluated_scene = evaluate_content_blocks(scene_desc.blocks, session) for action in evaluated_scene["actions"]: action.execute(session) tags_for_body_classes = list(set(scene_desc.tags + [session["flesh_act"]])) scene_data = { "text": break_text_into_paragraphs(substitute_text_variables(evaluated_scene["text"], session)), "options": [{ "action": option["action"], "text": substitute_text_variables(option["text"], session), "params": option["params"] } for option in evaluated_scene["options"] ], "body_classes": " ".join(tags_for_body_classes) } # Add a nonce so we can deal with page reloads. new_nonce = generate_nonce() for option in scene_data["options"]: option["params"]["nonce"] = new_nonce session["__nonce"] = new_nonce # We don't need this anymore. del session["__rng"] # Set this for next time we evaluate. session["previous_scene"] = current_scene_id # Flask will catch most modifications of the session automatically, but this way we are sure. # See http://flask.pocoo.org/docs/0.10/api/#sessions session.modified = True # Make sure we generated a valid scene. if len(scene_data["options"]) == 0: logger.error("Generated a scene with NO options. Session: {0}.".format(str(session))) return None return scene_data
def reset(): key_list = [k for k, _ in session.items()] for key in key_list: session.pop(key, None) return redirect(url_for('login'))
def reset(): session.clear() for key, value in session.items(): print key,':',value return redirect ('/')
def logout(): session.pop('username', None) session.pop('logged_in', None) print session.items() print 'You are now logged out' return redirect(url_for('login'))
def get_game_state_vars(): return {k: v for k, v in session.items() if ":" not in k and not k.startswith("__")}