分享一个基于python的智慧居家养老服务平台 django社区养老管理系统与可视化统计(源码、调试、LW、开题、PPT)

💕💕作者:计算机源码社

💕💕个人简介:本人 八年开发经验,擅长Java、Python、PHP、.NET、Node.js、Android、微信小程序、爬虫、大数据、机器学习等,大家有这一块的问题可以一起交流!

💕💕学习资料、程序开发、技术解答、文档报告

💕💕如需要源码,可以扫取文章下方二维码联系咨询

💕💕Java项目
💕💕微信小程序项目
💕💕Android项目
💕💕Python项目
💕💕PHP项目
💕💕ASP.NET项目
💕💕Node.js项目
💕💕选题推荐

项目实战|基于python的智慧居家养老服务平台的设计与实现

文章目录

1、研究背景

随着全球人口老龄化进程的加速,居家养老已成为许多国家应对人口老龄化的重要策略。然而,传统的居家养老模式面临着诸多挑战,如照护资源不足、服务质量参差不齐、老年人安全隐患等问题。同时,信息技术的迅猛发展为解决这些问题提供了新的可能性。物联网、大数据、人工智能等技术的成熟,为打造智能化、个性化的居家养老服务创造了条件。在这一背景下,开发基于Python的智慧居家养老服务平台,不仅能够整合各方资源,提高养老服务效率,还能为老年人提供更安全、舒适的居家环境,成为应对人口老龄化挑战的有力工具。

2、研究目的和意义

开发智慧居家养老服务平台的主要目的是构建一个综合性的智能养老生态系统。该平台旨在通过Python的强大功能,整合物联网设备、健康监测系统、紧急呼叫系统等多元化技术,实现对老年人生活状态的实时监控和智能分析。平台将提供个性化的健康管理方案,智能调节居家环境,并在紧急情况下快速响应。同时,平台还将连接家庭成员、社区服务人员、医疗机构等多方资源,形成一个高效协同的养老服务网络。通过这种方式,我们希望能够提高居家养老的安全性和舒适度,减轻家庭和社会的照护负担,让老年人能够在熟悉的环境中享受高质量的晚年生活。

从更广泛的社会意义来看,开发这样一个平台具有多重价值,它有助于推动养老产业的转型升级,促进"互联网+养老"模式的发展,为解决人口老龄化带来的社会问题提供创新解决方案。通过数据的积累和分析,平台可以为制定养老政策提供科学依据,推动精准化、差异化的养老服务体系建设。智慧居家养老服务平台的推广将带动相关产业的发展,创造新的就业机会,促进经济增长。这种智能化的养老模式有助于提高老年人的生活质量和幸福感,促进家庭和谐,增强社会凝聚力,对构建积极老龄化社会具有重要意义。

3、系统研究内容

用户管理系统:

开发老年用户、家属和护理人员的注册、登录和身份验证模块

设计用户信息管理功能,包括个人资料、健康状况、紧急联系人等

研究基于Django或Flask的Web应用框架,实现用户界面

服务需求匹配系统:

设计老年人服务需求的分类和标准化模型

开发服务供给方(如护理人员、志愿者)资源库

研究基于机器学习的智能匹配算法,如协同过滤或基于内容的推荐

健康监测与提醒系统:

开发用于记录和分析老年人日常健康数据的模块

设计用药提醒和跟踪功能

社交互动平台:

开发老年人在线社交功能,如兴趣小组、在线聊天

设计活动组织和参与模块

4、系统页面设计






如需要源码,可以扫取文章下方二维码联系咨询

5、参考文献

[1]师玄博.基于数字包容的智慧居家养老服务优化路径研究[J].互联网周刊,2024,(17):44-46.

[2]杜艳莹,梁莉莉,刘洹颖,等.居家养老护理服务平台的应用进展[J].全科护理,2024,22(16):3015-3018.

[3]郑振华.养老变"享老"托起"夕阳红"[N].珠海特区报,2024-08-09(003). DOI:10.38317/n.cnki.nzhtq.2024.001865.

[4]周涛,时鸣泽,刘春丽,等.情境感知理论下的智慧居家养老服务平台设计研究[J].家电维修,2024,(08):77-79.

[5]刘静静.让老年人在家门口享受普惠便捷服务[N].中国社会报,2024-07-04(003). DOI:10.28698/n.cnki.nshhu.2024.000803.

[6]王凤丽.推动乌鲁木齐市社区居家养老服务高质量发展的对策研究[J].中共乌鲁木齐市委党校学报,2024,(02):54-57.

