Search code examples
pythonpython-3.xfasthtml

How to add several cookies to response in FastHTML?


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') 

Solution

  • 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