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

相关推荐
luoluoal5 小时前
基于python的人脸识别的酒店客房入侵检测系统(源码+文档)
python·mysql·django·毕业设计·源码
小小弯_Shelby13 小时前
el-table固定列显示错位问题处理
vue.js·elementui
dreams_dream13 小时前
前后端分离项目多环境配置完整笔记
数据库·笔记·sqlite
风清扬_jd13 小时前
sqlite支持sqlcipher-4.12.0版本加密编译说明
数据库·c++·sqlite·sqlcipher·sqlite加密
Blossom.11813 小时前
从数字大脑到物理实体:具身智能时代的大模型微调与部署实战
人工智能·python·深度学习·fpga开发·自然语言处理·矩阵·django
墨染青竹梦悠然13 小时前
基于Django+vue的零食商城
python·django
喵手1 天前
Python爬虫实战:快递物流轨迹采集实战:从公开查询到时间线可视化(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·零基础python爬虫教学·csv导出·快递物流轨迹采集
移幻漂流1 天前
03 - SQLite 技术全景:嵌入式关系数据库引擎完整解析
android·数据库·sqlite
WangYaolove13141 天前
基于Python的旅游城市关键词分析
python·django·毕业设计·源码·计算机源码
喵手1 天前
Python爬虫实战:论坛社区数据采集实战:从主题列表到分页回帖爬取(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·零基础python爬虫教学·论坛社区数据采集·csv采集数据导出