Django的用户信息后端接口

一.
1-1,序列化器部分

from myapp.models import *  #导入所有模型
from rest_framework import serializers		#导入序列器
from rest_framework.exceptions import ValidationError	
import re	#导入re功能包
class UserSer(serializers.ModelSerializer):     #用户模型类的序列化器
    password = serializers.CharField(max_length=64, write_only=True,trim_whitespace=True)
    class Meta:
        model =User
        fields =['id','username','password','mobile','email','date_joined','last_login']
        read_only_fields =['id']		#只读字段设置id字段
    def validate(self, attrs):  #反序列化时,对接收的数据进行全局的校验
        #设置attrs为获取数据的存放函数
        # print("验证数据中...", attrs)
        username =attrs.get("username")     #获取数据
        password =attrs.get("password")
        mobile =attrs.get("mobile")
        email =attrs.get("email")
        if not all([username,password,mobile,email]):		 #三者只要有一个为空,则抛出异常
            raise ValidationError		#ValidationError	合法性错误	raise 	发起
        # 用户名需包含字母、数字、下划线,长度为5-20
        if not re.findall("^\w{5,20}$",username):	#检验用户名的正则
            raise ValidationError("用户名不符合规范")
        # 密码是8到20位数字、字母或下划线以及特殊!@#$%^&*符号
        elif not re.findall(r"^[\w!@#$%^&*]{8,20}$", password):	#检验密码的正则
            raise ValidationError("密码不符合规范")
        elif not re.findall(r"^1[34578]\d{9}$", mobile):	#检验手机号的正则
            raise ValidationError("手机格式不符合规范")
        else:
            return attrs		#如果以上条件都满足,则返回数据到attrs函数
    #重写序列化器的create方法
    def create(self, validated_data):       #validated_data验证过的数据
        #自己创建的数据对象,并加密数据添加到数据库
        user = User.objects.create_user(**validated_data)		

        # user.set_password(validated_data.get("password"))
        # user.save()
        return user	

1-2,视图部分

from rest_framework.views import APIView	#导入api视图
from rest_framework.response import Response	#导入响应
from myapp.serializers import UserSer	#导入序列化器
from myapp.models import User	#导入模型层
from rest_framework.viewsets import ModelViewSet    #导入视图集
from rest_framework.pagination import PageNumberPagination      #导入分页器

class MyPagination(PageNumberPagination):       #定义自己的分页类
    page_size = 3		#每页3个数据
    max_page_size = 5		#最大页面数为5
    page_query_param = "page"	#页面查询参数
    page_size_query_param = "pageSize"      #/users/?page=2&pageSize=3
class UserInfoViewSet(ModelViewSet): #用户信息视图
    queryset = User.objects.all()   #获取查询集
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个关于如何使用Python Django搭建后端接口来识别水果图片的问题。我可以提供一些思路和代码片段供参考。 首先,需要安装Django和相关的Python库,如numpy、Pillow、joblib等。然后,创建一个Django项目和应用程序,设置数据库和路由等。 接下来,需要将训练好的模型类型为pkl加载进来,可以使用joblib库来实现。假设我们已经将模型保存在了项目目录下的`model.pkl`文件中,可以通过以下代码将其加载进来: ```python import joblib model = joblib.load('model.pkl') ``` 然后,在应用程序中编写一个视图函数来处理用户上传的图片,并调用模型进行识别。可以使用Pillow库来打开和处理图片,使用numpy库来将图片转换为模型所需要的格式。假设我们的模型需要输入一张大小为224x224的RGB图片,可以使用以下代码来处理: ```python from PIL import Image import numpy as np def predict_fruit(image): # Open the image img = Image.open(image) # Resize the image to 224x224 img = img.resize((224, 224)) # Convert the image to a numpy array img_array = np.array(img) # Convert the image to RGB (if it is grayscale) if len(img_array.shape) == 2: img_array = np.stack([img_array] * 3, axis=-1) # Convert the image to a float tensor and normalize it img_array = img_array.astype('float32') / 255.0 # Add a batch dimension img_array = np.expand_dims(img_array, axis=0) # Make the prediction pred = model.predict(img_array) # Get the predicted class label and confidence score class_idx = np.argmax(pred[0]) confidence = pred[0][class_idx] # Return the predicted class label and confidence score return class_idx, confidence ``` 最后,在路由中定义一个接口,接收用户上传的图片并调用上述视图函数进行识别,返回识别结果给前端。假设我们的接口路径为`/api/predict`,可以使用以下代码来实现: ```python from django.http import JsonResponse def predict(request): if request.method == 'POST' and request.FILES.get('image'): # Get the uploaded image image = request.FILES['image'] # Make the prediction class_idx, confidence = predict_fruit(image) # Convert the class index to a fruit name fruits = ['apple', 'banana', 'orange'] fruit_name = fruits[class_idx] # Return the prediction as JSON return JsonResponse({'fruit': fruit_name, 'confidence': float(confidence)}) else: return JsonResponse({'error': 'Invalid request'}) ``` 以上是一个简单的使用Python Django搭建后端接口来识别水果图片的示例。当用户上传一张水果照片时,调用接口,根据图像识别出水果种类,返回识别出的水果类型和信度值给前端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值