gpt4 book ai didi

python - 如何将 set_cookie 值设置为 Python Flask 的整数?

转载 作者:行者123 更新时间:2023-12-03 17:01:07 25 4
gpt4 key购买 nike

我刚刚学习 Flask 框架,在做练习时我遇到了一个问题,出于某种原因我无法将 cookie 存储为整数,当我将变量 count 转换为存储它之前的字符串。这是我的代码:

from flask import Flask, render_template, session, request, make_response, redirect
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'


@app.route('/')
def index():
if 'counter' in request.cookies:
count = int(request.cookies.get('counter')) + 1
resp = make_response(render_template('index.html', c=count))
resp.set_cookie('counter', str(count))
else:
resp = make_response(render_template('index.html', c=1))
resp.set_cookie('counter', '1')

return resp

@app.route('/addtwo', methods=['get'])
def add_two():
if 'counter' in request.cookies:
count = int(request.cookies.get('counter')) + 1
resp = make_response(redirect('/'))
resp.set_cookie('counter', str(count))
else:
resp = make_response(redirect('/'))
resp.set_cookie('counter', '2')

return resp

@app.route('/reset', methods=['get'])
def reset():
resp = make_response(redirect('/'))
resp.set_cookie('counter', '0')
return resp


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

最佳答案

答案在评论里。不要在没有答案的情况下离开问题 - 引用 dirn:

Checking if 'counter' in request.cookies and using request.cookies.getis unnecessary. If the if passes, the key is there and can be accesseddirectly request.cookies['counter']. Better yet, you can remove the ifentirely and just use int(request.cookies.get('counter', 0)) + 1regardless of whether or not the cookie has already been set

关于python - 如何将 set_cookie 值设置为 Python Flask 的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38080515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com