1

We are using the Flask development server which I know we need to change. It seems that when two requests come in very close to each other bad things happen. On one of those occasions we got this sqlalchemy.exc.InvalidRequestError upon commit.

The response object had already been created and assigned a UUID:

class ServiceResponse(db.Model):                                                                                    
    service_response_id = db.Column(
        db.String(32),
        unique=True,
        nullable=False,
        primary_key=True,
        default=lambda: uuid.uuid4().hex
    )                                                                 
    status_code = db.Column(db.SmallInteger, nullable=False)

The problem is that all subsequent requests kept assigning the same UUID to the corresponding response object. This caused integrity errors because a response object with the same UUID already existed in the DB. After I deleted the offending row from the DB the same value was generated one more time, didn't cause an integrity error anymore, and since then different values have been generated as expected.

I'm aware that the type could be changed to UUID but my question is why is uuid.uuid4() generating the same value over and over again for different requests?

  • Does this answer your question? [How can I use UUIDs in SQLAlchemy?](https://stackoverflow.com/questions/183042/how-can-i-use-uuids-in-sqlalchemy) – pjcunningham May 15 '20 at 10:21
  • Not directly. I can certainly try migrating the field to type UUID but that would also use uuid.uuid4 as the default. And my question is really why the same default value keeps being generated over and over again. After i deleted the row from the database, the same value was generated one more time but didn't cause the integrity error. After that, different values have been generated as expected. – Julio Carrera May 16 '20 at 13:03
  • Did you read the part "Be careful not to miss passing the callable uuid.uuid4 into the column definition, rather than calling the function itself with uuid.uuid4(). Otherwise, you will have the same scalar value for all instances of this class." – pjcunningham May 16 '20 at 15:00
  • I did. The default is set to a lambda function which is executed every time and results in a different value being generated. You can verify it in the Python interpreter. – Julio Carrera May 17 '20 at 16:27

0 Answers0