bgk / code.py

import web
import shelve
from random import choice

# Settings
SERVICE_URL = 'http://bgk.me/'
SHELVE_FILENAME = "bgkurls.db"
ADMIN = "/admin" # obfuscate it!
POST_REDIRECT_URL = 'http://www.biologeek.com/journal/%s/'
THOUGHT_REDIRECT_URL = 'http://www.biologeek.com/bistrot/%s/'

# Messages
INDEX_MESSAGE = """<h1>My own URL shortener that doesn't suck.</h1>

Get your own at <a href="http://code.welldev.org/bgk/" 
title="Access mercurial repository">http://code.welldev.org/bgk/</a>.
"""
FAIL_MESSAGE = 'Redirection failed, verify your link...'

# URLs
urls = (
    "/",                "Index",
    ADMIN,              "Admin",
    ADMIN+"/done/(.*)", "AdminDone",
    "/p/(\d+)",         "RedirectToPost",
    "/t/(\d+)",         "RedirectToThought",
    "/(.*)",            "RedirectToOthers",
)
app = web.application(urls, globals())

# Stolen from django.contrib.auth.models
def random_shortcut(self, length=10, 
    allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
    return ''.join([choice(allowed_chars) for i in range(length)])

class Index:
    def GET(self):
        return INDEX_MESSAGE

class Admin:
    def GET(self):
        admin_form = web.form.Form(
            web.form.Textbox("url",     description="Long URL"),
            web.form.Textbox("shortcut",description="Shortcut"),
        )
        admin_template = web.template.Template("""$def with(form)
        <!DOCTYPE HTML>
        <html>
          <head>
            <meta http-equiv="Content-Type" content="text/html; UTF-8" />
            <title>URL shortener administration</title>
          </head>
          <body onload="document.getElementById('url').focus()">
            <header><h1>Admin</h1></header>
            <form method="POST" action="/admin">
              $:form.render()
              <input type="submit" value="Shorten this long URL" />
            </form>
          </body>
        </html>
        """)
        return admin_template(admin_form())
        
    def POST(self):
        data = web.input()
        shortcut = str(data.shortcut) or random_shortcut()
        storage = shelve.open(SHELVE_FILENAME)
        if storage.has_key(shortcut) or not data.url:
            response = web.badrequest()
        else:
            storage[shortcut] = data.url
            response = web.seeother(ADMIN+'/done/'+shortcut)
        storage.close()
        return response

class AdminDone:
    def GET(self, short_name):
        admin_done_template = web.template.Template("""$def with(new_url)
        <!DOCTYPE HTML>
        <html>
          <head>
            <meta http-equiv="Content-Type" content="text/html; UTF-8" />
            <title>URL shortener administration</title>
          </head>
          <body>
            <header><h1>Done!</h1></header>
            <p>You created: $new_url</p>
            <p><a href="http://twitter.com/home?status=$new_url" 
              title="Tweet it!">Tweet it?</a></p>
          </body>
        </html>
        """)
        return admin_done_template(SERVICE_URL+short_name)

class RedirectToPost:
    def GET(self, post_id):
        return web.redirect(POST_REDIRECT_URL % post_id)

class RedirectToThought:
    def GET(self, thought_id):
        return web.redirect(THOUGHT_REDIRECT_URL % thought_id)

class RedirectToOthers:
    def GET(self, short_name):
        storage = shelve.open(SHELVE_FILENAME)
        short_name = str(short_name) # shelve does not allow unicode keys
        if storage.has_key(short_name):
            response = web.redirect(storage[short_name])
        else:
            response = FAIL_MESSAGE
        storage.close()
        return response

if __name__ == "__main__":
    app.run()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.