首页 > 编程语言 >基于Python实现校园爱心帮扶平台

基于Python实现校园爱心帮扶平台

时间:2024-08-30 09:24:50浏览次数:10  
标签:__ code Python request 校园 dict msg discusswupinyimai 帮扶

作者简介:Java领域优质创作者、CSDN博客专家 、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验,被多个学校常年聘为校外企业导师,指导学生毕业设计并参与学生毕业答辩指导,有较为丰富的相关经验。期待与各位高校教师、企业讲师以及同行交流合作

主要内容:Java项目、Python项目、前端项目、PHP、ASP.NET、人工智能与大数据、单片机开发、物联网设计与开发设计、简历模板、学习资料、面试题库、技术互助、就业指导等

业务范围:免费功能设计、开题报告、任务书、中期检查PPT、系统功能实现、代码编写、论文编写和辅导、论文降重、长期答辩答疑辅导、腾讯会议一对一专业讲解辅导答辩、模拟答辩演练、和理解代码逻辑思路等

收藏点赞不迷路  关注作者有好处

文末获取源码 

项目编号:BS-Python-040

一,环境介绍

语言环境:Python3.8

数据库:Mysql: mysql5.7

WEB框架:Django

开发工具:IDEA或PyCharm

二,项目简介

基于Python实现一个校园爱心帮扶平台,旨在构建一个促进校园内学生间互助与爱心传递的在线系统。该平台将充分利用Python的灵活性、丰富的库资源以及高效的数据库管理能力,为学生提供一个便捷、安全、匿名的求助与援助渠道。

系统核心功能包括:

  1. 用户注册与登录:通过邮箱或学号注册成为平台用户,确保信息的真实性与隐私保护。登录系统后,用户可根据自身需求进行求助或提供帮助。

  2. 发布求助信息:学生可以在平台上发布自己的学习、生活或心理等方面的求助信息,系统支持文字、图片等多种形式,便于详细描述问题。

  3. 浏览与筛选帮助需求:其他用户可以浏览平台上的所有求助信息,并通过关键词、类别等方式筛选感兴趣的帮助需求,从而找到最适合自己帮助的对象。

  4. 匿名援助:为保护双方隐私,系统支持匿名交流。用户可以在不透露个人信息的情况下进行互动,增加参与的安全感。

  5. 进度跟踪与反馈:援助过程中,双方可记录并更新援助进度,平台提供反馈机制,让求助者可以表达对援助的满意度,同时也为援助者提供正向激励。

  6. 数据分析与展示:系统后台将收集用户行为数据,进行统计分析,以图表形式展示校园内各类求助需求的分布情况,为学校管理部门提供决策支持。

通过这一平台,不仅能够有效缓解学生在校园生活中遇到的各种困难,还能增进学生之间的交流与理解,共同营造一个充满爱心与温暖的校园环境。

三,系统展示

四,核心代码展示

#coding:utf-8
__author__ = "ila"
import base64, copy, logging, os, time, xlrd
from django.http import JsonResponse
from django.apps import apps
from django.db.models.aggregates import Count,Sum
from .models import discusswupinyimai
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

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


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

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

        datas = discusswupinyimai.getbyparams(discusswupinyimai, discusswupinyimai, req_dict)
        if not datas:
            msg['code'] = password_error_code
            msg['msg'] = mes.password_error_code
            return JsonResponse(msg)
        try:
            __sfsh__= discusswupinyimai.__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, discusswupinyimai, req_dict)


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

        return JsonResponse(msg)


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

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

        columns=  discusswupinyimai.getallcolumn( discusswupinyimai, discusswupinyimai)

        try:
            __loginUserColumn__= discusswupinyimai.__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'
        recordsParam = {}
        recordsParam[username_str] = req_dict.get("username")
        records=discusswupinyimai.getbyparams(discusswupinyimai, discusswupinyimai, recordsParam)
        if len(records)<1:
            msg['code'] = 400
            msg['msg'] = '用户不存在'
            return JsonResponse(msg)

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



def discusswupinyimai_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']  = discusswupinyimai.getbyparams(discusswupinyimai, discusswupinyimai, req_dict)[0]

        return JsonResponse(msg)