[7]杨晶晶.内蒙古社区智慧居家养老服务研究[D].内蒙古财经大学,2024. DOI:10.27797/d.cnki.gnmgc.2024.000010.

[8]王珊珊.山东省居家养老服务供给困境与对策研究[D].山东财经大学,2024. DOI:10.27274/d.cnki.gsdjc.2024.000959.

[9]张学臣.D市智慧居家养老服务中存在的问题与对策研究[D].山东财经大学,2024. DOI:10.27274/d.cnki.gsdjc.2024.001170.

[10]吴莹莹,王睿.基于社区的居家智慧养老服务平台的研究与设计[J].现代计算机,2023,29(15):109-112.

[11]马萍.数字治理视角下智慧居家养老服务平台的特质、问题及其优化之策[J].人口与社会,2022,38(06):54-65.DOI:10.14132/j.2095-7963.2022.06.005.

[12]张志刚.安全当先社区居家养老服务模式探析------智慧养老安全服务平台体系化构建研究[J].中国安防,2022,(06):93-96.

[13]陈永海.基于民政大数据的智慧居家养老服务平台的构建研究[J].电脑知识与技术,2021,17(15):30-31+47.DOI:10.14004/j.cnki.ckt.2021.1440.

[14]张飞霞.智慧居家养老服务模式:实践与反思------以甘肃为例[J].邢台学院学报,2021,36(01):5-11.

[15]张朕.智慧医养护一体化服务平台分析与设计[D].华中科技大学,2020. DOI:10.27157/d.cnki.ghzku.2020.003958.

[16]张日升,一键通关护服务系统.内蒙古自治区,内蒙古国讯富通科技有限公司,2017-05-12.

[17]刘奕夫,周晓霞,王接飞.空间智能生态城市的建设与实践空间智能生态城市的建设与实践[J].测绘地理信息,2014,39(01):83-84.DOI:10.14188/j.2095-6045.2014.01.020.

6、核心代码

java 复制代码
#coding:utf-8
__author__ = "ila"
import base64, copy, logging, os, sys, time, xlrd, json, datetime, configparser
from django.http import JsonResponse
from django.apps import apps
from django.db.models.aggregates import Count,Sum
from django.db.models import Case, When, IntegerField, F
from django.forms import model_to_dict
from .models import jiankangbaogao
from util.codes import *
from util.auth import Auth
from util.common import Common
import util.message as mes
from django.db import connection
import random
from django.core.mail import send_mail
from django.conf import settings
from django.shortcuts import redirect
from django.db.models import Q
from util.baidubce_api import BaiDuBce
from .config_model import config






def jiankangbaogao_register(request):
    if request.method in ["POST", "GET"]:
        msg = {'code': normal_code, "msg": mes.normal_code}
        req_dict = request.session.get("req_dict")
        req_dict['mima'] = Common.md5(Common, req_dict.get('mima'))


        error = jiankangbaogao.createbyreq(jiankangbaogao, jiankangbaogao, req_dict)
        if error != None:
            msg['code'] = crud_error_code
            msg['msg'] = "用户已存在,请勿重复注册!"
        return JsonResponse(msg)

def jiankangbaogao_login(request):
    if request.method in ["POST", "GET"]:
        msg = {'code': normal_code, "msg": mes.normal_code}
        req_dict = request.session.get("req_dict")
        req_dict['password'] = Common.md5(Common, req_dict.get('password'))
        datas = jiankangbaogao.getbyparams(jiankangbaogao, jiankangbaogao, req_dict)
        if not datas:
            msg['code'] = password_error_code
            msg['msg'] = mes.password_error_code
            return JsonResponse(msg)

        try:
            __sfsh__= jiankangbaogao.__sfsh__
        except:
            __sfsh__=None

        if  __sfsh__=='是':
            if datas[0].get('sfsh')!='是':
                msg['code']=other_code
                msg['msg'] = "账号已锁定,请联系管理员审核!"
                return JsonResponse(msg)
                
        req_dict['id'] = datas[0].get('id')


        return Auth.authenticate(Auth, jiankangbaogao, req_dict)


def jiankangbaogao_logout(request):
    if request.method in ["POST", "GET"]:
        msg = {
            "msg": "登出成功",
            "code": 0
        }

        return JsonResponse(msg)


