使用 bottle.py 为静态文件设置 cookie

Setting cookies for static files using bottle.py

python 的新手。我正在使用 bottle.py 作为网络服务器。

我有一组静态 HTML 文件需要在不同的路由上呈现。我正在使用 static_file() 函数。我还想为页面设置一个基于会话的 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'])

好吧,我刚试过,确实不行,我之前从未尝试过将 cookie 与 static_file() 一起使用...但是,您可以对 return 静态文件执行以下操作文件作为模板,将设置 cookie :

您的路由功能:

@route('/test')
def cookie_test():
    response.set_cookie("test", "Yeah")
    return template('template/test.html')

为此,您需要以这种方式为 /template 定义路由:

@route('/template/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root="./template")

(显然,根据您的项目路径将“/template”更改为您需要的任何内容!)

我就是这样做的,效果很好!我不确定为什么当您尝试使用 static_file() 设置 cookie 时它不起作用,这可能是因为它是您正在提供的静态文件,或者其他什么,我真的不知道。

此外,使用 template() 函数来为 "static" html 页面提供服务可能不是正确的方法,但我个人已经这样做了一段时间,我从来没有遇到过任何问题。

希望对您有所帮助!

欢迎使用 Bottle 和 Python。 :)

看看Bottle source code,问题就很明显了。看看static_file如何结束:

def static_file(...):
    ...
    return HTTPResponse(body, **headers)

static_file 创建一个 new HTTPResponse object--所以你之前设置的任何 headers 都将是丢弃。

解决此问题的一个非常简单的方法是在您调用 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

我刚刚试过了,效果很好。祝你好运!