def discusswupinyimai_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=discusswupinyimai.getbyparams(discusswupinyimai, discusswupinyimai, req_dict)
        if len(data)>0:
            msg['data']  = data[0]
        else:
            msg['data']  = {}
        return JsonResponse(msg)

def discusswupinyimai_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")

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

        #当前登录用户所在表
        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__=discusswupinyimai.__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__=discusswupinyimai.__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 'discusswupinyimai' != 'forum':
            if req_dict.get("userid") and 'discusswupinyimai' != 'chat':
                del req_dict["userid"]

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

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

        if __authTables__!=None and  __authTables__!={}:
            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

        q = Q()

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

        return JsonResponse(msg)

def discusswupinyimai_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 discusswupinyimai.getallcolumn(discusswupinyimai,discusswupinyimai):
            req_dict['sort']='clicknum'
        else:
            req_dict['sort']='clicktime'
        req_dict['order']='desc'
        msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
        msg['data']['pageSize']  = discusswupinyimai.page(discusswupinyimai,discusswupinyimai, req_dict)

        return JsonResponse(msg)


def discusswupinyimai_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=  discusswupinyimai.getallcolumn( discusswupinyimai, discusswupinyimai)
        #表属性[foreEndList]前台list:和后台默认的list列表页相似,只是摆在前台,否:指没有此页,是:表示有此页(不需要登陆即可查看),前要登:表示有此页且需要登陆后才能查看
        try:
            __foreEndList__=discusswupinyimai.__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__=discusswupinyimai.__foreEndListAuth__
        except:
            __foreEndListAuth__=None


        #authSeparate
        try:
            __authSeparate__=discusswupinyimai.__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__=discusswupinyimai.__authTables__
        except:
            __authTables__=None

        if __authTables__!=None and  __authTables__!={} and __foreEndListAuth__=="是":
            try:
                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 discusswupinyimai.__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']  = discusswupinyimai.page(discusswupinyimai, discusswupinyimai, req_dict, request, q)

        return JsonResponse(msg)

def discusswupinyimai_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=  discusswupinyimai.getallcolumn( discusswupinyimai, discusswupinyimai)
        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')


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

        return JsonResponse(msg)


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

        #获取全部列名
        columns=  discusswupinyimai.getallcolumn( discusswupinyimai, discusswupinyimai)
        try:
            __authSeparate__=discusswupinyimai.__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__=discusswupinyimai.__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")

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