def jiankangbaogao_resetPass(request):
    '''
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code}

        req_dict = request.session.get("req_dict")

        columns=  jiankangbaogao.getallcolumn( jiankangbaogao, jiankangbaogao)

        try:
            __loginUserColumn__= jiankangbaogao.__loginUserColumn__
        except:
            __loginUserColumn__=None
        username=req_dict.get(list(req_dict.keys())[0])
        if __loginUserColumn__:
            username_str=__loginUserColumn__
        else:
            username_str=username
        if 'mima' in columns:
            password_str='mima'
        else:
            password_str='password'

        init_pwd = '123456'
        init_pwd = Common.md5(Common, init_pwd)
        recordsParam = {}
        recordsParam[username_str] = req_dict.get("username")
        records=jiankangbaogao.getbyparams(jiankangbaogao, jiankangbaogao, recordsParam)
        if len(records)<1:
            msg['code'] = 400
            msg['msg'] = '用户不存在'
            return JsonResponse(msg)

        eval('''jiankangbaogao.objects.filter({}='{}').update({}='{}')'''.format(username_str,username,password_str,init_pwd))
        
        return JsonResponse(msg)



def jiankangbaogao_session(request):
    '''
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}

        req_dict={"id":request.session.get('params').get("id")}
        msg['data']  = jiankangbaogao.getbyparams(jiankangbaogao, jiankangbaogao, req_dict)[0]

        return JsonResponse(msg)


def jiankangbaogao_default(request):

    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}
        req_dict = request.session.get("req_dict")
        req_dict.update({"isdefault":"是"})
        data=jiankangbaogao.getbyparams(jiankangbaogao, jiankangbaogao, req_dict)
        if len(data)>0:
            msg['data']  = data[0]
        else:
            msg['data']  = {}
        return JsonResponse(msg)

def jiankangbaogao_page(request):
    '''
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code,  "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
        req_dict = request.session.get("req_dict")

        global jiankangbaogao

        #获取全部列名
        columns=  jiankangbaogao.getallcolumn( jiankangbaogao, jiankangbaogao)

        if "vipread" in req_dict and "vipread" not in columns:
          del req_dict["vipread"]

        #当前登录用户所在表
        tablename = request.session.get("tablename")
            #authColumn=list(__authTables__.keys())[0]
            #authTable=__authTables__.get(authColumn)

            # if authTable==tablename:
                #params = request.session.get("params")
                #req_dict[authColumn]=params.get(authColumn)

        '''__authSeparate__此属性为真,params添加userid,后台只查询个人数据'''
        try:
            __authSeparate__=jiankangbaogao.__authSeparate__
        except:
            __authSeparate__=None

        if __authSeparate__=="是":
            tablename=request.session.get("tablename")
            if tablename!="users" and 'userid' in columns:
                try:
                    req_dict['userid']=request.session.get("params").get("id")
                except:
                    pass

        #当项目属性hasMessage为"是",生成系统自动生成留言板的表messages,同时该表的表属性hasMessage也被设置为"是",字段包括userid(用户id),username(用户名),content(留言内容),reply(回复)
        #接口page需要区分权限,普通用户查看自己的留言和回复记录,管理员查看所有的留言和回复记录
        try:
            __hasMessage__=jiankangbaogao.__hasMessage__
        except:
            __hasMessage__=None
        if  __hasMessage__=="是":
            tablename=request.session.get("tablename")
            if tablename!="users":
                req_dict["userid"]=request.session.get("params").get("id")

        # 判断当前表的表属性isAdmin,为真则是管理员表
        # 当表属性isAdmin="是",刷出来的用户表也是管理员,即page和list可以查看所有人的考试记录(同时应用于其他表)
        __isAdmin__ = None

        allModels = apps.get_app_config('main').get_models()
        for m in allModels:
            if m.__tablename__==tablename:

                try:
                    __isAdmin__ = m.__isAdmin__
                except:
                    __isAdmin__ = None
                break

        # 当前表也是有管理员权限的表
        if  __isAdmin__ == "是" and 'jiankangbaogao' != 'forum':
            if req_dict.get("userid") and 'jiankangbaogao' != 'chat':
                del req_dict["userid"]
        else:
            #非管理员权限的表,判断当前表字段名是否有userid
            if tablename!="users" and 'jiankangbaogao'[:7]!='discuss'and "userid" in jiankangbaogao.getallcolumn(jiankangbaogao,jiankangbaogao):
                req_dict["userid"] = request.session.get("params").get("id")

        #当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为"是",那么该用户查看该表信息时,只能查看自己的
        try:
            __authTables__=jiankangbaogao.__authTables__
        except:
            __authTables__=None

        if __authTables__!=None and  __authTables__!={} and __isAdmin__ == "是":
            try:
                del req_dict['userid']
                # tablename=request.session.get("tablename")
                # if tablename=="users":
                    # del req_dict['userid']
                
            except:
                pass
            for authColumn,authTable in __authTables__.items():
                if authTable==tablename:
                    params = request.session.get("params")
                    req_dict[authColumn]=params.get(authColumn)
                    username=params.get(authColumn)
                    break
        if tablename == 'laoren':
            from .models import laoren
            req_dict['laorenzhanghao'] = request.session.get("params").get(laoren.__loginUserColumn__)
            if 'userid' in req_dict.keys():
                del req_dict["userid"]
        q = Q()

        msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
        msg['data']['pageSize']  =jiankangbaogao.page(jiankangbaogao, jiankangbaogao, req_dict, request, q)

        return JsonResponse(msg)

def jiankangbaogao_autoSort(request):
    '''
    .智能推荐功能(表属性:[intelRecom(是/否)],新增clicktime[前端不显示该字段]字段(调用info/detail接口的时候更新),按clicktime排序查询)
