Skip to content

Instantly share code, notes, and snippets.

@Roasbeef
Created July 10, 2012 17:40
Show Gist options
  • Save Roasbeef/3084985 to your computer and use it in GitHub Desktop.
Save Roasbeef/3084985 to your computer and use it in GitHub Desktop.
Start of URL Shortener
import os
import requests
'''
url = self.request.get('url')
try:
l = Link()
l.seed(url)
except ValueError:
self.render('index.html', error='Invalid Url')
'''
class Link(db.Model):
url = db.LinkProperty(required=True)
hash = db.StringProperty()
created = db.DateTimeProperty(auto_now=False, auto_now_add=True)
hits = db.IntegerProperty()
def seed(self, url):
if is_valid_url(url):
self.url = url
self.hash = generate_unique_hash()
self.hits = 0
self.put()
return self
else:
raise ValueError('Invalid URL')
def is_valid_url(url):
r = requests.get(url)
if r.status_code != 200:
return False
else:
return True
def generate_unique_hash(self):
h = self.generate_hash()
l = Link.all().filter("hash =", h)
if h:
return self.generate_unique_hash()
else:
return h
def generate_hash(self):
#returns random 16-bit string
return os.urandom(2).encode('hex')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment