Commits

Miki Tebeka  committed 95f8cf6

next-id

  • Participants
  • Parent commits 8bf25a9
  • Branches next-id

Comments (0)

Files changed (3)

+'''Encode numbers to base62'''
+import string
+
+ALPHABET = string.digits + string.letters
+
+def encode(num):
+    '''Encode number in base62.'''
+    if num == 0:
+        return ALPHABET[0]
+
+    arr = []
+    base = len(ALPHABET)
+
+    while num:
+        rem = num % base
+        num = num // base
+        arr.append(ALPHABET[rem])
+
+    return ''.join(reversed(arr))
+
         </form>
 
         <div class="footer">
-            G'day {{ user }}, this page was viewed {{ count }} times.
+            G'day {{ user }}, we've shortened {{ count }} urls so far.
         </div>
     </body>
 </html>
 
 An AppEngine Demo.
 '''
+import base62
+
 from google.appengine.ext import webapp
 from google.appengine.api import users
 from google.appengine.ext import db
-
 import jinja2
 
 from os.path import dirname
         counter = Counter(key_name=Counter.key_name)
     return counter
 
-def record_hit():
-    '''Record a page hit, increment counter and return count.'''
+def next_id():
+    '''Get next short url id.
 
-    # Sadly, Python does not have proper lexical scoping. This is a hack round
-    # it.
-    count = [0]
+    We do that by incrementing the global counter and then base62 encoding the
+    current count.
+    '''
 
-    # Update count in transaction
+    id = [0]
+
+    # Update counter in transaction
     def txn():
         counter = get_counter()
         counter.count += 1
         counter.put()
-        count[0] = counter.count
+        id[0] = counter.count
 
     db.run_in_transaction(txn)
 
-    return count[0]
+    return base62.encode(id[0])
 
 
 class Home(webapp.RequestHandler):
         env.update({
             'login' : self.login_html(),
             'user' : users.get_current_user() or 'stranger',
-            'count' : record_hit(),
+            'count' : get_counter().count
         })
         self.response.out.write(template.render(**env))