主要信息列表(如商品列表,新闻列表)中使用,显示最近点击的或最新添加的5条记录就行
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code,  "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
        req_dict = request.session.get("req_dict")
        if "clicknum"  in jiankangbaogao.getallcolumn(jiankangbaogao,jiankangbaogao):
            req_dict['sort']='clicknum'
        elif "browseduration"  in jiankangbaogao.getallcolumn(jiankangbaogao,jiankangbaogao):
            req_dict['sort']='browseduration'
        else:
            req_dict['sort']='clicktime'
        req_dict['order']='desc'
        msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
        msg['data']['pageSize']  = jiankangbaogao.page(jiankangbaogao,jiankangbaogao, req_dict)

        return JsonResponse(msg)

#分类列表
def jiankangbaogao_lists(request):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code,  "data":[]}
        msg['data'],_,_,_,_  = jiankangbaogao.page(jiankangbaogao, jiankangbaogao, {})
        return JsonResponse(msg)

def jiankangbaogao_list(request):
    '''
    前台分页
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code,  "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
        req_dict = request.session.get("req_dict")
        #获取全部列名
        columns=  jiankangbaogao.getallcolumn( jiankangbaogao, jiankangbaogao)
        if "vipread" in req_dict and "vipread" not in columns:
          del req_dict["vipread"]
        #表属性[foreEndList]前台list:和后台默认的list列表页相似,只是摆在前台,否:指没有此页,是:表示有此页(不需要登陆即可查看),前要登:表示有此页且需要登陆后才能查看
        try:
            __foreEndList__=jiankangbaogao.__foreEndList__
        except:
            __foreEndList__=None

        if __foreEndList__=="前要登":
            tablename=request.session.get("tablename")
            if tablename!="users" and 'userid' in columns:
                try:
                    req_dict['userid']=request.session.get("params").get("id")
                except:
                    pass
        #forrEndListAuth
        try:
            __foreEndListAuth__=jiankangbaogao.__foreEndListAuth__
        except:
            __foreEndListAuth__=None

        #authSeparate
        try:
            __authSeparate__=jiankangbaogao.__authSeparate__
        except:
            __authSeparate__=None

        if __foreEndListAuth__ =="是" and __authSeparate__=="是":
            tablename=request.session.get("tablename")
            if tablename!="users":
                req_dict['userid']=request.session.get("params",{"id":0}).get("id")

        tablename = request.session.get("tablename")
        if tablename == "users" and req_dict.get("userid") != None:#判断是否存在userid列名
            del req_dict["userid"]
        else:
            __isAdmin__ = None

            allModels = apps.get_app_config('main').get_models()
            for m in allModels:
                if m.__tablename__==tablename:

                    try:
                        __isAdmin__ = m.__isAdmin__
                    except:
                        __isAdmin__ = None
                    break

            if __isAdmin__ == "是":
                if req_dict.get("userid"):
                    # del req_dict["userid"]
                    pass
            else:
                #非管理员权限的表,判断当前表字段名是否有userid
                if "userid" in columns:
                    try:
                        pass
                    except:
                        pass
        #当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为"是",那么该用户查看该表信息时,只能查看自己的
        try:
            __authTables__=jiankangbaogao.__authTables__
        except:
            __authTables__=None

        if __authTables__!=None and  __authTables__!={} and __foreEndListAuth__=="是":
            for authColumn,authTable in __authTables__.items():
                if authTable==tablename:
                    try:
                        del req_dict['userid']
                    except:
                        pass
                    params = request.session.get("params")
                    req_dict[authColumn]=params.get(authColumn)
                    username=params.get(authColumn)
                    break
        
        if jiankangbaogao.__tablename__[:7]=="discuss":
            try:
                del req_dict['userid']
            except:
                pass


        q = Q()
        msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
        msg['data']['pageSize']  = jiankangbaogao.page(jiankangbaogao, jiankangbaogao, req_dict, request, q)

        return JsonResponse(msg)

def jiankangbaogao_save(request):
    '''
    后台新增
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
        req_dict = request.session.get("req_dict")
        if 'clicktime' in req_dict.keys():
            del req_dict['clicktime']
        tablename=request.session.get("tablename")
        __isAdmin__ = None
        allModels = apps.get_app_config('main').get_models()
        for m in allModels:
            if m.__tablename__==tablename:

                try:
                    __isAdmin__ = m.__isAdmin__
                except:
                    __isAdmin__ = None
                break

        #获取全部列名
        columns=  jiankangbaogao.getallcolumn( jiankangbaogao, jiankangbaogao)
        if tablename!='users' and req_dict.get("userid")!=None and 'userid' in columns  and __isAdmin__!='是':
            params=request.session.get("params")
            req_dict['userid']=params.get('id')


        if 'addtime' in req_dict.keys():
            del req_dict['addtime']

        error= jiankangbaogao.createbyreq(jiankangbaogao,jiankangbaogao, req_dict)
        if error!=None:
            msg['code'] = crud_error_code
            msg['msg'] = error

        return JsonResponse(msg)


