Commits

Miki Tebeka  committed 269c3dc

redirect and log error

  • Participants
  • Parent commits 3cd4946
  • Branches redirect

Comments (0)

Files changed (1)

 from os.path import dirname
 from urlparse import urlparse
 import re
+from httplib import NOT_FOUND
+import logging as log
 
 # Load templates from application directory
 get_template = jinja2.Environment(
     created = db.DateTimeProperty(auto_now_add=True)
     hits = db.IntegerProperty(default=0)
 
+def get_url(short_url):
+    '''Get a Url from datastore by short url.'''
+    return Url.get_by_key_name(short_url)
+
 def fix_url(url):
     '''Fix url by appending http:// if needed.
 
         url = urlparse(self.request.uri)
         return '{0.scheme}://{0.netloc}/{1}'.format(url, short)
 
+class Redirect(webapp.RequestHandler):
+    '''Redirect handler, gets short URL and issue an HTTP redirect to the long
+    one.'''
+    def get(self, short_url):
+        url = get_url(short_url)
+        if not url:
+            log.error('redirect for {0} not found'.format(short_url))
+            self.abort(NOT_FOUND)
+
+        long_url = str(url.long)
+        self.redirect(long_url)
+
 app = webapp.WSGIApplication([
     ('/', Home),
+    ('/([a-zA-Z0-9]+)', Redirect),
 ], debug=True)