Created
June 7, 2016 21:06
-
-
Save mordaha/f9aea81904ee41d0b8b852e54ca67c0d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ShortUrlModelMixin(models.Model): | |
TOKEN_LEN = 5 | |
short_url = models.CharField(max_length=TOKEN_LEN, db_index=True, unique=True, editable=False) | |
class Meta: | |
abstract = True | |
def save(self, *args, **kwargs): | |
if not self.pk: | |
while 1: | |
self.short_url = self.gen_token() | |
try: | |
self._meta.model.objects.get(short_url=self.short_url) | |
except self._meta.model.DoesNotExist: | |
break | |
super(ShortUrlModelMixin, self).save(*args, **kwargs) | |
def gen_token(self): | |
token_src = binascii.b2a_base64(str(random.randrange(0, 1000000)).encode('utf-8'))[:-3] | |
return ''.join(random.sample(str(token_src).replace("'", ""), self.TOKEN_LEN)).lower() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment