【发布时间】:2021-10-12 05:55:29
【问题描述】:
我是网络开发新手,但我会尽力弄清楚问题,解释我的方法以及我尝试过的方法。我还包括导入以防万一导致问题,但我很确定我已将其隔离到我所描述的范围内。
我正在尝试使用 Flask-session 来保持信息的私密性,但有些值“丢失”了。为简单起见,此代码被显着缩减。用户登陆/send,我们渲染加载模板。 loading.js 在运行动画时对/deploy 执行fetch(),然后()在部署功能完成后转到/results。
加载.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,但我对如何实现它有点迷茫。 cookie 是不是不必要的(因为服务器实际上不需要从我的 js 文件中接收任何数据)?我应该使用重定向还是 fetch() 之外的其他东西?
Hacky 修复、不同的方法和资源都是受欢迎的。我觉得我很接近了,好像有一种使用我忽略的 cookie 的简单方法。
我将继续研究并详细说明我正在考虑的方法 Edit1:查看 Flask 的 should_set_cookie 方法
【问题讨论】:
标签: javascript python flask session-cookies fetch-api