Django_Vue3_ElementUI_Release_002_后台API_注册登陆和注销

1. 准备工作

1.1 解决跨域问题

bash 复制代码
[pip.exe path] install django-cors-headers



python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'index',
    'item',
    'cart',
    'corsheaders'
]



MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
...
]


# 设置跨域访问
# 指定所有域名(IP)都可以访问,默认为False
CORS_ORIGIN_ALLOW_ALL = True
# 设置允许携带Cookie
CORS_ALLOW_CREDENTIALS = True
# 设置允许访问的域名(IP)
# 如果CORS_ORIGIN_ALLOW_ALL=True则无需设置
CORS_ORIGIN_WHITELIST = []
# 允许执行的请求方式
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)
# 允许执行的请求头
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

1.2 安装djangorestframework

bash 复制代码
pip.exe install djangorestframework
python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'index',
    'item',
    'cart',
    'corsheaders',
    'rest_framework'
]

REST_FRAMEWORK = {
    # 配置分页器
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    # 每页的数据量
    'PAGE_SIZE': 6,
    # 用户认证方式
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

2. 注册和登陆接口

2.1 序列化类Serializer

python 复制代码
from rest_framework import serializers
from .models import *
# 定义ModelSerializer类
class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = '__all__'

2.2 创建form验证

python 复制代码
from django import forms
# from django.contrib.auth.models import User
from .models import *
from django.core.exceptions import ValidationError


class LoginModelForm(forms.ModelForm):
    class Meta:
        # 和模型进行绑定
        model = UserInfo
        # 选取模型中的某些字段
        fields = ('username', 'password')
        # 设置html的标签
        labels = {
            'username': '请您输入手机号',
            'password': '请您输入密码',
        }
        error_messages = {
            '__all__': {'required': '请输入内容',
                        'invalid': '请检查输入内容'},
        }
        # 定义widgets,设置表单字段对应HTML元素控件的属性
        widgets = {
            'username': forms.widgets.TextInput(
                                   attrs={'class': 'layui-input', 'placeholder': '请您输入手机号',
                                          'lay-verify': 'required|phone', 'id': 'username'}),
            'password': forms.widgets.PasswordInput(
                                   attrs={'class': 'layui-input', 'placeholder': '请您输入密码',
                                          'lay-verify': 'required|password', 'id': 'password'})
        }

    # 自定义表单字段username的数据清洗
    def clean_username(self):
        if len(self.cleaned_data['username']) == 11:
            return self.cleaned_data['username']
        else:
            raise ValidationError('用户名为手机号码')

2.3 设定路由

python 复制代码
"""shopping_car_back URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path,include
from index.views import index
from django.views.static import serve
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/index/', include(('index.urls', 'index'), namespace='index')),

    re_path('media/(?P<path>.*)',serve,{'document_root':settings.MEDIA_ROOT},name='media'),
]
python 复制代码
from django.urls import path
from .views import *

urlpatterns = [
    path('login/', loginView.as_view(), name='login'),
]

2.4 View开发

注意#注释部分,postman要用注释的部分,实际vue2需要要没注释的部分

python 复制代码
class loginView(APIView):
    '''
    用户登录与注册
    '''
    # 取消所有认证
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        context = {'state': 'fail', 'msg': '注册或登录失败'}
        # json_str = json.loads(request.body.decode())
        # infos = LoginModelForm(data=json_str)
        infos = LoginModelForm(data=request.POST)
        d = infos.data
        username = d['username']
        password = d['password']
        last_login = ''
        # 用户存在则进行登录验证
        if UserInfo.objects.filter(username=username).first():
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                last_login = user.last_login
                context = {'state': 'success', 'msg': '登录成功'}
        else:
            # 用户不存在进行用户注册
            context = {'state': 'success', 'msg': '注册成功'}
            d = dict(username=username, password=password, is_staff=1, is_active=1)
            user = UserInfo.objects.create_user(**d)
            user.save()
            login(request, user)
        context['username'] = username
        context['last_login'] = last_login
        return Response(context)

2.5 postman测试

2.5.1 注册测试

2.5.2 数据库查看

2.5.3 登陆测试

3. 退出接口

3.1 退出路由

python 复制代码
from django.urls import path
from .views import *

urlpatterns = [
    path('login/', loginView.as_view(), name='login'),
    path('logout/', logoutView.as_view(), name='logout'),
]

3.2 退出view

python 复制代码
class MySessionAuthentication(SessionAuthentication):
    '''
    自定义SessionAuthentication,取消CSRF验证
    '''
    def authenticate(self, request):
        user = getattr(request._request, 'user', None)
        if not user or not user.is_active:
            return None
        return (user, None)

class logoutView(APIView):
    '''
    退出用户登录
    '''
    authentication_classes = [MySessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request):
        context = {'state': 'fail', 'msg': '退出失败'}
        # 使用内置函数logout退出用户登录状态
        if request.user.username:
            logout(request)
            context = {'state': 'success', 'msg': '退出成功'}
        return Response(context)

3.3 postman测试

相关推荐
rhythmcc1 小时前
【Django5】django的helloworld
python·django
BYSJMG3 小时前
计算机毕设设计推荐-基于python+Djanog大数据的电影数据可视化分析
大数据·数据库·python·django·毕业设计·课程设计·毕设
J不A秃V头A3 小时前
el-table使用el-switch选择器没效果
javascript·vue.js·elementui
BYSJMG4 小时前
计算机毕业设计选题推荐-基于python+Django的全屋家具定制服务平台
开发语言·数据库·python·django·毕业设计·课程设计·毕设
mariokkm4 小时前
Django一分钟:借助Django的认证系统快速实现RBAC权限校验以及Session会话
python·安全·django·web
EelBarb4 小时前
python:django项目知识点01——前期配置、用户管理、权限核验、django-orm
python·django
拾伍廿肆4 小时前
Django 聚合查询
数据库·django
A乐神4 小时前
Django 基础之启动命令和基础配置
后端·python·django
穷酸的小明4 小时前
mac m1 electron生产环境使用prisma,sqlite
macos·electron·sqlite