Skip to content

Instantly share code, notes, and snippets.

@alanduan
Created September 10, 2013 06:35
Show Gist options
  • Save alanduan/6505720 to your computer and use it in GitHub Desktop.
Save alanduan/6505720 to your computer and use it in GitHub Desktop.
cgi demo
#!/usr/bin/env python
import cgi
import os
import sys
import Cookie
def init_page(user='guest'):
return '''Content-Type: text/html
<!DOCTYPE HTML>
<html>
<p>hello: %s</p>
<form method=post>
login as: <input type=text name=name />
</form>
</html>
''' % user
cookie_name = request_name = ''
if os.environ.has_key('HTTP_COOKIE'):
cookie = Cookie.SimpleCookie()
cookie.load(os.environ['HTTP_COOKIE'])
if cookie.has_key('name'):
name = cookie['name'].value
if name:
cookie_name = name
form = cgi.FieldStorage()
name = form.getfirst('name', '')
if name:
request_name = name
if not cookie_name and not request_name:
print init_page()
elif request_name and (request_name != cookie_name):
# TODO: verify the user name
cookie = Cookie.SimpleCookie()
cookie['name'] = request_name
print 'Content-Type:text/plain'
print 'Refresh:1'
print cookie
print
print 'login as:', request_name
sys.exit()
else:
print init_page(cookie_name)
print '<pre>'
print cgi.escape(open('demo', 'r').read())
print '</pre>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment