Better Python Redirect

Not too long ago, I showed you how to do a simple redirect with Javascript. This works, of course, but it’s far from ideal.

So let’s do it a more correct way.
You ask, “How do we do that and still keep it a hack <scratching head>?”
We will set the Location and Status headers. And to keep things rebellious, we will be using python.

#!/usr/bin/env python
import cgi
url = "http://example.com/"
print "Status: 302 Moved"
print "Location: %s" % url
print

** Note that, as always when doing CGI with Python, we need to have an alone print statement after our header writes. Haven’t seen this before? Here is the same concept, but this time instead of doing a redirect we can see Python CGI in action simply printing out “Hello, world.” :

#!/usr/bin/env python
import cgi
print "Content-type: text/html"
print
print "Hello, world."

That’s it. It’s much more proper, and it’s noticeably faster. Try it both ways and you’ll see.

Don’t have your webserver setup for Python? What are you waiting for? Do yourself a favor and install Lighttpd, configure out fastcgi, and get cranking in Python.