How to keep a counter for use in rest api calls.

Hello, just started with Django and I am trying to keep a counter that increments by 1 every time a request comes in to the /create url route.

Basically, ‘’ calls my view which then calls another external rest end point that creates an item. The issue is I need to pass this external rest call a number to prepend to the created item identifier. So in this case I just figured to use the number of created items/calls to the create end point over time, even if the server is stopped.

I previously had just been running a script to do this and created a counter python object with a lock to handle async calls and race conditions. I though maybe I could use the same idea here, but dont know where I would instantiate and load the counter, so that it could be accessed by any url route I wanted to add. Is there a way to pass it around?

I thought possibly using the included db, but as i understand it there is no protection against async function calls race conditions?

1 Like

I’d do this in the database layer. I’d create a SEQUENCE for this purpose and use a raw SQL call to retrieve the next value of the sequence. That’s going to give you a unique value to all processes connecting to that instance of the database.

1 Like

Thank you for your time and solution :slight_smile: