I'm trying to create a numeric id for an entity without conflicts when multiple people could potentially be trying to create entities at once (the id will be seen and used by the apps users, so ideally it will be under 6 digits in length - auto assigned ID's probably aren't acceptable).
My current solution seems overly cumbersome and possibly doesn't even work to solve conflicts.
I have an ID counter that I'm storing within a different App entity:
class App(ndb.Model):
# counter to store number of projects
num_projects = ndb.IntegerProperty(default = 0)
And the actual projects:
class Project(ndb.Model):
date_created = ndb.DateTimeProperty(auto_now_add = True)
last_modified = ndb.DateTimeProperty(auto_now = True)
owner = ndb.KeyProperty(required = True)
owner_name = ndb.StringProperty(required = True)
name = ndb.StringProperty(required = True)
and a handler class for creating projects: (that could be called simultaneously)
def make_new_project(self):
pdt = App.by_id('pdt')
pdt.num_projects = pdt.num_projects + 1
if not Project.by_id(pdt.num_projects):
project = Project(id=pdt.num_projects)
project.put()
pdt.put()
return project
else:
return self.make_new_project()
The intention of the handler is to check if the project ID is already being used (someone literally put a new project after I retrieved the App counter) and if not, create the project with the new counter number, then store both to the DB.
I feel this is still kinda buggy and could lead to race conditions?? Is there a better way? Should I be pre-assigning keys and if so how do I do that? Do I store the assigned keys into my App model for later retrieval?
I get easily confused about the run-time of certain functions. If I add a function to assign keys to my main.py, does this run every time a new instance is started?
To clarify for some of the questions asked below, the projects should be findable by nuerics as the users of the existing system prefer to quote a project number when talking to other staff... ie: "I'm phoning regarding project 13670" and they can tell which project is older by sequential numbering, otherwise I would just generate a random 5 digit number and check it's not already in use before assigning.
Any help, clarification, etc... would be greatly appreciated.