Skip to content

Instantly share code, notes, and snippets.

@anemitz
Created August 24, 2012 08:09
Show Gist options
  • Save anemitz/3447356 to your computer and use it in GitHub Desktop.
Save anemitz/3447356 to your computer and use it in GitHub Desktop.
MongoEngine RandomPKDocument
import os
from zbase62 import zbase62
from mongoengine import *
from mongoengine.queryset import OperationError
class RandomPKDocument(Document):
id = StringField(unique=True, primary_key=True)
def get_pk_prefix(self):
return self._get_collection_name()[:4]
def save(self, *args, **kwargs):
old_id = self.id
# Don't cascade saves by default.
kwargs['cascade'] = kwargs.get('cascade', False)
try:
if not self.id:
self.id = u'%s_%s' % (self.get_pk_prefix(), zbase62.b2a(os.urandom(32)))
# Throw an exception if another object with this id already exists.
kwargs['force_insert'] = True
# But don't do that when cascading.
kwargs['cascade_kwargs'] = { 'force_insert': False }
return super(RandomPKDocument, self).save(*args, **kwargs)
except OperationError, err:
self.id = old_id
# Use "startswith" instead of "in". Otherwise, if a free form
# StringField had a unique constraint someone could inject that
# string into the error message.
if unicode(err).startswith(u'Tried to save duplicate unique keys (E11000 duplicate key error index: %s.%s.$_id_ ' % (self._get_db().name, self._get_collection_name())):
self.save(*args, **kwargs)
else:
raise
meta = {
'allow_inheritance': True,
'abstract': True,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment