Commits

Miki Tebeka committed 3cd4946

Check and fix url

Comments (0)

Files changed (1)

 
 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))
 
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.