|
|
|
|
|
by sheng
4535 days ago
|
|
I'm not familiar with SQLAlchemy but my overall SQL sense is tingling here: purchase.downloads_left -= 1
Is this the preferred method to update a field? I'm asking because i'm wondering if sqlalchemy will translate this to an sql query similar to: UPDATE purchase SET downloads_left = downloads_left - 1;
Because otherwise this might be dangerous. |
|
however, this is only one way to do it, which is the so-called pessimistic approach. An optimistic approach would just ensure that the transaction isolation is in repeatable read, so that the flush (occurs within the commit() here) would just fail in the very unlikely case a single user is submitting twice. SQLAlchemy also offers a "version counter" feature that can accomplish the same task if RR isn't an option. Both of these are configuration-level features that would allow the code to remain unchanged.
The "session.add(purchase)" is also unnecessary in that code sample, and the code also has a bug in that it does not commit the transaction when downloads_left reaches zero, so the number can never actually reach zero in the database.