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

如何在FastHTML中为响应添加多个Cookie?

如何在FastHTML中为响应添加多个Cookie?

我来帮你解决FastHTML里设置多个Cookie的问题!你遇到的情况其实是因为FastHTML默认处理响应头时,重复的set-cookie键会被后面的覆盖,所以只保留了最后一个Cookie。下面给你两种可行的解决办法:

方法一:直接构建包含多个Cookie的响应头列表

通过fh.Response对象包装内容和响应头,把多个Cookie的字符串放到set-cookie对应的列表里,这样浏览器就能接收到多个Set-Cookie头:

from fasthtml import common as fh
@app.get("/route1")
def getroute1(request):
    # 准备响应内容
    content = fh.P("This is a test")
    # 定义多个符合格式的Cookie字符串
    headers = {"set-cookie": [
        'cookie1=value1; Path=/; SameSite=lax',
        'cookie2=value2; Path=/; SameSite=lax'
    ]}
    # 返回包装好的响应
    return fh.Response(content, headers=headers)

方法二:复用fh.cookie生成Cookie字符串

如果你不想手动编写Cookie格式的字符串,可以先用fh.cookie生成单个Cookie的内容,再把它们收集到列表中:

from fasthtml import common as fh
@app.get("/route1")
def getroute1(request):
    # 用fh.cookie生成单个Cookie的字符串
    cookie1_str = fh.cookie('cookie1', 'value1').v
    cookie2_str = fh.cookie('cookie2', 'value2').v
    # 将多个Cookie字符串放入响应头列表
    headers = {"set-cookie": [cookie1_str, cookie2_str]}
    # 返回响应
    return fh.Response(fh.P("This is a test"), headers=headers)

这两种方法都能让浏览器正确保存多个Cookie。之前你直接返回多个fh.cookie或fh.HttpHeader实例时,FastHTML会将相同键的响应头覆盖,只保留最后一个,所以才会出现只有最后一个Cookie被保存的问题。

备注:内容来源于stack exchange,提问作者Ximo Dante

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 03:19:45