Python Bottle - TypeError: Secret key missing for non-string Cookie.

Python Bottle - TypeError: Secret key missing for non-string Cookie.
I was trying to set several cookies using the Python Bottle micro framework and ended up getting a 500 server error along with the above message. So I searched Google to find a solution for this, but I couldn't find any webpage that would help me. Then I opened the Bottle's documentation and read the cookies section, and there was another sub section under cookies, called Signed Cookies.

There I found that response.set_cookie() accepts a third parameter to encrypt the stored cookie. Although it's mentioned in the documentation that the cookie is still readable by the user, it was not directly readable, meaning it had an encryption. Apparently, the error was solved by using this third parameter, but when I try to read the cookie, it was encrypted. But I wanted to have a non-encrypted cookie.

But if I tried to use the response.set_cookie() without the “secret” parameter, it always gave me this error. TypeError: Secret key missing for non-string Cookie. Since I was not ready to keep the cookie encrypted, I tried to find the error in my code and found that I cannot have non-string cookies without the encryption. The third parameter was not needed if it's a string. But if the cookie value is something other than a string, say an Integer, it had to be encrypted with the secret key parameter.

Here is a section of the original code.

            response.set_cookie("session_key", login_user[0]["session_key"])
            response.set_cookie("loggedIn", 1)  #this gives the error.
            response.set_cookie("first_name", login_user[0]["first_name"])
            response.set_cookie("last_name", login_user[0]["last_name"])
            response.set_cookie("username", username)

If you notice the second line, it is an integer value. So it has to have the “secret” parameter. But If I pass the “secret” parameter, the values will be encrypted. Then I changed the integer to a string by wrapping it with quotes as shown below, and it solved my problem.

           response.set_cookie("loggedIn", “1”)

I hope this will be useful to someone in the future because I didn't find any tutorial to help me with this when I had this problem. So I'm sharing my experience. If you think this is a bad practice, or if you know any better solution than this, please feel free to leave a comment and let others know it :)

2 comments :

  1. Nearly 3 years later, and this issue is still an issue. Using bottle-0.12.9 and I tripped over it today. Thanks for the helpful post!

    ReplyDelete