美文网首页测试员的那点事
django-登陆功能实现

django-登陆功能实现

作者: 望月成三人 | 来源:发表于2020-11-28 18:16 被阅读0次

    django安装

    • pip install Django
    • 创建项目及应用
    # 创建应用
    D:\project>django-admin startproject mysite
    D:\project>cd mysite
    # 创建应用下的一个项目
    D:\project\mysite> python manage.py startapp myapi
    

    django 配置

    • setting.py
    import pymysql
    pymysql.version_info = (1, 4, 13, "final", 0) #指定版本
    pymysql.install_as_MySQLdb()
    
    
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'myapi' # 注册应用
    ]
    
    
    // 设置默认数据库为mysql
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'mydb',  # 数据库名字
            'USER': 'root',  # 帐号
            'PASSWORD': '123456',  # 密码
            'HOST': '127.0.0.1',  # IP
            'PORT': '3306',  # 端口
        }
    }
    
    • 执行下面的数据库迁移指令
    python manage.py makemigrations
    python manage.py migrate
    

    admin后台

    • 在admin中注册模型
    # myapi/admin.py
    
    from django.contrib import admin
    from . import models
    
    admin.site.register(models.User)
    
    • 建立超级管理员
    python manage.py createsuperuser
    
    • 运行服务器,进入到http://127.0.0.1:8100/admin
    python manage.py runserver 8100
    
    • 新增账号


      image.png
    • 新增账号好,在mysql中可以查到数据


      image.png

    URL路由和视图设置

    • mysite/myapi/urls.py设置路由
    from django.conf.urls import url
    from django.contrib import admin
    from myapi import views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^index/', views.index),
        url(r'^login/', views.login),
        url(r'^logout/', views.logout),
    ]
    
    • mysite/urls.py引用myapi的url
    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('myapi/', include('myapi.urls')),
    
    ]
    
    • mysite/myapi/views.py的视图代码
    from django.http import JsonResponse
    from django.shortcuts import render, redirect
    from django.views.decorators.csrf import csrf_exempt
    
    from myapi import models
    
    
    def check_login(func):  # 自定义登录验证装饰器
        def warpper(request, *args, **kwargs):
            is_login = request.session.get('is_login', False)
            if is_login:
                return func(request, *args, **kwargs)
            else:
                # return redirect("/login")
                return JsonResponse({'code': -1, 'msg': 'not login'})
    
        return warpper
    
    
    @check_login
    def index(request):
        # return render(request, 'login/index.html')
        return JsonResponse({'code': 2, 'msg': 'this is index message'})
    
    
    @csrf_exempt
    def login(request):
        if request.session.get('is_login', None):
            return {'code': 1, 'msg': 'already success'}
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        user = models.User.objects.get(name=user_name)
        if user and user.password == pwd:
            result = {'code': 1, 'msg': 'login is success'}
            request.session['is_login'] = True
            request.session['user_id'] = user.id
            request.session['user_name'] = user.name
        else:
            result = {'code': -1, 'msg': 'check user and pwd'}
    
        return JsonResponse(result)
    
    
    def loginout(request):
        if not request.session.get('is_login', None):
            # 若是原本就未登陆,也就没有登出一说
            # return redirect("/index/")
            return JsonResponse({"code": -1, "msg": "you are not login"})
    
        request.session.flush()
        # 或者使用下面的方法
        # del request.session['is_login']
        # del request.session['user_id']
        # del request.session['user_name']
        # return redirect("/index/")
        return JsonResponse({"code": 1, "msg": "login out is success"})
    

    代码测试

    import requests
    
    s = requests.Session()
    resp = s.post("http://127.0.0.1:8100/myapi/login/", data={"user_name": "test1", "pwd": "12345678"})
    print(resp.text)
    # resp2 = s.get("http://127.0.0.1:8100/myapi/loginout/")
    resp3 = s.get("http://127.0.0.1:8100/myapi/index/")
    
    
    # print(resp2.text)
    print(resp3.text)
    

    其他

    更新

    在vue发送请求后,出现跨域问题,在settings.py中设置

    INSTALLED_APPS = [
      ....
      'myapi',
        'corsheaders' # 新增
    
    ]
    
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'corsheaders.middleware.CorsMiddleware',  # 按顺序新增1
        'django.middleware.common.CommonMiddleware',  # 按顺序新增2
        'django.middleware.csrf.CsrfViewMiddleware',  # 按顺序新增3
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    
    # 跨域增加忽略
    CORS_ALLOW_CREDENTIALS = True
    CORS_ORIGIN_ALLOW_ALL = True
    CORS_ORIGIN_WHITELIST = ()
    CORS_ALLOW_METHODS = (
        'DELETE',
        'GET',
        'OPTIONS',
        'PATCH',
        'POST',
        'PUT',
        'VIEW',
    )
    CORS_ALLOW_HEADERS = (
        'XMLHttpRequest',
        'X_FILENAME',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'origin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with',
    )
    

    vue发送post请求,后台获取不到

    • 需要在vue这改造,用JSON.stringify传参
    axios.post("login/",JSON.stringify(this.loginForm))
    
    • 后台修改接受方式为
    @csrf_exempt
    def login(request):
        if request.session.get('is_login', None):
            return {'code': 1, 'msg': 'already success'}
        data = json.loads(request.body)
        user_name = data.get('username')
        pwd = data.get("pwd")
    

    当接受到的用户名不在user表中,出现DoesNotExist异常

    • 需要捕获异常
    @csrf_exempt
    def login(request):
        if request.session.get('is_login', None):
            return {'code': 1, 'msg': 'already success'}
        data = json.loads(request.body)
        user_name = data.get('username')
        pwd = data.get("pwd")
        if not user_name or not pwd:
            return JsonResponse({"code": -1, "msg":"username and pwd must fill in"})
        try:
            user = models.User.objects.get(name=user_name)
            if user and user.password == pwd:
                result = {'code': 1, 'msg': 'login is success'}
                request.session['is_login'] = True
                request.session['user_id'] = user.id
                request.session['user_name'] = user.name
            else:
                result = {'code': -1, 'msg': 'check user and pwd'}
        except models.User.DoesNotExist:
            result = {'code': -2, 'msg': 'check user'}
        return JsonResponse(result)
    
    

    相关文章

      网友评论

        本文标题:django-登陆功能实现

        本文链接:https://www.haomeiwen.com/subject/tpmqwktx.html