You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中增量更新cookie值时visit_count设置失效、返回None问题咨询

故障原因分析
  • 类型判断逻辑错误:从request.cookies中取出的所有值都是字符串格式,你代码中写if vc==1:是拿字符串和整数比较,永远返回False,不会进入首访分支。
  • Cookie读取时机错误:set_cookie方法是把Cookie配置写入待返回的响应中,需要浏览器接收响应后才会存储该Cookie,下次请求时才会携带到服务端。你在当前请求的处理逻辑里刚设置完visit_count就直接从本次的request.cookies里取值,本次请求的请求头根本没有这个Cookie,所以读取结果为None。
  • 统计逻辑设计错误:你设置了两个不相关的Cookieuser_visit和visit_count,没有把访问次数的自增逻辑和实际访问行为绑定,完全达不到统计访问次数的效果。

修正后参考代码

from flask import Flask, render_template, request, make_response

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def show_page():
    return render_template('cookiecounter.html')

@app.route('/visit', methods=['GET','POST'])
def visit():
    # 直接读取访问次数字段,首访默认是0
    visit_count = request.cookies.get('visit_count', 0)
    visit_count = int(visit_count) + 1
    resp = make_response(f'这是你的第 {visit_count} 次访问')
    resp.set_cookie('visit_count', str(visit_count), max_age=5*60*60)
    return resp

if __name__=="__main__":
    app.run(debug=True)

内容的提问来源于stack exchange,提问作者PRJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:45:06