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测试

相关推荐
落魄小二1 小时前
el-table 表格索引不展示问题
javascript·vue.js·elementui
YUJIANYUE5 小时前
PHP将指定文件夹下多csv文件[即多表]导入到sqlite单文件
jvm·sqlite·php
coberup5 小时前
django Forbidden (403)错误解决方法
python·django·403错误
别拿曾经看以后~5 小时前
【el-form】记一例好用的el-input输入框回车调接口和el-button按钮防重点击
javascript·vue.js·elementui
过期动态20 小时前
详解Python面向对象程序设计
开发语言·python·pycharm·django
Bonne journée21 小时前
SQLite数据库是什么?DB Browser for SQLite是什么?
数据库·sqlite
阿乾之铭21 小时前
通过Django 与 PostgreSQL 进行WEB开发详细流程
python·postgresql·django
春天的菠菜1 天前
【django】Django REST Framework (DRF) 项目中实现 JWT
后端·python·django·jwt
千里码aicood1 天前
[含文档+PPT+源码等]精品基于Python实现的django房屋出租系统的设计与实现
开发语言·python·django
啧不应该啊1 天前
Django替换现有用户模型(auth_user)
后端·python·django