Permalink
Browse files

Trap illegal characters

  • Loading branch information...
1 parent 3528d6b commit c103cae517284d2ae6ebf8b1c276dc1dbfcdc53d @lsemel lsemel committed May 20, 2011
Showing with 22 additions and 3 deletions.
  1. +22 −3 tiny.py
  2. BIN tiny.pyc
View
25 tiny.py
@@ -19,7 +19,7 @@
"""
import random
-SET = 'qpiDX1TuSEOzf3to0NP8BaWwIHchMmle75AQGjZRLJ2Vr9Y4vdnbKsUxFkCg6y'
+SET = 'poygezRY9L1x8CTl6rUBKQHwVuIkh4fZ7cv3sdJaAjO2iqWbFt0nM5EPGSmDXN'
def to_tiny(id):
"""Converts from an integer to a tinified string."""
@@ -35,13 +35,32 @@ def to_tiny(id):
return hexn
def from_tiny(s):
- """Converts from a tinified string to an integer."""
+ """Converts from a tinified string to an integer.
+
+ If any illegal characters are used in the string, return a -1.
+ These tiny urls are almost always used to look up a database item by
+ primary key, so this ensures that the database item is not found,
+ and a normal 404 page is thrown. If we instead threw an exception
+ we'd have a different exception to handle and the normal 404 page would
+ not be shown.
+
+ >>> from_tiny('abc_')
+ -1
+ >>> from_tiny('!!#$#$')
+ -1
+ >>> from_tiny('')
+ 0
+
+ """
radix = len(SET)
strlen = len(s)
n = 0
i = 0
while (i < strlen):
- c = SET.find(s[i]) * pow(radix, strlen - i - 1)
+ p = SET.find(s[i])
+ if (p < 0):
+ return -1
+ c = p * pow(radix, strlen - i - 1)
n += c
i += 1
return n
View
BIN tiny.pyc
Binary file not shown.

0 comments on commit c103cae

Please sign in to comment.