首页
关于
留言
友联
壁纸
统计
Search
1
python 爬虫
89 阅读
2
nas内网穿透
81 阅读
3
jenkins docker 部署 前端
73 阅读
4
VUE codemirror插件 设置回显对象
67 阅读
5
js前端密码校验
60 阅读
默认分类
前端
后端
其他
登录
Search
标签搜索
python
React
Django
爬虫
css
2c
累计撰写
19
篇文章
累计收到
12
条评论
首页
栏目
默认分类
前端
后端
其他
页面
关于
留言
友联
壁纸
统计
搜索到
2
篇与
的结果
2022-04-28
python Django增删改查 快速体验
先创建个app子级python .\manage.py startapp app01 ## 然后创建数据模型 **app01下的** **modules.py文件**from django.db import models # Create your models here. class UserInfo(models.Model): name=models.CharField(max_length=32) password=models.CharField(max_length=12) age=models.IntegerField() tel=models.IntegerField(max_length=11)配置数据库'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '数据库名', 'USER': '数据库用户名', 'PASSWORD': '密码', 'HOST': '127.0.0.1', 'PORT': '3306', }迁移数据库python manage.py makemigrations 和 python manage.py migrate写路由urlfrom django.contrib import admin from django.urls import path,include from app01 import views urlpatterns = [ # path('admin/', admin.site.urls), # path('index/',views.index), # path('user/list/', views.user_list), # path('login/', views.ApiLogin.as_view()), # path('del/', views.ApiDel.as_view()), path('add/', views.addUser.as_view()), path('user/', views.UserList.as_view()), path('updateuser/', views.upDateUser.as_view()), path('del/', views.deluser.as_view()), ] 4.view页面编写增删改查from django.shortcuts import render,HttpResponse from rest_framework.views import APIView # Create your views here. from django import views from app01.models import UserInfo from rest_framework.response import Response from app01.ser import APIViewUserInfo class addUser(APIView): def post(self,request): obj=APIViewUserInfo(data=request.data) if obj.is_valid(): obj.save() return Response({"data":obj.data, "status" : 201,"message":"添加用户成功"}) return Response(data=obj.errors,status=400) class UserList(APIView): def get(self,request): obj=UserInfo.objects.all() ser=APIViewUserInfo(instance=obj,many=True) return Response(ser.data) class upDateUser(APIView): def post(self,request): print(request.data.get('id')) i=request.data.get('id') try: user=UserInfo.objects.get(id=i) except Exception as e: return Response(data='不存在', status=201) # 创建序列化对象,并将要反序列化的数据传递给data构造参数,进而进行验证 user.password=request.data.get('password') if request.data.get('name')!='': print(request.data.get('name')=='') user.name=request.data.get('name') user.save() return Response(status=400) class deluser(APIView): def post(self,request): id=request.data.get('id') UserInfo.objects.filter(id=id).delete() return Response({"msg":'删除成功',"state":"true"}) # def index(request): # return HttpResponse("欢迎使用") # # # def user_list(request): # return render(request,"user_list.html") # # class ApiLogin(APIView): # def get(self,request): # return HttpResponse('get') # def post(self,request): # UserInfo.objects.create(name='张三',password='123456',age=15,tel='1234567891') # obj=UserInfo.objects.all() # print(obj) # return HttpResponse('post') # # class ApiDel(APIView): # def post(self,request): # UserInfo.objects.filter(id=4).delete() # return HttpResponse('删除成功')5.序列化 反序列化# -*- coding: utf-8 -*- from rest_framework import serializers from app01.models import UserInfo class APIViewUserInfo(serializers.Serializer): """图书数据序列化器""" id = serializers.IntegerField(label='ID', read_only=True) # 主键序列化 # 第一:普通字段序列化 name = serializers.CharField(label='名称', max_length=20) password = serializers.CharField(label='密码') age = serializers.IntegerField(label='年龄', required=False) tel = serializers.IntegerField(label='电话', required=False) # # 第二:一对多字段序列化 # heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) # # 第三:自定义显示(显示多对多) # xxx = serializers.SerializerMethodField(read_only=True) class Meta: model = UserInfo # 自定义显示 多对多 字段 # 定义创建语法:ser.save()执行,就会立刻调用create方法用来创建数据 def create(self, validated_data): '''validated_data: 表单或者vue请求携带的json:{"username":"zhangsan","password":"123456"}''' return self.Meta.model.objects.create(**validated_data)
2022年04月28日
53 阅读
0 评论
0 点赞
2022-04-28
Django JWT token 登录注册
setting.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'corsheaders', # 添加 django-cors-headers 使其可以进行 cors 跨域 'app01', ... ]MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL=True # jwt载荷中的有效期设置 JWT_AUTH = { # 1.token前缀:headers中 Authorization 值的前缀 'JWT_AUTH_HEADER_PREFIX': 'JWT', # 2.token有效期:一天有效 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), # 3.刷新token:允许使用旧的token换新token,接口对接需要设置为true 'JWT_ALLOW_REFRESH': True, # 4.token有效期:token在24小时内过期, 可续期token 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24), # 5.自定义JWT载荷信息:自定义返回格式,需要手工创建 'JWT_RESPONSE_PAYLOAD_HANDLER': 'app01.views.jwt_response_payload_handler', } # AUTHENTICATION_BACKENDS = ['user.utils.EmailAuthBackend'] # 在DRF配置文件中开启认证和权限 REST_FRAMEWORK = { # 用户登陆认证方式 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 在DRF中配置JWT认证 # 'rest_framework.authentication.SessionAuthentication', # 使用session时的认证器 # 'rest_framework.authentication.BasicAuthentication' # 提交表单时的认证器 ], # 权限配置, 顺序靠上的严格 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAdminUser', # 管理员可以访问 'rest_framework.permissions.IsAuthenticated', # 全局配置只有认证用户可以访问接口 # 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 认证用户可以访问, 否则只能读取 # 'rest_framework.permissions.AllowAny', # 所有用户都可以访问 ], }urls.pyfrom django.urls import include, path from rest_framework.authtoken.views import obtain_auth_token from app01 import views from rest_framework_jwt.views import obtain_jwt_token from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('login/', obtain_jwt_token), # 登录url,用于获取token path('register/', views.RegisterView.as_view()), # 注册视图, /user/register/ path('adduser/',views.adduserList.as_view()), path('getuserlist/', views.getuserlist.as_view()), ] views.pyfrom rest_framework.permissions import AllowAny from .models import * from .ser import seruserlist,sergetuserList from django.contrib.auth.backends import ModelBackend from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.pagination import PageNumberPagination def jwt_response_payload_handler(token, user=None, request=None): """ 自定义jwt认证成功返回数据 """ return { 'token': token, 'user_id': user.id, 'username': user.username, "code": 200, "state": True } class RegisterView(APIView): """ 用户注册, 权限是: 匿名用户可访问 """ # 自定义权限类 permission_classes = (AllowAny,) def post(self, request): """ 接收邮箱和密码, 前端校验两遍一致性, 注册成功后返回成功, 然后用户自行登录获取token 1. 随机用户名 2. 生成用户 3. 设置用户密码 4. 保存用户 :param request: :return: {'code':0,'msg':'注册成功'} """ email = request.data.get('email') passwrod = request.data.get('password') username = request.data.get('username') if all([email, passwrod]): pass else: return Response({'code': 9999, 'msg': '参数不全'}) user = User(username=username, email=email) user.set_password(passwrod) # 密码加密 user.save() return Response({'code': 0, 'msg': '注册成功'}) # 用户添加 class adduserList(APIView): # 自定义权限类 def post(self, request): ser=seruserlist(data=request.data) if ser.is_valid(): ser.save() return Response({"msg": '成功',"code":200}) return Response(data=ser.errors,status=400) # 分页(局部):自定义分页器 局部 class PageNum(PageNumberPagination): # 查询字符串中代表每页返回数据数量的参数名, 默认值: None page_size_query_param = 'page_size' # 查询字符串中代表页码的参数名, 有默认值: page page_query_param = 'page' # 一页中最多的结果条数 # max_page_size = 2 # 查询用户 class getuserlist(APIView): def get(self, request): queryset = userlist.objects.all() print(request) if request.GET.get('page'): print(queryset) # 分页 pg = PageNum() page_objs = pg.paginate_queryset(queryset=queryset, request=request, view=self) ser = sergetuserList(instance=page_objs, many=True) # 关联数据多条 return Response(ser.data) ser = sergetuserList(instance=queryset, many=True) # 关联数据多条 return Response(ser.data)
2022年04月28日
41 阅读
0 评论
0 点赞