Login

Random object IDs using an abstract base model

Author:
elver
Posted:
July 15, 2011
Language:
Python
Version:
1.3
Score:
-1 (after 1 ratings)

To put obfuscated primary keys in any class, simply inherit from this one. For example:

class Offer(ObfuscatedPKModel)

You can match for these bigint primary keys in your urls.py like this:

'^offer/(?P<offer_pk>[0-9-]+)$'

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class ObfuscatedPKModel(models.Model):
    class Meta:
        abstract = True
        
    id = models.BigIntegerField(primary_key = True, db_index = True)
    
    def save(self, *args, **kwargs):
        if not self.pk:
            kwargs["force_insert"] = True
            while True:
                # Avoid generating 0
                self.pk = random.randint(-models.BigIntegerField.MAX_BIGINT - 1, models.BigIntegerField.MAX_BIGINT) or models.BigIntegerField.MAX_BIGINT
                try:
                    super(ObfuscatedPKModel, self).save(*args, **kwargs)
                    break
                except IntegrityError:
                    logger.info("Duplicate PK situation averted.")
                    continue
        else:
            super(ObfuscatedPKModel, self).save(*args, **kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

willhardy (on July 15, 2011):

Here are a few things I noticed:

  1. (Obscure bug) You leave open the possibility of pk = 0, which some parts of Django and third party code might not expect. It also means the next time you save the object, it will be assigned a new random primary key (and be duplicated in the database).
  2. (Not too important) The hardcoded limits for bigintegerfield can be better accessed at -.models.BigIntegerField.MAX_BIGINT-1 and models.BigIntegerField.MAX_BIGINT
  3. (not important) the first two pk assignments are unnecessary (but change if statement to use self.pk).
  4. (completely optional) You might like to encode the gigantic integer as a base36 string when including it in the URL.

#

elver (on July 15, 2011):

Thanks for the comments! I rewrote it, taking your comments into account, and also removing the highly remote possibility of two threads happening upon the same PK by chance and overwriting one another's data.

#

Please login first before commenting.