【问题标题】:Sending cookies between Flask and javascript and using Flask-session在 Flask 和 javascript 之间发送 cookie 并使用 Flask-session
【发布时间】: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


    【解决方案1】:

    flask 中的会话实现为客户端会话,将所有会话内容保存为客户端 cookie。 flask-session 扩展为会话提供了一些其他的服务器存储。例如。 app.config["SESSION_TYPE"] = "filesystem" 将会话内容保存在服务器上的文件中。

    但是这两种方法仍然依赖于Cookie。服务器端会话存储需要从客户端Cookie获取session_id

    您需要在 Fetch API 上启用 cookie 发送。

    fetch, sending cookies

    【讨论】:

      【解决方案2】:

      尝试使用fetchcredentials:'include' 来让浏览器发送带有包含在服务器端调用中的凭据的请求:

      fetch('deploy', {
        method: 'GET',
        credentials: 'include'
      }).then(navigate);
      

      使用它,您将在results 路由中访问session['contract_address']

      flask-session 在您的浏览器中设置一个带有密钥会话的 cookie,使用credentials:'include' 获取在网络调用中包含此 cookie 值。

      【讨论】:

      • @Danjoe4 如果可行,请接受答案:)
      猜你喜欢
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2017-12-01
      • 2021-07-24
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多