def discusswupinyimai_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=discusswupinyimai.getbyid(discusswupinyimai,discusswupinyimai,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 = discusswupinyimai.updatebyparams(discusswupinyimai,discusswupinyimai, update_dict)
        if error!=None:
            msg['code'] = crud_error_code
            msg['msg'] = error
        return JsonResponse(msg)


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

        data = discusswupinyimai.getbyid(discusswupinyimai,discusswupinyimai, int(id_))
        if len(data)>0:
            msg['data']=data[0]
            if msg['data'].__contains__("reversetime"):
                msg['data']['reversetime'] = msg['data']['reversetime'].strftime("%Y-%m-%d %H:%M:%S")
        #浏览点击次数
        try:
            __browseClick__= discusswupinyimai.__browseClick__
        except:
            __browseClick__=None

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

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

        data =discusswupinyimai.getbyid(discusswupinyimai,discusswupinyimai, int(id_))
        if len(data)>0:
            msg['data']=data[0]
            if msg['data'].__contains__("reversetime"):
                msg['data']['reversetime'] = msg['data']['reversetime'].strftime("%Y-%m-%d %H:%M:%S")

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

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

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


def discusswupinyimai_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 req_dict.get("mima") and req_dict.get("password"):
            if "mima" not  in discusswupinyimai.getallcolumn(discusswupinyimai,discusswupinyimai) :
                del req_dict["mima"]
            if  "password" not  in discusswupinyimai.getallcolumn(discusswupinyimai,discusswupinyimai) :
                del req_dict["password"]
        try:
            del req_dict["clicknum"]
        except:
            pass


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

        return JsonResponse(msg)


def discusswupinyimai_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=discusswupinyimai.deletes(discusswupinyimai,
            discusswupinyimai,
             req_dict.get("ids")
        )
        if error!=None:
            msg['code'] = crud_error_code
            msg['msg'] = error
        return JsonResponse(msg)


def discusswupinyimai_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= discusswupinyimai.getbyid(discusswupinyimai, discusswupinyimai, int(id_))
        for i in data:
            votenum=i.get('votenum')
            if votenum!=None:
                params={"id":int(id_),"votenum":votenum+1}
                error=discusswupinyimai.updatebyparams(discusswupinyimai,discusswupinyimai,params)
                if error!=None:
                    msg['code'] = crud_error_code
                    msg['msg'] = error
        return JsonResponse(msg)

def discusswupinyimai_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 = {}
                    discusswupinyimai.createbyreq(discusswupinyimai, discusswupinyimai, req_dict)
                    
            except:
                pass
                
        else:
            msg.code = 500
            msg.msg = "文件类型错误"
                
        return JsonResponse(msg)

def discusswupinyimai_sendemail(request):
    if request.method in ["POST", "GET"]:
        req_dict = request.session.get("req_dict")

        code = random.sample(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 4)
        to = []
        to.append(req_dict['email'])

        send_mail('用户注册', '您的注册验证码是【'+''.join(code)+'】,请不要把验证码泄漏给其他人,如非本人请勿操作。', '[email protected]', to, fail_silently = False)

        cursor = connection.cursor()
        cursor.execute("insert into emailregistercode(email,role,code) values('"+req_dict['email']+"','用户','"+''.join(code)+"')")

        msg = {
            "msg": "发送成功",
            "code": 0
        }

        return JsonResponse(msg)

# 推荐算法接口
def discusswupinyimai_autoSort2(request):
    
    if request.method in ["POST", "GET"]:
        req_dict = request.session.get("req_dict")
        cursor = connection.cursor()
        leixing = set()
        try:
            cursor.execute("select inteltype from storeup where userid = %d"%(request.session.get("params").get("id"))+" and tablename = 'discusswupinyimai' order by addtime desc")
            rows = cursor.fetchall()
            for row in rows:
                for item in row:
                    if item != None:
                        leixing.add(item)
        except:
            leixing = set()
        
        L = []
        cursor.execute("select * from discusswupinyimai where $intelRecomColumn in ('%s"%("','").join(leixing)+"') union all select * from discusswupinyimai where $intelRecomColumn not in('%s"%("','").join(leixing)+"')")
        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)


        return JsonResponse({"code": 0, "msg": '',  "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":5,"list": L[0:6]}})

def discusswupinyimai_value(request, xColumnName, yColumnName, timeStatType):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": {}}
        
        where = ' where 1 = 1 '
        sql = ''
        if timeStatType == '日':
            sql = "SELECT DATE_FORMAT({0}, '%Y-%m-%d') {0}, sum({1}) total FROM discusswupinyimai {2} GROUP BY DATE_FORMAT({0}, '%Y-%m-%d') LIMIT 10".format(xColumnName, yColumnName, where, '%Y-%m-%d')

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

        if timeStatType == '年':
            sql = "SELECT DATE_FORMAT({0}, '%Y') {0}, sum({1}) total FROM discusswupinyimai {2} GROUP BY DATE_FORMAT({0}, '%Y') LIMIT 10".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 discusswupinyimai_o_value(request, xColumnName, yColumnName):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": {}}
        
        where = ' where 1 = 1 '
        
        sql = "SELECT {0}, sum({1}) AS total FROM discusswupinyimai {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 discusswupinyimai_group(request, columnName):
    if request.method in ["POST", "GET"]:
        msg = {"code": normal_code, "msg": "成功", "data": {}}
        
        where = ' where 1 = 1 '

        sql = "SELECT COUNT(*) AS total, " + columnName + " FROM discusswupinyimai " + where + " GROUP BY " + columnName + " LIMIT 10" 
        
        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)


五,相关作品展示

基于Java开发、Python开发、PHP开发、C#开发等相关语言开发的实战项目

基于Nodejs、Vue等前端技术开发的前端实战项目

基于微信小程序和安卓APP应用开发的相关作品

基于51单片机等嵌入式物联网开发应用

