Simple CGI Script in Python: Difference between revisions
No edit summary |
No edit summary |
||
Line 27: | Line 27: | ||
print "<dd>" + os.environ[key] + "</dd>" | print "<dd>" + os.environ[key] + "</dd>" | ||
print "</dl>" | print "</dl>" | ||
</source> | |||
== "Discriminating" Response based on IP Address == | |||
interesting headers: | |||
* HTTP_USER_AGENT (string identifying the user's browser, also often includes information about the computer / operating system as well) | |||
* REMOTE_ADDR (the IP address of the user's machine *or* gateway) | |||
* REQUEST_METHOD (either "GET" or "POST") | |||
* QUERY_STRING (the stuff after the '?' in the users's request URL) | |||
* HTTP_ACCEPT_LANGUAGE (language code set by user's browser) | |||
<source lang="python"> | |||
#!/usr/bin/env python | |||
#-*- coding:utf-8 -*- | |||
import os | |||
print "Content-type: text/html" | |||
print | |||
addr = os.environ['REMOTE_ADDR'] | |||
last = addr.split(".")[-1] | |||
agent = os.environ.get("HTTP_USER_AGENT") | |||
if agent == None: | |||
print "Go away bot!" | |||
if (last == "174"): | |||
print 'Welcome "%s"' % agent | |||
else: | |||
print '<img src="http://www.kuliniewicz.org/hotlink/hotlink.png" />' | |||
</source> | </source> |
Revision as of 17:25, 12 January 2011
The Python documentation is a pretty good place to start: http://docs.python.org/library/cgi.html
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
Show Headers
HTTP headers are simply environment variables. Use the os.environ dictionary to get at them.
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
print "Content-type: text/html"
print
# show all headers as an HTML definition list
print "<dl>"
for key in os.environ:
print "<dt>" + key + "</dt>"
print "<dd>" + os.environ[key] + "</dd>"
print "</dl>"
"Discriminating" Response based on IP Address
interesting headers:
- HTTP_USER_AGENT (string identifying the user's browser, also often includes information about the computer / operating system as well)
- REMOTE_ADDR (the IP address of the user's machine *or* gateway)
- REQUEST_METHOD (either "GET" or "POST")
- QUERY_STRING (the stuff after the '?' in the users's request URL)
- HTTP_ACCEPT_LANGUAGE (language code set by user's browser)
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
print "Content-type: text/html"
print
addr = os.environ['REMOTE_ADDR']
last = addr.split(".")[-1]
agent = os.environ.get("HTTP_USER_AGENT")
if agent == None:
print "Go away bot!"
if (last == "174"):
print 'Welcome "%s"' % agent
else:
print '<img src="http://www.kuliniewicz.org/hotlink/hotlink.png" />'