我是一个web开发新手,但我会尽最大努力弄清楚这个问题,解释我的方法,以及我尝试过的东西。我也包括了导入,以防那些导致了问题,但我很确定我已经把它隔离到我所描述的地方了。
我试图使用Flask-session来保护信息的私密性,但是一些值“丢失”了。为了简单起见,这段代码被大幅删减了。用户登陆/send,我们呈现加载的模板。loading.js在运行动画时在/deploy上执行fetch(),然后()我们在部署函数完成后转到/results。
loading.js
function navigate() {
window.location.href = 'results'; // redirect to results page when done!
}
// deploy the contract while the loading screen goes then navigate to results page
const data = fetch('deploy').then(navigate);
loopThroughMessages(messages);main.py
from flask_session import Session
app = Flask(__name__,
static_folder='static',
template_folder='templates')
# for the session, i.e passing values
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config.from_object(__name__)
Session(app)
@app.route('/send')
def main():
# take url parameters and do stuff with them
return render_template('loading.html')
@app.route("/deploy")
def deploy_contract():
session['contract_address'] = some_fnc()
# fetch() requires that this function return a json
return {}
@app.route("/results")
def serve_results_page():
# pull saved values from the session
data = {'contract_key' : session['contract_address']
} # calling session here causes the error, the contract_address key doesn't exist
return render_template('results.html', data=data)因此,contract_address被保存到会话中,但是当我们到达/results时,服务器无法将该会话与客户端相关联。
我们想让我们的contract_address保持私有,所以不能把它发送给loading.js。我猜由于http是无状态的,所以我需要在js和python文件之间传递cookie,但我对如何实现它有点迷惑。cookies是不必要的吗(因为服务器实际上不需要从我的js文件接收任何数据)?我应该使用重定向或者除了fetch()之外的其他东西吗?
麻烦的修复、不同的方法和资源都是受欢迎的。我觉得我已经很接近了,好像有一种简单的方式可以使用我忽略的cookie。
我将继续研究和详细介绍我正在考虑的方法:查看Edit1的should_set_cookie方法
发布于 2021-08-08 09:32:53
flask中的会话被实现为客户端会话,将所有会话内容保存为客户端cookie。flask-session扩展为会话提供了一些其他服务器存储。例如,app.config["SESSION_TYPE"] = "filesystem"将会话内容保存在服务器上的文件中。
但这两种方法仍然依赖于Cookie。服务器端会话存储需要从客户端Cookie获取session_id。
Fetch接口需要开启cookie发送功能。
发布于 2021-08-08 16:43:39
尝试使用credentials:'include'的fetch,以使浏览器发送包含在服务器端调用中的凭据的请求:
fetch('deploy', {
method: 'GET',
credentials: 'include'
}).then(navigate);使用它,您将在results路由中访问session['contract_address']。
flask-session使用浏览器中的关键会话设置cookie,fetch with credentials:'include'在网络调用中包含此Cookie值。
https://stackoverflow.com/questions/68696808
复制相似问题