1. Miki Tebeka
  2. appengine-py-demo

Commits

Miki Tebeka  committed 3cd4946

Check and fix url

  • Participants
  • Parent commits 7f1478b
  • Branches url-error

Comments (0)

Files changed (1)

File shortie.py

View file
 
 from os.path import dirname
 from urlparse import urlparse
+import re
 
 # Load templates from application directory
 get_template = jinja2.Environment(
     loader=jinja2.FileSystemLoader(dirname(__file__))).get_template
 
+# Check if URL has schema prefix
+has_schema = re.compile('^[a-z]+://.+').match
+
 class Counter(db.Model):
     '''Global counter.'''
     key_name = 'counter-key'
     created = db.DateTimeProperty(auto_now_add=True)
     hits = db.IntegerProperty(default=0)
 
+def fix_url(url):
+    '''Fix url by appending http:// if needed.
+
+    Will raise an ValueError on malformed url.
+    '''
+    url = url.strip()
+    if not url:
+        raise ValueError('empty url')
+    if '.' not in url:
+        raise ValueError('{0} - malformed url'.format(url))
+
+    if not has_schema(url):
+        url = 'http://{0}'.format(url)
+
+    return url
 
 class Home(webapp.RequestHandler):
     def get(self):
         self.reply()
 
     def post(self):
-        long_url = self.request.get('url') or ''
-        long_url = long_url.strip()
-        if not long_url:
-            self.reply(error='No URL')
+        url = self.request.get('url') or ''
+        try:
+            long_url = fix_url(url)
+        except ValueError as e:
+            self.reply(error=str(e))
             return
 
-        short_url = next_id()
-        url = Url(key_name=short_url)
-        url.long = long_url
-        url.user = users.get_current_user()
-        url.put()
+        try:
+            short_url = next_id()
+            url = Url(key_name=short_url)
+            url.long = long_url
+            url.user = users.get_current_user()
+            url.put()
+        except db.Error as e:
+            self.reply(error=str(e))
+            return
 
         self.reply(short_url=self.full_url(short_url))