Nine, Django locks, transaction, ajax

First, transactions and locks

  1. Row-level locking

select_for_update attention must be used inside a transaction

select_for_update(nowait=False, skip_locked=False)

entries = Entry.objects.select_for_update().filter(author=request.user)  #加互斥锁,由于mysql在查询时自动加的是共享锁,所以我们可以手动加上互斥锁。create、update、delete操作时,mysql自动加行级互斥锁

select * from t1 where id=1 for update;
models.T1.objects.select_for_update().fitler(id=1)

All matching rows are locked until the end of the transaction. This means that data can be locked to prevent other transactions from modifying.

  1. Affairs

The first way: global

This approach is all the more unified sql http requests are placed in a corresponding transaction execution (either all succeed, or all else fails), is a global configuration

在settings文件中:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mxshop',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123',
        'OPTIONS': {
            "init_command": "SET default_storage_engine='INNODB'",
       #'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", #配置开启严格sql模式


        }
        "ATOMIC_REQUESTS": True, #全局开启事务,绑定的是http请求响应整个过程
        "AUTOCOMMIT":False, #全局取消自动提交,慎用
    },
  'other':{
    'ENGINE': 'django.db.backends.mysql', 
            ......
  } #还可以配置其他数据库
}

The second way: local

Achieved by the atomic transaction code block

from django.db import transaction  # 导入transaction

在视图函数中加:
@transaction.non_atomic_requests
def index(request):
    pass (orm...sql..语句)
    return xxx

上下文逻辑里面加:
def index(request):
    ..
    with transaction.atomic():  # 设置事务的保存点
        pass orm...sql..
    ...
    return xxx

Two, Ajax

  1. Brief introduction

    AJAX (Asynchronous Javascript And XML), translated into Chinese is "asynchronous Javascript and XML", that the use of Javascript language to interact with the server asynchronous data transfer as XML.

    The biggest advantage is AJAX without reloading the entire page, you can exchange data with the server and update parts of the page content. (This feature is the feeling to the user request and response process is completed unknowingly)

    AJAX does not require any browser plug-ins, but requires the user to allow the execution of JavaScript in the browser

In addition to asynchronous AJAX features, and the other is: partial refresh browser page;

  • Asynchronous Interaction: the client sends a request to the server without waiting for the end of the response, it can issue a second request
  • The partial refresh: this characteristic feeling to the user request and response process is completed unknowingly
  1. Normal login authentication example

First of all do not ajax, complete a login authentication interface

  1. Configuring routing URLs
    from app01 Import views
    the urlpatterns = [
    URL (R & lt 'Login ^ /', views.LoginView.as_view (), name = 'Login'),
    # which is configured path begins when CBV
    ]

  2. The view function is accomplished CBV
    from the render django.shortcuts Import, the HttpResponse, the redirect
    from django.views Import View

    class LoginView(View):
        def get(self,request):
            return render(request,'login.html')
    
        def post(self,request):
            name = request.POST.get('username')
            pwd = request.POST.get('password')
            if name=='yangzm' and pwd=='123':
                return render(request,'index.html')
            else:
                return redirect('login')
  3. Complete two html files, login.html used to complete the sign-on capabilities; index.html file to complete the page display after a successful login, the user name if the wrong password, the redirection will login.html page
    # login.html

    Welcome to the login page



    {% Csrf_token%}
    Username:
    password:

    # index.html
    <p>登录成功</p>
    <p>欢迎大佬到来</p>
  4. Results and analysis of shortcomings
    when user input 127.0.0.1:8000/login/, displays the login page
    to log successful jump index page, the login fails again return to this page

    Analysis Cons: When the user enters information is not the right time, as do a redirect, click submit, refresh the page, jump back to the login page, then the page is requested again, the previously entered data will be cleared , so that the user experience is very poor
    goals to improve: the user enters the wrong, you want to keep the previous information, and prompts the user to enter the wrong, then let the user input on the content of reform, improve the user experience, this when you need to use ajax to complete this function

  5. Examples ajax login authentication based on complete

  6. jquery ajax need to use the file, the file is introduced to a static configuration
    # Configure Settings:
    STATICFILES_DIRS = [
    the os.path.join (base_dir, 'statics to')
    ]

    # 新建文件夹statics,放静态文件 jquery.js
  7. At this time, the file need to introduce login.html jquery file, and then write js code that implements Ajax
    {%} static Load%

    <body>
    <h1>欢迎来到登录页面</h1>
    
    <form action="/login/" method="post">
        {% csrf_token %}
        用户名:<input type="text" id="username" name="username">
        密  码:<input type="password" id="password" name="password">
        <input type="button" id="btn" value="提交">
        <span style="color: red;font-size: 12px" id="error"></span>
    </form>
    
    
    <script src="{% static 'jquery.js' %}"></script>
    <script>
        $('#btn').click(function () {
            $.ajax({
                url:'/login/',
                type:'post',
                data:{
                    uname:$('#username').val(),
                    pwd:$('#password').val(),
                    csrfmiddlewaretoken:$('[name=csrfmiddlewaretoken]').val()
                    # 这是为了通过post提交的认证机制
    
                },
                success:function (res) {
                    var resStr = JSON.parse(res);
                    if(resStr['code'] === 3){
                        $('#error').text(resStr['redirect_url'])
                    }
                    else if(resStr['code'] === 0){
                        location.href=resStr['redirect_url'];
                    }
                }
            })
        })
    </script>
    
    </body>
  8. url need to reconfigure the path index of a successful login
    the urlpatterns = [
    url (R & lt 'ADMIN ^ /', admin.site.urls),
    url (R & lt 'Login ^ /', views.LoginView.as_view (), name = 'Login '),
    URL (R & lt' index ^ / ', views.index),
    ]

  9. 视图函数views
    from django.shortcuts import render,HttpResponse,redirect

    # Create your views here.
    
    from django.views import View
    
    class LoginView(View):
        def get(self,request):
            return render(request,'login.html')
    
        def post(self,request):
            name = request.POST.get('uname')
            pwd = request.POST.get('pwd')
            if name=='yangzm' and pwd=='123':
                ret = '{"code":0,"redirect_url":"/index/"}'
                return HttpResponse(ret)
            else:
                ret = '{"code":3,"redirect_url":"用户名密码错误!!!"}'
                return HttpResponse(ret)
    
    def index(request):
    
        return render(request,'index.html')
  10. result

    In this case entered an incorrect user name and password, do not refresh the page to display the prompt information, retain the original data, until the input of the successful jump to the login page
  11. Way external js file import to write code, then write js code can not be django template syntax, because the load order html file: url-- view --html template rendering --- return to the browser - browser rendering - - srcipt of src - before going to request js file - then the js file code will now only be loaded into your html document - there is no template rendering steps - and there is no way to replace the corresponding template syntax.

Guess you like

Origin www.cnblogs.com/yangzm/p/11272687.html