最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to add several cookies to response in FastHTML? - Stack Overflow

programmeradmin1浏览0评论

There are similar questions (Add several cookies in IHTTPResponse and Setting several cookies in same response) but they are not about FastHTML.

I want to add 2 or more cookies to the response (cookie1 and cookie2 in the example)

from fasthtml import common as fh
@app.get("/route1")
    def getroute1(request):
       return fh.P("This is a test"), fh.cookie('cookie1', 'value1'), fh.cookie('cookie2', 'value2')

Only the last cookie (cookie2) is stored, even if I add more cookies.

I have also tried this return sentence, with the same result (only the last cookie is stored)

return fh.P("This is a test"),
fh.HttpHeader(k='set-cookie', v='cookie1=value1; Path=/; SameSite=lax'),
fh.HttpHeader(k='set-cookie', v='cookie2=value2; Path=/; SameSite=lax') 

There are similar questions (Add several cookies in IHTTPResponse and Setting several cookies in same response) but they are not about FastHTML.

I want to add 2 or more cookies to the response (cookie1 and cookie2 in the example)

from fasthtml import common as fh
@app.get("/route1")
    def getroute1(request):
       return fh.P("This is a test"), fh.cookie('cookie1', 'value1'), fh.cookie('cookie2', 'value2')

Only the last cookie (cookie2) is stored, even if I add more cookies.

I have also tried this return sentence, with the same result (only the last cookie is stored)

return fh.P("This is a test"),
fh.HttpHeader(k='set-cookie', v='cookie1=value1; Path=/; SameSite=lax'),
fh.HttpHeader(k='set-cookie', v='cookie2=value2; Path=/; SameSite=lax') 
Share Improve this question edited Feb 11 at 6:43 Ximo Dante asked Jan 21 at 7:30 Ximo DanteXimo Dante 12511 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I have converted the fastHTML component to "XML" and created a Response object as a workaround. Here is the code:

from fasthtml import common as fh
    
@app.get("/route1")
def getroute1(request):
    my_fh= fh.P("This is a test")
    # Get the html code generated by fastHTML and create the Response object
    my_resp=fh.Response(fh.to_xml(my_fh))
    # Add 2 cookies to the response
    my_resp.set_cookie(key="cookie1", value="value1", httponly=True, max_age=3600)
    my_resp.set_cookie(key="cookie2", value="value2", httponly=True, max_age=3600)
    return my_resp
发布评论

评论列表(0)

  1. 暂无评论