def jiankangbaogao_add(request):
    '''
    前台新增
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
        req_dict = request.session.get("req_dict")
        tablename=request.session.get("tablename")

        #获取全部列名
        columns=  jiankangbaogao.getallcolumn( jiankangbaogao, jiankangbaogao)
        try:
            __authSeparate__=jiankangbaogao.__authSeparate__
        except:
            __authSeparate__=None

        if __authSeparate__=="是":
            tablename=request.session.get("tablename")
            if tablename!="users" and 'userid' in columns:
                try:
                    req_dict['userid']=request.session.get("params").get("id")
                except:
                    pass

        try:
            __foreEndListAuth__=jiankangbaogao.__foreEndListAuth__
        except:
            __foreEndListAuth__=None

        if __foreEndListAuth__ and __foreEndListAuth__!="否":
            tablename=request.session.get("tablename")
            if tablename!="users":
                req_dict['userid']=request.session.get("params").get("id")


        if 'addtime' in req_dict.keys():
            del req_dict['addtime']
        error= jiankangbaogao.createbyreq(jiankangbaogao,jiankangbaogao, req_dict)
        if error!=None:
            msg['code'] = crud_error_code
            msg['msg'] = error
        return JsonResponse(msg)

def jiankangbaogao_thumbsup(request,id_):
    '''
     点赞:表属性thumbsUp[是/否],刷表新增thumbsupnum赞和crazilynum踩字段,
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
        req_dict = request.session.get("req_dict")
        id_=int(id_)
        type_=int(req_dict.get("type",0))
        rets=jiankangbaogao.getbyid(jiankangbaogao,jiankangbaogao,id_)

        update_dict={
        "id":id_,
        }
        if type_==1:#赞
            update_dict["thumbsupnum"]=int(rets[0].get('thumbsupnum'))+1
        elif type_==2:#踩
            update_dict["crazilynum"]=int(rets[0].get('crazilynum'))+1
        error = jiankangbaogao.updatebyparams(jiankangbaogao,jiankangbaogao, update_dict)
        if error!=None:
            msg['code'] = crud_error_code
            msg['msg'] = error
        return JsonResponse(msg)


