Flask会话在移动端浏览器无法保留问题求助
Flask移动端会话维持问题:iPhone浏览器无法保持会话状态
我是Flask新手,从零开发应用学习框架。该应用在桌面浏览器(Edge、Chrome、Firefox)运行正常,但在iPhone 12的Chrome、Safari、Opera、Firefox等移动端浏览器中无法维持会话,始终返回{'status': False}。
后端初始化代码
from flask import Flask, jsonify, request, make_response, render_template, session, redirect, url_for app = Flask(__name__) app.config['SECRET_KEY'] = "Actual one is a fixed, random string like 89hsfd98sdhf89u983qwj9" @app.route('/') def index(): return render_template('index.html') # This is where the session is created @app.route('/player/add', methods=['POST']) def player_add(): req = request.get_json() session['session_key'] = _generate_session_key(STRING_LENGTH) session['name'] = req['name'] return make_response(jsonify({"result": player.player_add(req['name'], session['session_key'])}), 200) # This is the important one where the session is called @app.route('/player', methods=['GET']) def get_session_name(): try: if not _valid_session(): return make_response(jsonify({'status': False}), 200) data = player.player_info(session['name']) except: data = {'status': False} return make_response(jsonify(data), 200) """ Many more app routes """ if __name__ == '__main__': app.run()
前端通信代码
fetch(`${window.origin}/player`, { method: "GET", credentials: "include", cache: "no-cache", headers: new Headers({ "content-type": "application/json" }) }).then(...)
应用部署在PythonAnywhere上,控制台及后端无报错。我已尝试以下方案但未解决:
- 调用fetch时使用
credentials: "same-origin" - 设置Flask配置:
SESSION_TYPE="filesystem"、SESSION_PERMANENT=False、SESSION_COOKIE_SECURE=True、SESSION_COOKIE_SAMESITE='None' - 使用HTTPS替代HTTP
- 关闭移动端浏览器的“阻止跨站跟踪”功能
- 清理会话并重新生成SECRET_KEY
- 清理浏览器存储的Cookie和历史记录
希望能获得解决该问题的帮助或指导,哪怕是临时的设置方案也可以。
内容的提问来源于stack exchange,提问作者LogicAndTruth
相关产品推荐
相关产品推荐

