Commits

Miki Tebeka committed 7f1478b

Url and full_url

Comments (0)

Files changed (1)

 import jinja2
 
 from os.path import dirname
+from urlparse import urlparse
 
 # Load templates from application directory
 get_template = jinja2.Environment(
 
     return base62.encode(id[0])
 
+class Url(db.Model):
+    '''Url object in database.
+
+    Key name will be the short id.
+    '''
+    long = db.LinkProperty()
+    user = db.UserProperty()
+    created = db.DateTimeProperty(auto_now_add=True)
+    hits = db.IntegerProperty(default=0)
+
 
 class Home(webapp.RequestHandler):
     def get(self):
         self.reply()
 
     def post(self):
-        url = self.request.get('url') or ''
-        url = url.strip()
-        if not url:
+        long_url = self.request.get('url') or ''
+        long_url = long_url.strip()
+        if not long_url:
             self.reply(error='No URL')
             return
-        self.reply(short_url=url)
+
+        short_url = next_id()
+        url = Url(key_name=short_url)
+        url.long = long_url
+        url.user = users.get_current_user()
+        url.put()
+
+        self.reply(short_url=self.full_url(short_url))
 
     def reply(self, **kw):
         '''Fills index template with kw and other variables, send to client.'''
 
         return '<a href="{0}">{1}</a>'.format(fn(self.request.uri), txt)
 
+    def full_url(self, short):
+        '''Adds <schema>:://netloc before short url to get full url.
+
+        This works both locally and on AppEngine.'''
+        url = urlparse(self.request.uri)
+        return '{0.scheme}://{0.netloc}/{1}'.format(url, short)
+
 app = webapp.WSGIApplication([
     ('/', Home),
 ], debug=True)