def jiankangbaogao_info(request,id_):
    '''
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}

        data = jiankangbaogao.getbyid(jiankangbaogao,jiankangbaogao, int(id_))
        if len(data)>0:
            msg['data']=data[0]
            if msg['data'].__contains__("reversetime"):
                if isinstance(msg['data']['reversetime'], datetime.datetime):
                    msg['data']['reversetime'] = msg['data']['reversetime'].strftime("%Y-%m-%d %H:%M:%S")
                else:
                    if msg['data']['reversetime'] != None:
                        reversetime = datetime.datetime.strptime(msg['data']['reversetime'], '%Y-%m-%d %H:%M:%S')
                        msg['data']['reversetime'] = reversetime.strftime("%Y-%m-%d %H:%M:%S")

        #浏览点击次数
        try:
            __browseClick__= jiankangbaogao.__browseClick__
        except:
            __browseClick__=None

        if __browseClick__=="是"  and  "clicknum"  in jiankangbaogao.getallcolumn(jiankangbaogao,jiankangbaogao):
            try:
                clicknum=int(data[0].get("clicknum",0))+1
            except:
                clicknum=0+1
            click_dict={"id":int(id_),"clicknum":clicknum}
            ret=jiankangbaogao.updatebyparams(jiankangbaogao,jiankangbaogao,click_dict)
            if ret!=None:
                msg['code'] = crud_error_code
                msg['msg'] = ret
        return JsonResponse(msg)

def jiankangbaogao_detail(request,id_):
    '''
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}

        data =jiankangbaogao.getbyid(jiankangbaogao,jiankangbaogao, int(id_))
        if len(data)>0:
            msg['data']=data[0]
            if msg['data'].__contains__("reversetime"):
                if isinstance(msg['data']['reversetime'], datetime.datetime):
                    msg['data']['reversetime'] = msg['data']['reversetime'].strftime("%Y-%m-%d %H:%M:%S")
                else:
                    if msg['data']['reversetime'] != None:
                        reversetime = datetime.datetime.strptime(msg['data']['reversetime'], '%Y-%m-%d %H:%M:%S')
                        msg['data']['reversetime'] = reversetime.strftime("%Y-%m-%d %H:%M:%S")

        #浏览点击次数
        try:
            __browseClick__= jiankangbaogao.__browseClick__
        except:
            __browseClick__=None

        if __browseClick__=="是"   and  "clicknum"  in jiankangbaogao.getallcolumn(jiankangbaogao,jiankangbaogao):
            try:
                clicknum=int(data[0].get("clicknum",0))+1
            except:
                clicknum=0+1
            click_dict={"id":int(id_),"clicknum":clicknum}

            ret=jiankangbaogao.updatebyparams(jiankangbaogao,jiankangbaogao,click_dict)
            if ret!=None:
                msg['code'] = crud_error_code
                msg['msg'] = ret
        return JsonResponse(msg)

def jiankangbaogao_update(request):
    '''
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
        req_dict = request.session.get("req_dict")
        if 'clicktime' in req_dict.keys() and req_dict['clicktime']=="None":
            del req_dict['clicktime']
        if req_dict.get("mima") and "mima" not in jiankangbaogao.getallcolumn(jiankangbaogao,jiankangbaogao) :
            del req_dict["mima"]
        if req_dict.get("password") and "password" not in jiankangbaogao.getallcolumn(jiankangbaogao,jiankangbaogao) :
            del req_dict["password"]
        try:
            del req_dict["clicknum"]
        except:
            pass


        error = jiankangbaogao.updatebyparams(jiankangbaogao, jiankangbaogao, req_dict)
        if error!=None:
            msg['code'] = crud_error_code
            msg['msg'] = error

        return JsonResponse(msg)


def jiankangbaogao_delete(request):
    '''
    批量删除
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
        req_dict = request.session.get("req_dict")

        error=jiankangbaogao.deletes(jiankangbaogao,
            jiankangbaogao,
             req_dict.get("ids")
        )
        if error!=None:
            msg['code'] = crud_error_code
            msg['msg'] = error
        return JsonResponse(msg)


def jiankangbaogao_vote(request,id_):
    '''
    浏览点击次数(表属性[browseClick:是/否],点击字段(clicknum),调用info/detail接口的时候后端自动+1)、投票功能(表属性[vote:是/否],投票字段(votenum),调用vote接口后端votenum+1)
统计商品或新闻的点击次数;提供新闻的投票功能
    '''
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": mes.normal_code}


        data= jiankangbaogao.getbyid(jiankangbaogao, jiankangbaogao, int(id_))
        for i in data:
            votenum=i.get('votenum')
            if votenum!=None:
                params={"id":int(id_),"votenum":votenum+1}
                error=jiankangbaogao.updatebyparams(jiankangbaogao,jiankangbaogao,params)
                if error!=None:
                    msg['code'] = crud_error_code
                    msg['msg'] = error
        return JsonResponse(msg)