基于各类算法实现的AI智能应用

基于大数据实现的各类数据管理和推荐系统

 

 

标签:__,code,Python,request,校园,dict,msg,discusswupinyimai,帮扶
From: https://blog.csdn.net/znzbs/article/details/141581611

相关文章

  • Python--异常的分类
    异常是Python编程中常见的错误类型,帮助开发者识别和调试代码中的问题。以下是对出现的常见异常的详细阐述:IndexError(索引超出序列的范围)当尝试访问一个序列(如列表、元组等)中不存在的索引时,会引发此异常。例如,访问一个长度为5的列表的第10个元素时就会出现IndexErr......
  • 快速排序python实现
    defquick_sort(arr,left,right):origin_left=leftorigin_right=rightpivot_data=arr[left]#枢轴上的值(基准值),就是开始用来比较的值,一般是随机选择一个位置,这儿选择最左边的值#blank_pos=left#最左边的值已经复制到pivot中了,所以这块......
  • 使用 python 升级OTA程序
    依赖文件pymodbus==3.6.3pyserial==3.5importbinasciiimportmathimporttimeimportserialfrompymodbus.clientimportModbusSerialClientasModbusClientimportstruct##设备串口配置#port='/dev/cu.usbserial-1130'#根据实际情况修改为实际串口号#baudra......
  • Python中的“for循环”:探索其无限潜力
    引言for循环是任何Python程序员工具箱中的必备技能之一。无论是在处理数据时需要遍历数组,还是在编写Web应用时循环处理请求,亦或是进行复杂的算法实现,for循环都能派上大用场。通过掌握for循环的不同用法,我们可以更高效地解决问题,写出更加优雅且高效的代码。基础语法介绍核心概念......
  • Python中的`while`循环:探索无限可能
    引言while循环允许我们重复执行一段代码块,直到指定条件不再满足为止。这种机制非常适合处理那些不确定具体重复次数的任务场景,比如读取文件直到末尾、定时任务执行等。掌握好while循环,不仅能让你的代码更加高效、简洁,还能帮助你在面对复杂问题时找到更优的解决方案。基础语法介绍......
  • Python实现图片的拼接
    Python实现图片的拼接Python中有多种方法可以实现图片拼接,下面是一个使用Pillow库的示例:首先,你需要安装Pillow库:pipinstallpillow然后,可以使用以下代码实现图片拼接:fromPILimportImage#读取两张图片img1=Image.open('image1.jpg')img2=Image.open('image2.jpg'......
  • 校园小情书微信小程序源码 | 社区小程序前后端开源 | 校园表白墙交友小程序
    校园小情书微信小程序源码 | 社区小程序前后端开源 | 校园表白墙交友小程序【校园小情书】——用代码编织的青春告白在这个数字化的时代,我们的情感表达也逐渐从纸笔转向了屏幕。小红书上的小伙伴们,你们是否也曾幻想过,在校园的某个角落,有一个属于自己的表白墙,可以匿名或实......
  • Python的requests库详细介绍
    Pythonrequests库是一个用于发送HTTP请求的简单而强大的库,它可以让你轻松地在Python中处理HTTP请求。这个库是Python中处理HTTP请求的标准工具,因其简洁的API和强大的功能而广受欢迎。1.安装requestspipinstallrequests2.基本用法2.1导入库importr......
  • Python深度学习股价预测、量化交易策略:LSTM、GRU深度门控循环神经网络|附代码数据
    全文链接:https://tecdat.cn/?p=37539原文出处:拓端数据部落公众号 分析师:ShuoZhang本文以上证综指近22年的日交易数据为样本,构建深度门控循环神经网络模型,从股价预测和制定交易策略两方面入手,量化循环神经网络在股票预测以及交易策略中的效果,结合一个Python深度学习股价预测......
  • python实现RC4加解密算法
    目录RC4算法简介RC4算法的加密和解密流程RC4算法的Python实现代码解释RC4算法的应用场景RC4的安全性分析总结RC4(RivestCipher4)是一种流加密算法,由RonRivest于1987年设计。RC4广泛应用于各种加密协议,如SSL/TLS和WEP/WPA等。RC4算法因其简单、高效的特点受到广泛关......