Python CGI
Python CGI
• <html>
• <body>
• <form method = 'post' action = '/cgi-bin/formtest.py' target = _blank>
• First Name: <input type = 'text' name = 'first_name'> <br />
• Key Value
• # To save one line of code
• # we replaced the print command with a '\n'
• print ('Content-Type: text/html\n')
• # End of HTTP header
• print ('<html><body>')
• print ('Server time is', time.asctime(time.localtime()))
• print ('</body></html>')
Set Cookie using http.cookies Module
• from http.cookies import SimpleCookie
• >>> c= SimpleCookie()
• >>> c["a"]= 1
• >>> c["b"]=2
• >>> print(c) // Generate HTTP Headers
• Set-Cookie: a=1
• Set-Cookie: b=2
The Cookie Object
• The Cookie module can save us a lot of coding and errors . A cookie can be set using following script:
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe
• import time
• from http.cookies import SimpleCookie
• print('<html><body>')
• print('Server time is', time.asctime(time.localtime()))
• print('</body></html>')
• Save and run this code from your browser and take a look at the cookie saved there. Search for the
cookie name,’lastvisit’.
Reading Cookie Value by server
• The returned cookie will be available as a string in the
os.environ dictionary with the HTTP_COOKIE key. The
environment variable HTTP_COOKIE is set by the web server.
When we rerun a web page the cookies are retrieved as
follows:
•
cookie_string = os.environ.get('HTTP_COOKIE')
• Cookie_string will contain all cookies set by server. This
environment variables is formatted as a series
of key=value pairs delimited by semicolons.
Gettingcookievalue.py
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe
• import time, os
• from http.cookies import SimpleCookie
• cookie = SimpleCookie()
• cookie['lastvisit'] = str(time.time())
• print(cookie)
• print('Content-Type: text/html\n')
• print('<html><body>')
• print('<p>Server time is', time.asctime(time.localtime()), '</p>')
• print('</body></html>')
Cookie
• We will write a script to
• retrieve cookie, initialize counter to zero, or
• increment the value of counter by one, and then
• display the counter value on the page.
Countercookies.py
• import os
• from http.cookies import SimpleCookie
• def increment():
• """
• Retrieves cookie, either initializes counter,
• or increments the counter by one.
• """
• if 'HTTP_COOKIE' in os.environ:
• cnt = SimpleCookie(os.environ['HTTP_COOKIE'])
• else:
• cnt = SimpleCookie()
• if 'visits' not in cnt:
• cnt['visits'] = 0
• else:
• cnt['visits'] = str(1 + int(cnt['visits'].value))
• return cnt
• def main():
• """
• Retrieves a cookie and writes
• the value of counter to the page,
• after incrementing the counter.
• """
• counter = increment()
• print(counter)
• print("Content-Type: text/plain\n")
• print("counter: %s" % counter['visits'].value)