def jiankangbaogao_importExcel(request):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": {}}

        excel_file = request.FILES.get("file", "")
        file_type = excel_file.name.split('.')[1]
        
        if file_type in ['xlsx', 'xls']:
            data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())
            table = data.sheets()[0]
            rows = table.nrows
            
            try:
                for row in range(1, rows):
                    row_values = table.row_values(row)
                    req_dict = {}
                    jiankangbaogao.createbyreq(jiankangbaogao, jiankangbaogao, req_dict)
                    
            except:
                pass
                
        else:
            msg = {
                "msg": "文件类型错误",
                "code": 500
            }
                
        return JsonResponse(msg)

def jiankangbaogao_autoSort2(request):
    return JsonResponse({"code": 0, "msg": '',  "data":{}})

# (按值统计)时间统计类型
def jiankangbaogao_value(request, xColumnName, yColumnName, timeStatType):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": {}}
        
        where = ' where 1 = 1 '
        token = request.META.get('HTTP_TOKEN')
        decode_str = eval(base64.b64decode(token).decode("utf8"))
        if decode_str['tablename'] == 'laoren':
            where = where + " and laorenzhanghao ='{0}' ".format(decode_str['params']['laorenzhanghao'])
        sql = ''
        if timeStatType == '日':
            sql = "SELECT DATE_FORMAT({0}, '%Y-%m-%d') {0}, sum({1}) total FROM jiankangbaogao {2} GROUP BY DATE_FORMAT({0}, '%Y-%m-%d')".format(xColumnName, yColumnName, where, '%Y-%m-%d')

        if timeStatType == '月':
            sql = "SELECT DATE_FORMAT({0}, '%Y-%m') {0}, sum({1}) total FROM jiankangbaogao {2} GROUP BY DATE_FORMAT({0}, '%Y-%m')".format(xColumnName, yColumnName, where, '%Y-%m')

        if timeStatType == '年':
            sql = "SELECT DATE_FORMAT({0}, '%Y') {0}, sum({1}) total FROM jiankangbaogao {2} GROUP BY DATE_FORMAT({0}, '%Y')".format(xColumnName, yColumnName, where, '%Y')

        L = []
        cursor = connection.cursor()
        cursor.execute(sql)
        desc = cursor.description
        data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] 
        for online_dict in data_dict:
            for key in online_dict:
                if 'datetime.datetime' in str(type(online_dict[key])):
                    online_dict[key] = online_dict[key].strftime(
                        "%Y-%m-%d %H:%M:%S")
                else:
                    pass
            L.append(online_dict)
        msg['data'] = L
        return JsonResponse(msg)

# 按值统计
def jiankangbaogao_o_value(request, xColumnName, yColumnName):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": {}}
        
        where = ' where 1 = 1 '
        token = request.META.get('HTTP_TOKEN')
        decode_str = eval(base64.b64decode(token).decode("utf8"))
        if decode_str['tablename'] == 'laoren':
            where = where + " and laorenzhanghao ='{0}' ".format(decode_str['params']['laorenzhanghao'])
        
        sql = "SELECT {0}, sum({1}) AS total FROM jiankangbaogao {2} GROUP BY {0} LIMIT 10".format(xColumnName, yColumnName, where)
        L = []
        cursor = connection.cursor()
        cursor.execute(sql)
        desc = cursor.description
        data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] 
        for online_dict in data_dict:
            for key in online_dict:
                if 'datetime.datetime' in str(type(online_dict[key])):
                    online_dict[key] = online_dict[key].strftime(
                        "%Y-%m-%d %H:%M:%S")
                else:
                    pass
            L.append(online_dict)
        msg['data'] = L
        return JsonResponse(msg)

# (按值统计)时间统计类型(多)
def jiankangbaogao_valueMul(request, xColumnName, timeStatType):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": []}

        req_dict = request.session.get("req_dict")

        where = ' where 1 = 1 '
        token = request.META.get('HTTP_TOKEN')
        decode_str = eval(base64.b64decode(token).decode("utf8"))
        if decode_str['tablename'] == 'laoren':
            where = where + " and laorenzhanghao ='{0}' ".format(decode_str['params']['laorenzhanghao'])

        for item in req_dict['yColumnNameMul'].split(','):
            sql = ''
            if timeStatType == '日':
                sql = "SELECT DATE_FORMAT({0}, '%Y-%m-%d') {0}, sum({1}) total FROM jiankangbaogao {2} GROUP BY DATE_FORMAT({0}, '%Y-%m-%d') LIMIT 10".format(xColumnName, item, where, '%Y-%m-%d')

            if timeStatType == '月':
                sql = "SELECT DATE_FORMAT({0}, '%Y-%m') {0}, sum({1}) total FROM jiankangbaogao {2} GROUP BY DATE_FORMAT({0}, '%Y-%m') LIMIT 10".format(xColumnName, item, where, '%Y-%m')

            if timeStatType == '年':
                sql = "SELECT DATE_FORMAT({0}, '%Y') {0}, sum({1}) total FROM jiankangbaogao {2} GROUP BY DATE_FORMAT({0}, '%Y') LIMIT 10".format(xColumnName, item, where, '%Y')

            L = []
            cursor = connection.cursor()
            cursor.execute(sql)
            desc = cursor.description
            data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] 
            for online_dict in data_dict:
                for key in online_dict:
                    if 'datetime.datetime' in str(type(online_dict[key])):
                        online_dict[key] = online_dict[key].strftime(
                            "%Y-%m-%d %H:%M:%S")
                    else:
                        pass
                L.append(online_dict)
            msg['data'].append(L)
        return JsonResponse(msg)

