python(session cookie 请求)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="/login/" method="POST">
        {% csrf_token %}
        <input type="text" name="user" />
        <input type="text" name="pwd" />
        <input type="checkbox" name="rmb" value="1" /> 10秒免登录
        <input type="submit" value="提交" />
        <input id="btn1" type="button" value="按钮" />
        <input id="btn2" type="button" value="按钮" />
    </form>

    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    <script>
        $(function(){
            $.ajaxSetup({
                beforeSend: function(xhr,settings){
                    xhr.setRequestHeader('X-CSRFtoken', $.cookie('csrftoken'));
                    {#配置所有ajax请求头#}
                }
            });

            $('#btn1').click(function () {
                $.ajax({
                    url: '/login/',
                    type:"GET",
                    data: {'user': 'root', 'pwd': '123'},
                    // headers: {'X-CSRFtoken': $.cookie('csrftoken')},
                    {#顶部ajaxSetup已经配置请求头,不需要在配置#}
                    success:function(arg){

                    }
                })
            });
        })
    </script>
</body>
</html>

 

 

from django.shortcuts import render, redirect, HttpResponse


# Create your views here.


def login(request):
    # from django.conf import settings
    # print(settings.CSRF_HEADER_NAME)
    # HTTP_X_CSRFTOKEN
    # X-CSRFtoken

    if request.method == "GET":
        return render(request,'login.html')
    elif request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'root' and pwd == "123":
            # session中设置值
            request.session['username'] = user
            request.session['is_login'] = True
            #设置session超时时间
            if request.POST.get('rmb',None) == '1':
                request.session.set_expiry(10)
            if request.POST.get('rmb',None) == '1':
                # 超时时间
                request.session.set_expiry(10)
            return redirect('/index/')
        else:
            return render(request,'login.html')


def index(request):

    if request.session.get['is_login',note]:
        return render(request, 'index.html', {'username': request.session['username']})
    else:
         return HttpResponse('gun')


def logout(request):
    request.session.clear()
    return redirect('/login/')

发表评论