Skip to content

Instantly share code, notes, and snippets.

@zhuowei
Created July 4, 2011 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zhuowei/1062835 to your computer and use it in GitHub Desktop.
Save zhuowei/1062835 to your computer and use it in GitHub Desktop.
Demo: A Python CGI URL Shortener

A simple CGI-based web server. first, run createDatabase.py, then run run.py.

Then navigate to http://127.0.0.1:8080/ in a web browser.

#!/usr/bin/python
import cgi
import sqlite3
import urlparse
import os
#Change this
PATH_TO_INSTALL = "/home/zhuowei/Documents/repos/URLShortener"
form = cgi.FieldStorage()
urlToAdd = form.getfirst("url")
if urlToAdd == None:
print "Content-Type: text/plain"
print
print "Please enter a url."
exit()
parsed_url = urlparse.urlparse(urlToAdd)
if parsed_url.scheme == '' or parsed_url.netloc == '':
print "Content-Type: text/plain"
print
print "That wasn't a url, you silly goose!"
exit()
conn = sqlite3.connect(PATH_TO_INSTALL + "/c/data/urls.db")
c = conn.cursor();
c.execute("insert into urls (url) values (?)", (parsed_url.geturl(),))
c.execute("select last_insert_rowid()")
result = c.fetchone()
conn.commit()
conn.close()
print "Content-Type: text/plain"
print
print "Done. your url is at:"
print os.environ["SERVER_NAME"] + "/c/g?" + str(result[0])
<!DOCTYPE html>
<html>
<head>
<title>Create a Shortened URL</title>
</head>
<body>
<h1>Create a new shortened url</h1>
<form action="/c/addURL" method="POST">
URL: <input name="url" type="url">
<input type="submit" value="Submit">
</form>
</body>
</html>
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect("c/data/urls.db")
c = conn.cursor();
c.execute("CREATE TABLE urls(id INTEGER PRIMARY KEY AUTOINCREMENT, url VARCHAR(1000))");
conn.commit()
conn.close()
#!/usr/bin/python
import os
import sqlite3
#Change this
PATH_TO_INSTALL = "/home/zhuowei/Documents/repos/URLShortener"
def print_fail():
print "Status: 404 Not Found"
print "Content-Type: text/plain"
print
print "This short url does not exist. Please try again in a different universe,"
query_string = os.environ["QUERY_STRING"].strip()
if not query_string.isdigit():
print_fail()
exit()
urlid = int(query_string)
# pull the url out of the database
conn = sqlite3.connect(PATH_TO_INSTALL + "/c/data/urls.db")
c = conn.cursor();
c.execute("select url from urls where id = ?", (urlid, ));
urldata = c.fetchone();
if urldata == None:
print_fail()
exit()
print "Content-Type: text/html"
print
print "<!DOCTYPE html>\n<html><head><title>Redirecting</title>"
print "<script type=\"text/javascript\">"
print "window.location = '" + urldata[0] + "';"
print "</script>"
print "<body>Redirecting to " + urldata[0] + "</body></html>"
<!DOCTYPE html>
<html>
<head>
<title>URLShortener</title>
</head>
<body>
<h1>The simple urlshortener</h1>
<p><a href="addURLPage.htm">Create a short url</a></p>
</body>
</html>
import CGIHTTPServer
import SocketServer
PORT = 8080
Handler = CGIHTTPServer.CGIHTTPRequestHandler
Handler.cgi_directories = ["c", "/c", "c/", "/c/"]
print Handler.cgi_directories
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.server_name = "localhost"
httpd.server_port = PORT
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment