【创建虚拟环境】
1 # 1.执行命令mkvirtualenv -p python3 smart_api 2 3 # 2.在虚拟环境中装django 4 pip install django==4.2.13 5 6 # 3. 创建后端项目 7 1 使用命令 8 django-admin startproject 项目名 9 2 pycharm创建--指定刚刚创建的虚拟环境 10 -找到刚刚创建的虚拟环境,加入进来,创建项目即可 11 -路径找到 12 -1 重启机器 13 -2 把虚拟环境目录浅一些 14 -3 使用命令创建,使用pycharm打开--》还得指定解释器
变成smart_api1
【欢迎页面】
# 1 后端需要配合接口 welcome
-welcome表:图片,id,跳转地址。。。
-接口:welcome接口
1 模型表:models.py 2 3 from django.db import models 4 5 6 # Create your models here. 7 class Welcome(models.Model): 8 img = models.ImageField(upload_to='welcome', default='slash.png') 9 order = models.IntegerField() 10 link = models.CharField(max_length=32) 11 create_time = models.DateTimeField(auto_now=True) 12 is_delete = models.BooleanField(default=False) 13 14 15 -------------------------------------------------------------------------------------- 16 views.py 17 18 from rest_framework.mixins import ListModelMixin 19 from rest_framework.viewsets import GenericViewSet 20 from core.models import Welcome 21 from core.serializers import WelcomeSerialzier 22 23 24 # Create your views here. 25 class WelcomeView(GenericViewSet, ListModelMixin): 26 queryset = Welcome.objects.all().filter(is_delete=False).order_by('-order') 27 serializer_class = WelcomeSerialzier 28 29 ------------------------------------------------------------------------------------- 30 serializer.py 31 32 from rest_framework import serializers 33 34 from core.models import Welcome 35 36 37 class WelcomeSerialzier(serializers.ModelSerializer): 38 class Meta: 39 model = Welcome 40 fields = ['img', 'link'] 41 42 --------------------------------------------------------------------------------------- 43 urls.py 44 45 from .views import WelcomeView 46 from rest_framework.routers import SimpleRouter 47 48 router = SimpleRouter() 49 router.register('welcome', WelcomeView,'welcome') 50 51 urlpatterns = [ 52 53 ] 54 55 urlpatterns += router.urls 56 57 -------------------------------------------------------------------------------------- 58 settings.py 59 60 MEDIA_URL = '/media/' 61 MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 1 后端创建轮播图表和公告表
# 2 admin中录入数据
-simpleui
1 models.py 2 3 # 轮播图表 4 class Banner(models.Model): 5 img = models.ImageField(upload_to='banner', default='banner1.png', verbose_name='图片') 6 order = models.IntegerField(verbose_name='顺序') 7 create_time = models.DateTimeField(auto_now=True, verbose_name='创建时间') 8 is_delete = models.BooleanField(default=False, verbose_name='是否删除') 9 10 class Meta: 11 verbose_name_plural = '轮播图' 12 13 14 # 公告表 15 class Notice(models.Model): 16 title = models.CharField(max_length=64, verbose_name='公共标题') 17 content = models.TextField(verbose_name='内容') 18 img = models.ImageField(upload_to='notice', default='notice.png', verbose_name='公告图片') 19 create_time = models.DateTimeField(auto_now=True, verbose_name='创建时间') 20 21 class Meta: 22 verbose_name_plural = '公告表' 23 24 25 -------------------------------------------------------------------------------------- 26 views.py 27 28 29 # 轮播图接口 30 class BannerView(GenericViewSet, ListModelMixin): 31 queryset = Banner.objects.all().filter(is_delete=False).order_by('order')[:2] 32 serializer_class = BannerSerializer 33 34 def list(self, request, *args, **kwargs): 35 res = super().list(request, *args, **kwargs) 36 notice = Notice.objects.all().order_by('create_time').first() 37 serializer = NoticeSerializer(instance=notice) 38 return Response({'code': 100, 'msg': '成功', 'banner': res.data, 'notice': serializer.data}) 39 40 -------------------------------------------------------------------------------------- 41 serializer.py 42 43 # 轮播图表序列化类 44 class BannerSerializer(serializers.ModelSerializer): 45 class Meta: 46 model = Banner 47 fields = '__all__' 48 49 50 # 社区通知序列化类 51 class NoticeSerializer(serializers.ModelSerializer): 52 class Meta: 53 model = Notice 54 fields = ['id', 'title','content'] 55 56 ----------------------------------------------------------------------------------- 57 urls.py 58 59 router.register('banner', BannerView,'banner')
pip install django-simpleui
信息采集拍照上传
# 1 小程序端拍照---》上传到咱们后台--》后台保存一份(media)--》把图片---》传到百度ai人脸识别库中存着
# 2 学习
-百度ai人脸库上传
-百度ai人脸库删除
-百度ai人脸库根据人脸匹配
pip3 install baidu-aip
pip3 install pypinyin
pip install chardet
需要安装的模块
1 # 人脸注册 2 3 from aip import AipFace 4 import base64 5 from pypinyin import lazy_pinyin, Style 6 7 8 class BaiDuAI: 9 def __init__(self, APP_ID='76543972', API_KEY='LAJoFtfUTgOfF90UqAtbObq1', 10 SECRET_KEY='2QXO7MOA4uWdAOhjl1Vz4FMeC7xZtL4K'): 11 """ 你的 APPID AK SK """ 12 self.APP_ID = APP_ID 13 self.API_KEY = API_KEY 14 self.SECRET_KEY = SECRET_KEY 15 self.client = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) 16 17 def name_to_pinyin(self, text): 18 style = Style.TONE3 19 name_list = lazy_pinyin(text, style=style) 20 return ''.join(name_list) 21 22 def add_user(self): 23 image = base64.b64encode( 24 open(r'C:\Users\靳小洁\PycharmProjects\smart_api1\scripts\彭于晏.png', 'rb').read()).decode('utf-8') 25 imageType = "BASE64" 26 groupId = "100" 27 userId = self.name_to_pinyin('彭于晏') 28 """ 调用人脸注册 """ 29 res = self.client.addUser(image, imageType, groupId, userId) 30 print(res) 31 32 """ 如果有可选参数 """ 33 ''' 34 {'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 937906163, 'timestamp': 1716948937, 'cached': 0, 'result': {'face_token': '7598884f9d9a349218941e8e6f52c884', 'location': {'left': 493.4, 'top': 329.74, 'width': 348, 'height': 321, 'rotation': -8}}} 35 ''' 36 37 def search(self): 38 image = base64.b64encode(open('彭于晏.png', 'rb').read()).decode('utf-8') 39 imageType = "BASE64" 40 groupIdList = "100,2" 41 """ 调用人脸搜索 """ 42 res = self.client.search(image, imageType, groupIdList); 43 """ 如果有可选参数 """ 44 print(res) 45 ''' 46 {'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 1190062038, 'timestamp': 1716949190, 'cached': 0, 'result': {'face_token': 'bdbc6214eb18ccee1bf72d1f72f0c979', 'user_list': [{'group_id': '100', 'user_id': 'peng2yu2yan4', 'user_info': '', 'score': 14.822490692139}]}} 47 ''' 48 49 def delete(self): 50 userId = "peng2yu2yan4" 51 groupId = "100" 52 faceToken = "374e14ed028e8b3fabe2c18d1656b381" 53 """ 调用人脸删除 """ 54 res = self.client.faceDelete(userId, groupId, faceToken); 55 print(res) 56 ''' 57 {'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 1355696697, 'timestamp': 1716949355, 'cached': 0, 'result': None} 58 ''' 59 60 61 if __name__ == '__main__': 62 ai = BaiDuAI() 63 # ai.add_user() 64 # ai.search() 65 ai.delete()
后端接口
# 1 采集上传接口---》存本地--》存百度ai
# 2 查询今天采集数据--》1 当前用户(没实现) 2 当天采集的数据 3 总条数Collection.objects.all().filter(create_time__gte=datetime.now().date())
# 3 删除采集接口-->id号删除
1 新增表模型 2 3 # 采集表 4 class Collection(models.Model): 5 name = models.CharField(max_length=32, verbose_name='采集人员姓名') 6 name_pinyin = models.CharField(max_length=32, verbose_name='姓名拼音', null=True) 7 avatar = models.ImageField(upload_to='collection/%Y/%m/%d', default='default.png', verbose_name='头像') 8 create_time = models.DateTimeField(auto_now=True, verbose_name='采集时间') 9 face_token = models.CharField(max_length=128, verbose_name='百度Token', null=True) 10 # 区域是外键关联 11 area = models.ForeignKey('Area', on_delete=models.CASCADE, verbose_name='网格区域', null=True) 12 13 class Meta: 14 verbose_name_plural = '采集表' 15 16 def __str__(self): 17 return self.name 18 19 20 # 区域表 21 class Area(models.Model): 22 name = models.CharField(max_length=32, verbose_name='网格区域名称') 23 desc = models.CharField(max_length=32, verbose_name='网格简称') 24 user = models.ForeignKey('UserInfo', on_delete=models.CASCADE, null=True, verbose_name='负责用户') 25 26 class Meta: 27 verbose_name_plural = '区域表' 28 29 def __str__(self): 30 return self.name 31 32 33 # 用户表 34 class UserInfo(models.Model): 35 name = models.CharField(max_length=32, verbose_name='姓名') 36 avatar = models.FileField(max_length=128, upload_to='avatar', verbose_name='头像') 37 create_date = models.DateField(auto_now_add=True, verbose_name='日期') 38 score = models.IntegerField(default=0, verbose_name='积分') 39 40 class Meta: 41 verbose_name_plural = '用户表' 42 43 def __str__(self): 44 return self.name 45 46 47 =========================================== 48 视图类 49 50 class CollectionView(GenericViewSet, ListModelMixin, DestroyModelMixin, CreateModelMixin): 51 # 查出当天的--》没过滤当前用户 52 queryset = Collection.objects.all().filter(create_time__gte=datetime.now().date()) 53 serializer_class = CollectionSerializer 54 55 def get_serializer_class(self): 56 if self.action == 'create': 57 return CollectionSaveSerializer 58 else: 59 return CollectionSerializer 60 61 def list(self, request, *args, **kwargs): 62 # 过滤当前用户采集的--》多种类型用户,数据权限不一样 63 res = super().list(request, *args, **kwargs) 64 today_count = len(self.get_queryset()) 65 return Response({'code': 100, 'msg': '成功', 'result': res.data, 'today_count': today_count}) 66 67 # 删除人脸,没有删除 具体的图片--》定时任务--》每天晚上备份用户头像 68 def destroy(self, request, *args, **kwargs): 69 from libs.baidu_ai import BaiDuFace 70 instance = self.get_object() 71 # 百度ai中删除 72 baidu = BaiDuFace() 73 res = baidu.delete(instance.name_pinyin, instance.face_token) 74 print(res) 75 self.perform_destroy(instance) 76 return Response() 77 78 # def perform_destroy(self, instance): 79 # from libs.baidu_ai import BaiDuFace 80 # baidu = BaiDuFace() 81 # res = baidu.delete(instance.name_pinyin, instance.face_token) 82 # print(res) 83 # super().perform_destroy(instance) 84 85 86 ================================================ 87 序列化类 88 89 # 上传人脸序列化类 90 class CollectionSaveSerializer(serializers.ModelSerializer): 91 class Meta: 92 model = Collection 93 fields = ['name', 'avatar', 'area'] 94 95 def create(self, validated_data): 96 # 在百度ai注册 97 from libs.baidu_ai import BaiDuFace 98 baidu = BaiDuFace() 99 avatar_file_object = validated_data.get('avatar') 100 print(avatar_file_object) 101 name = validated_data.get('name') 102 name_pinyin = baidu.name_to_pinyin(name) 103 res = baidu.add_user(avatar_file_object, name, name_pinyin) 104 validated_data['name_pinyin'] = name_pinyin 105 validated_data['face_token'] = res.get('result').get('face_token') 106 instance = super().create(validated_data) 107 return instance 108 109 110 # 采集序列化类 111 class CollectionSerializer(serializers.ModelSerializer): # 查询所有序列化类 112 class Meta: 113 model = Collection 114 fields = ['id', 'name', 'avatar', 'area'] 115 depth = 1 # area 外键关联详情拿到 116 117 118 ================================================ 119 libs--baidu_ai 120 121 # pip install baidu-aip 122 from aip import AipFace 123 import base64 124 125 from pypinyin import lazy_pinyin, Style 126 127 128 class BaiDuFace: 129 # 注册应用有的 130 def __init__(self, APP_ID='', API_KEY='', 131 SECRET_KEY=''): 132 self.APP_ID = APP_ID 133 self.API_KEY = API_KEY 134 self.SECRET_KEY = SECRET_KEY 135 self.client = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) 136 137 # 注册人脸 138 def add_user(self, file_obj, name,userId): 139 # 把图片转成base64 140 image = base64.b64encode(file_obj.read()).decode('utf-8') 141 imageType = "BASE64" 142 groupId = "100" 143 # userId = "dilireba" # 用人名拼音 144 """ 调用人脸注册 """ 145 # client.addUser(image, imageType, groupId, userId); 146 147 """ 如果有可选参数 """ 148 options = {} 149 options["user_info"] = name 150 options["quality_control"] = "NORMAL" 151 options["liveness_control"] = "LOW" 152 options["action_type"] = "REPLACE" 153 """ 带参数调用人脸注册 """ 154 res = self.client.addUser(image, imageType, groupId, userId) 155 156 return res 157 158 # 删除人脸 159 def delete(self, userId, faceToken): 160 groupId = "100" 161 """ 调用人脸删除 """ 162 res = self.client.faceDelete(userId, groupId, faceToken) 163 return res 164 165 # 搜索人脸 166 def search(self, file_obj): 167 image = base64.b64encode(file_obj.read()).decode('utf-8') 168 imageType = "BASE64" 169 groupIdList = "100" 170 """ 调用人脸搜索 """ 171 res = self.client.search(image, imageType, groupIdList) 172 return res 173 174 # 人名转拼音 175 def name_to_pinyin(self, text): 176 style = Style.TONE3 177 name_list = lazy_pinyin(text, style=style) 178 return ''.join(name_list) 179 180 181 ================================================= 182 路由 183 184 router.register('collection', CollectionView, 'collection') # 3个接口 185 ''' 186 http://192.168.1.96:8000/api/v1/collection/ # get 获取数据 187 http://192.168.1.96:8000/api/v1/collection/ # post 提交采集 188 http://192.168.1.96:8000/api/v1/collection/1/ # delete 删除 189 '''
查询所有网格接口
1 视图类 2 3 # 查询所有网格接口 4 class AreaView(GenericViewSet, ListModelMixin): 5 queryset = Area.objects.all() 6 serializer_class = AreaSerializer 7 8 9 ================================================= 10 序列化类 11 12 class AreaSerializer(serializers.ModelSerializer): 13 class Meta: 14 model = Area 15 fields = ['id', 'name', 'desc'] 16 17 ================================================ 18 路由 19 20 router.register('area', AreaView, 'area')
信息采集统计
1 视图类 2 3 # 信息采集统计 4 class StatisticsView(GenericViewSet, ListModelMixin): 5 # 按天分组数个数 6 queryset = Collection.objects.annotate(date=Trunc('create_time', 'day')).values('date').annotate( 7 count=Count('id')).values('date', 'count') 8 serializer_class = StatisticsListSerializer 9 10 ======================================== 11 序列化类 12 13 # 信息采集序列化类 14 class StatisticsListSerializer(serializers.Serializer): 15 date = serializers.DateTimeField(format="%Y年%m月%d日") 16 count = serializers.IntegerField() 17 18 19 ======================================= 20 路由 21 22 router.register('statistics', StatisticsView, 'statistics')
人脸检测
1 视图类 2 3 # 人脸检测接口 4 class FaceView(GenericViewSet): 5 def create(self, request, *args, **kwargs): 6 avatar_object = request.data.get('avatar') 7 if not avatar_object: 8 return Response({"msg": "未提交图像", "code": 101}) 9 from libs.baidu_ai import BaiDuFace 10 ai = BaiDuFace() 11 result = ai.search(avatar_object) 12 if result.get('error_code') == 0: # 查询到 13 # {'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 2159604393, 'timestamp': 1713864959, 'cached': 0, 'result': {'face_token': '095994eca64424cee347b59e0a7edc0e', 'user_list': [{'group_id': '100', 'user_id': 'li3si1xian4', 'user_info': '', 'score': 98.035797119141}]}} 14 user = result.get('result').get('user_list')[0] 15 user_info = user.get('user_info') 16 user_id = user.get('user_id') 17 score = user.get('score') 18 return Response({"code": 100, 'msg': '匹配成功', 'user_info': user_info, 'user_id': user_id, 'score': score, 19 'avatar': ''}) 20 else: 21 return Response({"code": 102, 'msg': '匹配失败,该人员可能不是我社区人员,注意防范'}) 22 23 24 =========================================== 25 路由 26 27 # 人脸检测接口 28 class FaceView(GenericViewSet): 29 def create(self, request, *args, **kwargs): 30 avatar_object = request.data.get('avatar') 31 if not avatar_object: 32 return Response({"msg": "未提交图像", "code": 101}) 33 from libs.baidu_ai import BaiDuFace 34 ai = BaiDuFace() 35 result = ai.search(avatar_object) 36 if result.get('error_code') == 0: # 查询到 37 # {'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 2159604393, 'timestamp': 1713864959, 'cached': 0, 'result': {'face_token': '095994eca64424cee347b59e0a7edc0e', 'user_list': [{'group_id': '100', 'user_id': 'li3si1xian4', 'user_info': '', 'score': 98.035797119141}]}} 38 user = result.get('result').get('user_list')[0] 39 user_info = user.get('user_info') 40 user_id = user.get('user_id') 41 score = user.get('score') 42 return Response({"code": 100, 'msg': '匹配成功', 'user_info': user_info, 'user_id': user_id, 'score': score, 43 'avatar': ''}) 44 else: 45 return Response({"code": 102, 'msg': '匹配失败,该人员可能不是我社区人员,注意防范'})
公告
1 视图类 2 3 # 公告 4 class NoticeView(GenericViewSet, ListModelMixin): 5 queryset = Notice.objects.all().order_by('create_time') 6 serializer_class = NoticeSerializer 7 8 9 ================================================= 10 序列化类 11 12 class NoticeSerializer(serializers.ModelSerializer): 13 # create_time = serializers.DateTimeField(format="%Y-%m-%d") 14 class Meta: 15 model = Notice 16 fields = ['id', 'title', 'img', 'create_time', 'content'] 17 extra_kwargs = { 18 'create_time': {'format': "%Y-%m-%d"} 19 } 20 21 ================================================= 22 路由 23 24 router.register('notice', NoticeView, 'notice')
社区活动
1 新增模型表 2 3 # 活动表 4 class Activity(models.Model): 5 title = models.CharField(verbose_name="活动标题", max_length=128) 6 text = models.TextField(verbose_name="活动描述", null=True, blank=True) 7 date = models.DateField(verbose_name="举办活动日期") 8 9 count = models.IntegerField(verbose_name='报名人数', default=0) 10 total_count = models.IntegerField(verbose_name='总人数', default=0) 11 score = models.IntegerField(verbose_name="积分", default=0) 12 13 join_record = models.ManyToManyField(verbose_name="参与者", 14 through="JoinRecord", 15 through_fields=("activity", "user"), 16 to="UserInfo") 17 18 class Meta: 19 verbose_name_plural = '活动表' 20 21 def __str__(self): 22 return self.title 23 24 25 # 活动报名记录 26 class JoinRecord(models.Model): 27 user = models.ForeignKey(verbose_name='用户', to="UserInfo", on_delete=models.CASCADE) 28 activity = models.ForeignKey(verbose_name="活动", to="Activity", on_delete=models.CASCADE, related_name='ac') 29 30 exchange = models.BooleanField(verbose_name="是否已兑换", default=False) 31 32 class Meta: 33 verbose_name_plural = '活动报名记录' 34 35 36 ================================================ 37 视图类 38 39 # 活动 40 class ActivityView(GenericViewSet, ListModelMixin): 41 queryset = Activity.objects.all().order_by('date') 42 serializer_class = ActivitySerializer 43 44 45 ================================================= 46 序列化类 47 48 # 活动序列化类 49 class ActivitySerializer(serializers.ModelSerializer): 50 class Meta: 51 model = Activity 52 fields = ['id', 'title', 'text', 'date', 'count', 'score', 'total_count'] 53 extra_kwargs = { 54 'date': {'format': "%Y-%m-%d"} 55 } 56 57 ================================================ 58 路由 59 60 router.register('activity', ActivityView, 'activity')