Python 新手。我正在使用 bottle.py 作为 Web 服务器。
我有一组静态 HTML 文件需要在不同的路由上呈现。我正在使用 static_file() 函数。我还想为页面设置一个基于 session 的 cookie。所以我正在使用 response.set_cookie()。
但事实证明,当我返回一个 static_file 时,cookie 从未被设置。但是,如果我将响应更改为一个简单的字符串,set_cookie() 可以正常工作。谁能解释为什么?我该如何解决这个问题?
@app.route("/index")
def landingPage():
response.set_cookie("bigUId", "uid12345")
# return "Hello there"
return static_file("/html/index.html", root=config.path_configs['webapp_path'])
请您参考如下方法:
欢迎使用 Bottle 和 Python。 :)
查看 Bottle source code ,问题就很明显了。看看 static_file 是如何结束的:
def static_file(...):
...
return HTTPResponse(body, **headers)
static_file 创建一个新 HTTPResponse 对象——因此您之前设置的任何 header 都将被丢弃。
解决此问题的一个非常简单的方法是在调用 static_file 之后 设置 cookie,如下所示:
@app.route("/index")
def landingPage():
resp = static_file("/html/index.html", root=config.path_configs["webapp_path"])
resp.set_cookie("bigUId", "uid12345")
return resp
我刚刚试过了,效果很好。祝你好运!
