Django transactions (reference documentation and blogs)

Source: Internet
Author: User
adding transactions on HTTP requests

For Web requests, Django officially recommends using the Transactionmiddleware to handle the transactions in the request and in response. It works like this: When a request arrives, Django starts a transaction, and if the response is not wrong, Django submits all the transactions for the period, and if the function in the view throws an exception, Django rolls back the transaction.

To implement this feature, you need to add transactionmiddleware to the Middleware_classes setting:

middleware_classes = (
    ' django.middleware.cache.UpdateCacheMiddleware ',
    ' Django.contrib.sessions.middleware.SessionMiddleware ',
    ' django.middleware.common.CommonMiddleware ',
    ' Django.middleware.transaction.TransactionMiddleware ',
    ' Django.middleware.cache.FetchFromCacheMiddleware ',
)

Order is important, Transactionmiddleware middleware will be included in the scope of the transaction after the middleware (except for the middleware used for caching, they will not be affected, such as Cachemiddleware, Updatecachemiddleware and Fetchfromcachemiddleware).

Also note that Transactionmiddleware only affects the default database in the databases setting, and for other databases, we can only use a different scenario if we implement transaction control.

Although the advantage of this transaction pattern is its simplicity, it can cause a lot of performance loss when the traffic grows to a certain extent. This is because opening one thing for each view has some extra overhead. In addition, this performance impact depends on the query pattern of your application and the efficiency of your database's handling of locks.

Note that it has a prerequisite: Your view code runs in a closed transaction. For example, the middleware can only run outside the transaction, so it is not difficult to understand why the rendering of the response template is not controlled by the transaction.

Even if the atomic_requests is turned on, you can still have a way to make the view method run outside of the transaction.

non_atomic_requests (Using=none) [Source]

For example, you can decorate the above to make the view method not controlled by the transaction.

From django.db Import Transaction

@transaction. Non_atomic_requests
def my_view (request):
    Do_stuff ()

@transaction. Non_atomic_requests (using= ' other ')
def my_other_view (request):
    Do_stuff_on_the_other_ Database ()
implementing transaction control in view

If you want to control transactions under finer-grained conditions, such as in a view function, we can use django.db.transaction. There are two uses: 1. Use of adorners

From django.db Import Transaction

@transaction. Commit_on_success
def viewfunc (Request):
    #
    ... # This code executes inside a transaction
# ...
2. Using the context Manager
From django.db Import Transaction
def viewfunc (Request):
    #
    ... # This code executes using default transaction management
    #
    ... With Transaction.commit_on_success ():
        #
        ... # This code executes inside a transaction
        # ...
autocommit ()

You can use the autocommit adorner to revert a transaction in the view function to the Django default autocommit mode, ignoring the global transaction setting.

Example:

From django.db Import Transaction
@transaction. Autocommit
def viewfunc (request):
    ....

@transaction. Autocommit (using= "My_other_database")
def VIEWFUNC2 (request): ...
    .
commit_on_success ()

As the name suggests, the view function succeeds in committing the transaction or rolling back. Usage ditto. commit_manually ()

Tell Django we'll control the transaction in the function. Also note that if you change the database's data in a view function and do not invoke commit () or rollback (), the Transactionmanagementerror exception is thrown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.