【发布时间】:2015-11-03 01:51:33
【问题描述】:
在我的 make_session 函数中,如果表单中的密码与某些凭据不匹配,则它会返回一个字符串,该字符串最终被存储为名为 session 的 cookie。在我的索引文件中,我在 index.html 上设置了它,如果 cookie 值为 {},它会询问登录信息。如果我通过将“invalid”替换为任何整数来更改 make_session 函数返回的内容,代码将按预期工作。
我的问题的一个不好的解决方案是添加
except:
data = {}
在返回到我的 get_saved_data 函数之前设置数据等于 {} 但这最终会得到相同的结果,就好像我的浏览器中根本没有 cookie,但它消除了我的错误:https://gist.github.com/anonymous/e101aa46f154a075b038
我怀疑 get_saved_data 函数可能有问题。
我的目录地图:
|---- layout.html
|---- index.html
|--- templates -|
Project -|
|--- test.py
test.py:
from flask import Flask, render_template, redirect, url_for, request, make_response
import json
def get_saved_data(key):
try:
data = json.loads(request.cookies.get(key))
except TypeError:
data = {}
return data
def make_session(form_data):
if form_data.get('username') == "username" and form_data.get('password') == "password":
return "12345"
else:
return "invalid"
app = Flask(__name__)
@app.route('/')
def index():
data = get_saved_data("session")
return render_template('index.html', saves=data)
@app.route('/login', methods=['POST'])
def login():
response = make_response(redirect(url_for('index')))
response.set_cookie("session", make_session(dict(request.form.items())))
return response
app.run(debug=True, host='0.0.0.0', port=8000)
index.html:
{% extends "layout.html" %}
{% block content %}
{% if saves == {}: %}
<p>Please log in.</p>
{% else: %}
<p>Your Session value is: {{ saves }}</p>
{% endif %}
{% if saves == {}: %}
<form action="{{ url_for('login') }}" method="POST">
<p>We take your private information very seriously. All data is encrypted not once but twice! in ROT13 to provide the best security.</p><br />
<label for="username">Please enter your username:</label>
<input type="text" name="username" /><br />
<label for="password">Please enter your password:</label>
<input type="text" name="password" /><br />
<button class="btn">Log In</button>
</form>
{% endif %}
{% endblock %}
layout.html:
<!DOCTYPE html>
<html>
<head>
<title>Character Generator</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
【问题讨论】:
标签: python json python-3.x cookies flask