简体   繁体   中英

Django, how to make a view atomic?

I have a simple django app to simulate a stock market, users come in and buy/sell. When they choose to trade,

  1. the market price is read, and
  2. based on the buy/sell order the market price is increased/decreased.

I'm not sure how this works in django, but is there a way to make the view atomic? ie I'm concerned that user A's actions may read the price but before it's updated because of his order, user B's action reads the price.

Couldn't find a simple, clean solution for this online. Thanks.

This is database transactions, with some notes. All notes for Postgresql; all databases have locking mechanisms but the details are different.

Many databases don't do this level of locking by default, even if you're in a transaction. You need to get an explicit lock on the data.

In Postgresql, you probably want SELECT ... FOR UPDATE, which will lock the returned rows. You need to use FOR UPDATE on every SELECT that wants to block if another user is about to update them.

Unfortunately, there's no way to do a FOR UPDATE in Django's ORM. You'd eitiher need to hack the ORM a bit or use raw SQL, as far as I know. If this is low-performance code and you can afford to serialize all access to the table, you can use a table-level LOCK IN EXCLUSIVE MODE, which will serialize the whole table.

http://www.postgresql.org/docs/current/static/explicit-locking.html

http://www.postgresql.org/docs/current/static/sql-lock.html

http://www.postgresql.org/docs/current/static/sql-select.html

Pretty old question, but since 1.6 you can use transaction.atomic() as decorator.

views.py

@transaction.atomic()
def stock_action(request):
  #trade here

Wrap the DB queries that read and the ones that update in a transaction. The syntax depends on what ORM you are using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM