I am developing a web tool and am having some problems with setting cookies. I used to do this in Perl 20 years ago and am shocked that there doesn't seem to be a clear and clean way to handle cookies with Python in 2017! What I thought would be easy and quick has taken all day. I have experimented with manually setting cookies, using the requests module, and a multitude of partial code examples I found on Stack Overflow. Everywhere I look, the documentation is poor, there are no complete working examples, or the answers are old.
I am creating a cgi script with Python. On the login page of the script, I have print "Content-type: text/html\r\n" in order to have a text box and select menu appear on the web page. When the user clicks submit, I have a validation step that needs to print something to the page if there is an error. If there are no errors, I need the script to load a new page and set a cookie.
Here is the code I am using to set my cookies:
#!C:\Python27\python.exe -u
import Cookie
c = Cookie.SimpleCookie()
c['id'] = '12345'
c['score'] = '8.76'
c['page'] = '3'
print "Content-type: text/html %s;\r\n" % (c)
print ""
print c
The problems are:
- Only two of the three c values shown above are stored as cookies when I check "Show Cookies" in Firefox after running the above code by itself.
- The page that I land on in the script shows
Content-type: text/html Set-Cookie: score=8.76 Set-Cookie: id=12345 Set-Cookie: page=3 ;at the top, due to setting the cookies with a print statement and sending the Content-type again. When this happens, no cookies are stored in my browser. Cookies are only stored if isn't already aContent-type: text/htmlin the headers.
Is there a way to set cookies from inside my script without printing another copy of Content-type: text/html to the browser?
I also need a way to seemlessly update cookies when the user moves around in the tool. For example, when they click the next page, the cookie would update to the next page number.
I am using Python 2.7 on Windows 10 and am using Firefox as my test browser.