# (按值统计(多))
def jiankangbaogao_o_valueMul(request, xColumnName):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": []}

        req_dict = request.session.get("req_dict")
        
        where = ' where 1 = 1 '
        token = request.META.get('HTTP_TOKEN')
        decode_str = eval(base64.b64decode(token).decode("utf8"))
        if decode_str['tablename'] == 'laoren':
            where = where + " and laorenzhanghao ='{0}' ".format(decode_str['params']['laorenzhanghao'])

        for item in req_dict['yColumnNameMul'].split(','):
            sql = "SELECT {0}, sum({1}) AS total FROM jiankangbaogao {2} GROUP BY {0} LIMIT 10".format(xColumnName, item, where)
            L = []
            cursor = connection.cursor()
            cursor.execute(sql)
            desc = cursor.description
            data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] 
            for online_dict in data_dict:
                for key in online_dict:
                    if 'datetime.datetime' in str(type(online_dict[key])):
                        online_dict[key] = online_dict[key].strftime(
                            "%Y-%m-%d %H:%M:%S")
                    else:
                        pass
                L.append(online_dict)
            msg['data'].append(L)

        return JsonResponse(msg)




def jiankangbaogao_group(request, columnName):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": {}}
        
        where = ' where 1 = 1 '
        token = request.META.get('HTTP_TOKEN')
        decode_str = eval(base64.b64decode(token).decode("utf8"))
        if decode_str['tablename'] == 'laoren':
            where = where + " and laorenzhanghao ='{0}' ".format(decode_str['params']['laorenzhanghao'])

        sql = "SELECT COUNT(*) AS total, " + columnName + " FROM jiankangbaogao " + where + " GROUP BY " + columnName

        L = []
        cursor = connection.cursor()
        cursor.execute(sql)
        desc = cursor.description
        data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] 
        for online_dict in data_dict:
            for key in online_dict:
                if 'datetime.datetime' in str(type(online_dict[key])):
                    online_dict[key] = online_dict[key].strftime("%Y-%m-%d")
                else:
                    pass
            L.append(online_dict)
        msg['data'] = L
        return JsonResponse(msg)

💕💕作者:计算机源码社

💕💕个人简介:本人 八年开发经验,擅长Java、Python、PHP、.NET、Node.js、Android、微信小程序、爬虫、大数据、机器学习等,大家有这一块的问题可以一起交流!

💕💕学习资料、程序开发、技术解答、文档报告

💕💕如需要源码,可以扫取文章下方二维码联系咨询

相关推荐
vener_14 小时前
LuckySheet协同编辑后端示例(Django+Channel,Websocket通信)
javascript·后端·python·websocket·django·luckysheet
mariokkm15 小时前
Django一分钟:django中收集关联对象关联数据的方法
android·django·sqlite
qq_q99225027720 小时前
django宠物服务管理系统
数据库·django·宠物
无忧无虑Coding1 天前
pyinstall 打包Django程序
后端·python·django
qq_q9922502771 天前
django基于python 语言的酒店推荐系统
后端·python·django
codists1 天前
《Django 5 By Example》阅读笔记:p679-p765
python·django
冷琴19961 天前
基于python+django+vue.js开发的停车管理系统
vue.js·python·django
highfish9202 天前
Django实现智能问答助手-数据库方式读取问题和答案
数据库·python·django
qq_q9922502772 天前
django基于Hadoop 的国产电影数据分析与可视化
hadoop·数据分析·django
qq_q9922502772 天前
django基于Django的二手电子设备交易平台设计与开发
数据库·django·sqlite