Services like bit.ly are great for shortening URL’s that you want to include in tweets and other conversations. What is the simplest URL shortener application one could write in python for the Google App Engine?
views:
712answers:
3
+3
Q:
What is the simplest URL shortener application one could write in python for the Google App Engine?
+15
A:
That sounds like a challenge!
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import run_wsgi_app
class ShortLink(db.Model):
url = db.TextProperty(required=True)
class CreateLinkHandler(webapp.RequestHandler):
def post(self):
link = ShortLink(url=self.request.POST['url'])
link.put()
self.response.out.write("%s/%d" % (self.request.host_url, link.key().id())
def get(self):
self.response.out.write('<form method="post" action="/create"><input type="text" name="url"><input type="submit"></form>')
class VisitLinkHandler(webapp.RequestHandler):
def get(self, id):
link = ShortLink.get_by_id(int(id))
if not link:
self.error(404)
else:
self.redirect(link.url)
application = webapp.WSGIApplication([
('/create', CreateLinkHandler),
('/(\d+)', VisitLinkHandler),
])
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Nick Johnson
2009-09-10 15:21:01
Nice indeed -- simple, clear, effective!
Alex Martelli
2009-09-10 15:29:38
A:
@Nick Looks good! I would suggest encoding/hashing the ID to create the shortest possible URL. Feel free to use the encoding library I wrote for my App Engine URL Shortener here - http://i.loo.lu/W
designcurve
2009-12-03 05:44:21
+1
A:
There is a django app on github, github.com/nileshk/url-shortener. I forked it to make it more of an all encompassing site,http://github.com/voidfiles/url-shortener.
Alex Kessinger
2009-12-04 08:01:13