目录
一、整体目录(示范):
文档含项目技术介绍、E-R图、数据字典、项目功能介绍与截图等
二、运行截图
三、代码部分(示范):
四、数据库表(示范):
数据库表有注释,可以导出数据字典及更新数据库时间,欢迎交流学习
五、主要技术介绍:
六、项目调试学习(点击查看)
七、项目交流
文档含项目技术介绍、E-R图、数据字典、项目功能介绍与截图等
注册较验代码:
// 注册
async register() {
if((!this.ruleForm.yonghuzhanghao) && `yonghu` == this.tableName){
this.$utils.msg(`用户账号不能为空`);
return
}
if(`yonghu` == this.tableName && (this.ruleForm.yonghuzhanghao.length<8)){
this.$utils.msg(`用户账号长度不能小于8`);
return
}
if(`yonghu` == this.tableName && (this.ruleForm.yonghuzhanghao.length>12)){
this.$utils.msg(`用户账号长度不能大于12`);
return
}
if((!this.ruleForm.mima) && `yonghu` == this.tableName){
this.$utils.msg(`密码不能为空`);
return
}
if(`yonghu` == this.tableName && (this.ruleForm.mima!=this.ruleForm.mima2)){
this.$utils.msg(`两次密码输入不一致`);
return
}
if((!this.ruleForm.yonghuxingming) && `yonghu` == this.tableName){
this.$utils.msg(`用户姓名不能为空`);
return
}
if(`yonghu` == this.tableName && this.ruleForm.nianling&&(!this.$validate.isIntNumer(this.ruleForm.nianling))){
this.$utils.msg(`年龄应输入整数`);
return
}
if((!this.ruleForm.schoolname) && `yonghu` == this.tableName){
this.$utils.msg(`学校名称不能为空`);
return
}
if(`yonghu` == this.tableName && this.ruleForm.shouji&&(!this.$validate.isMobile(this.ruleForm.shouji))){
this.$utils.msg(`手机应输入手机格式`);
return
}
if(`yonghu` == this.tableName && this.ruleForm.youxiang&&(!this.$validate.isEmail(this.ruleForm.youxiang))){
this.$utils.msg(`邮箱应输入邮件格式`);
return
}
await this.$api.register(`${this.tableName}`, this.ruleForm, this.emailcode);
this.$utils.msgBack('注册成功');;
}
}
}
推荐算法代码
//智能推荐商品业务步骤
1.获取当前用户信息
2.判断当前是否有收藏信息
3.如有收藏信息按收藏推荐信息推荐,无推荐信息默认按点击次数
//================以下是相关类和方法==============
//商品信息后端接口类
com.controller.ShangpinxinxiController
/**
* 商品信息前端智能排序
*/
@IgnoreAuth
@RequestMapping("/autoSort")
public R autoSort(@RequestParam Map params,ShangpinxinxiEntity shangpinxinxi, HttpServletRequest request,String pre){
EntityWrapper ew = new EntityWrapper();
Map newMap = new HashMap();
Map param = new HashMap();
boolean flag = false;
String isRecommend =(String) params.get("isRecommend");
if("1".equals(isRecommend)){ //是否推荐
String userId = (String) params.get("userId");
YonghuEntity user = yonghuService.selectById(Long.valueOf(userId));
params.remove("isRecommend");
params.remove("userId");
StringBuffer refIds = new StringBuffer();
List storeupList = storeupService.selectListView(new EntityWrapper().eq("userid",userId));
if(storeupList!=null && storeupList.size()>0){
for(StoreupView storeupView: storeupList){
refIds.append(storeupView.getRefid()+",");
}
flag =true;
ew.in("id",refIds.toString());
}
}
Iterator> it = param.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
String key = entry.getKey();
String newKey = entry.getKey();
if (pre.endsWith(".")) {
newMap.put(pre + newKey, entry.getValue());
} else if (StringUtils.isEmpty(pre)) {
newMap.put(newKey, entry.getValue());
} else {
newMap.put(pre + "." + newKey, entry.getValue());
}
}
params.put("sort", "clicknum");
params.put("order", "desc");
PageUtils page = shangpinxinxiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, shangpinxinxi), params), params));
return R.ok().put("data", page);
}
//收藏表后端接口
com.controller.StoreupController
/**
* 收藏表后端保存方法
*/
@RequestMapping("/save")
public R save(@RequestBody StoreupEntity storeup, HttpServletRequest request){
storeup.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
//ValidatorUtils.validateEntity(storeup);
storeup.setUserid((Long)request.getSession().getAttribute("userId"));
storeupService.insert(storeup);
return R.ok();
}
/**
* 收藏表删除方法
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
storeupService.deleteBatchIds(Arrays.asList(ids));
return R.ok();
}
#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 zuixindianying
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 alipay import AliPayConfig, AliPay
from django.conf import settings
from django.shortcuts import redirect
def zuixindianying_register(request):
if request.method in ["POST", "GET"]:
msg = {'code': normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
error = zuixindianying.createbyreq(zuixindianying, zuixindianying, req_dict)
if error != None:
msg['code'] = crud_error_code
msg['msg'] = "用户已存在,请勿重复注册!"
return JsonResponse(msg)
def zuixindianying_login(request):
if request.method in ["POST", "GET"]:
msg = {'code': normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
datas = zuixindianying.getbyparams(zuixindianying, zuixindianying, req_dict)
if not datas:
msg['code'] = password_error_code
msg['msg'] = mes.password_error_code
return JsonResponse(msg)
try:
__sfsh__= zuixindianying.__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, zuixindianying, req_dict)
def zuixindianying_logout(request):
if request.method in ["POST", "GET"]:
msg = {
"msg": "登出成功",
"code": 0
}
return JsonResponse(msg)
def zuixindianying_resetPass(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
columns= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
try:
__loginUserColumn__= zuixindianying.__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'
eval('''zuixindianying.objects.filter({}='{}').update({}='{}')'''.format(username_str,username,password_str,init_pwd))
return JsonResponse(msg)
def zuixindianying_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'] = zuixindianying.getbyparams(zuixindianying, zuixindianying, req_dict)[0]
return JsonResponse(msg)
def zuixindianying_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=zuixindianying.getbyparams(zuixindianying, zuixindianying, req_dict)
if len(data)>0:
msg['data'] = data[0]
else:
msg['data'] = {}
return JsonResponse(msg)
def zuixindianying_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= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
#当前登录用户所在表
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__=zuixindianying.__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__=zuixindianying.__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__ == "是":
if req_dict.get("userid"):
del req_dict["userid"]
else:
#非管理员权限的表,判断当前表字段名是否有userid
if tablename!="users" and 'zuixindianying'[:7]!='discuss'and "userid" in zuixindianying.getallcolumn(zuixindianying,zuixindianying):
req_dict["userid"] = request.session.get("params").get("id")
#当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
try:
__authTables__=zuixindianying.__authTables__
except:
__authTables__=None
if __authTables__!=None and __authTables__!={}:
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)
break
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] =zuixindianying.page(zuixindianying, zuixindianying, req_dict, request)
return JsonResponse(msg)
def zuixindianying_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 zuixindianying.getallcolumn(zuixindianying,zuixindianying):
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'] = zuixindianying.page(zuixindianying,zuixindianying, req_dict)
return JsonResponse(msg)
def zuixindianying_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= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
#表属性[foreEndList]前台list:和后台默认的list列表页相似,只是摆在前台,否:指没有此页,是:表示有此页(不需要登陆即可查看),前要登:表示有此页且需要登陆后才能查看
try:
__foreEndList__=zuixindianying.__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__=zuixindianying.__foreEndListAuth__
except:
__foreEndListAuth__=None
#authSeparate
try:
__authSeparate__=zuixindianying.__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"]
else:
#非管理员权限的表,判断当前表字段名是否有userid
if "userid" in columns:
try:
# 本接口可以匿名访问,所以try判断是否为匿名
req_dict['userid']=request.session.get("params").get("id")
except:
pass
#当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
try:
__authTables__=zuixindianying.__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)
break
if zuixindianying.__tablename__[:7]=="discuss":
try:
del req_dict['userid']
except:
pass
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] = zuixindianying.page(zuixindianying, zuixindianying, req_dict)
return JsonResponse(msg)
def zuixindianying_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= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
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= zuixindianying.createbyreq(zuixindianying,zuixindianying, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def zuixindianying_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= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
try:
__authSeparate__=zuixindianying.__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__=zuixindianying.__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= zuixindianying.createbyreq(zuixindianying,zuixindianying, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def zuixindianying_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=zuixindianying.getbyid(zuixindianying,zuixindianying,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 = zuixindianying.updatebyparams(zuixindianying,zuixindianying, update_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def zuixindianying_info(request,id_):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
data = zuixindianying.getbyid(zuixindianying,zuixindianying, int(id_))
if len(data)>0:
msg['data']=data[0]
#浏览点击次数
try:
__browseClick__= zuixindianying.__browseClick__
except:
__browseClick__=None
if __browseClick__=="是" and "clicknum" in zuixindianying.getallcolumn(zuixindianying,zuixindianying):
try:
clicknum=int(data[0].get("clicknum",0))+1
except:
clicknum=0+1
click_dict={"id":int(id_),"clicknum":clicknum}
ret=zuixindianying.updatebyparams(zuixindianying,zuixindianying,click_dict)
if ret!=None:
msg['code'] = crud_error_code
msg['msg'] = ret
return JsonResponse(msg)
def zuixindianying_detail(request,id_):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
data =zuixindianying.getbyid(zuixindianying,zuixindianying, int(id_))
if len(data)>0:
msg['data']=data[0]
#浏览点击次数
try:
__browseClick__= zuixindianying.__browseClick__
except:
__browseClick__=None
if __browseClick__=="是" and "clicknum" in zuixindianying.getallcolumn(zuixindianying,zuixindianying):
try:
clicknum=int(data[0].get("clicknum",0))+1
except:
clicknum=0+1
click_dict={"id":int(id_),"clicknum":clicknum}
ret=zuixindianying.updatebyparams(zuixindianying,zuixindianying,click_dict)
if ret!=None:
msg['code'] = crud_error_code
msg['msg'] = retfo
return JsonResponse(msg)
def zuixindianying_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 zuixindianying.getallcolumn(zuixindianying,zuixindianying) :
del req_dict["mima"]
if "password" not in zuixindianying.getallcolumn(zuixindianying,zuixindianying) :
del req_dict["password"]
try:
del req_dict["clicknum"]
except:
pass
error = zuixindianying.updatebyparams(zuixindianying, zuixindianying, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def zuixindianying_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=zuixindianying.deletes(zuixindianying,
zuixindianying,
req_dict.get("ids")
)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def zuixindianying_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= zuixindianying.getbyid(zuixindianying, zuixindianying, int(id_))
for i in data:
votenum=i.get('votenum')
if votenum!=None:
params={"id":int(id_),"votenum":votenum+1}
error=zuixindianying.updatebyparams(zuixindianying,zuixindianying,params)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def zuixindianying_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 = {}
zuixindianying.createbyreq(zuixindianying, zuixindianying, req_dict)
except:
pass
else:
msg.code = 500
msg.msg = "文件类型错误"
return JsonResponse(msg)
def zuixindianying_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 zuixindianying_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 = 'zuixindianying' order by addtime desc")
rows = cursor.fetchall()
for row in rows:
for item in row:
leixing.add(item)
except:
leixing = set()
L = []
cursor.execute("select * from zuixindianying where $intelRecomColumn in ('%s"%("','").join(leixing)+"') union all select * from zuixindianying 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 zuixindianying_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 zuixindianying {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 zuixindianying {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 zuixindianying {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 zuixindianying_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 zuixindianying {2} GROUP BY {0}".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 zuixindianying_alipay(request):
if request.method in ["POST", "GET"]:
alipay = AliPay(
appid=settings.ALIPAY_APP_ID,
app_notify_url=None,
app_private_key_string=settings.APP_PRIVATE_KEY_STRING,
alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,
sign_type=settings.ALIPAY_SIGN_TYPE,
debug=True,
config=AliPayConfig(timeout=15)
)
req_dict = request.session.get("req_dict")
order_string = alipay.api_alipay_trade_page_pay(
out_trade_no=req_dict['tradeno'],
total_amount=req_dict['totalamount'],
subject=req_dict['subject'],
return_url='http://localhost:8080/django3yz6u/zuixindianying/notify',
#notify_url=''
)
pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
pay_url = ''.format(pay_url)
return JsonResponse({'code': 0, "data": pay_url})
def zuixindianying_notify(request):
if request.method in ["POST", "GET"]:
req_dict = request.session.get("req_dict")
out_trade_no = req_dict['out_trade_no']
cursor = connection.cursor()
return redirect('http://localhost:8080/django3yz6u/admin/dist/index.html#/zuixindianying')
数据库表有注释,可以导出数据字典及更新数据库时间,欢迎交流学习
Django框架介绍:
Django是高水准的Python编程语言驱动的一个开源模型.视图,控制器风格的Web应用程序框架,它起源于开源社区。使用这种架构,程序员可以方便、快捷地创建高品质、易维护、数据库驱动的应用程序。这也正是OpenStack的Horizon组件采用这种架构进行设计的主要原因。另外,在Dj ango框架中,还包含许多功能强大的第三方插件,使得Django具有较强的可扩展性。Django 项目源自一个在线新闻 Web 站点,于 2005 年以开源的形式被释放出来。Django 框架的核心组件有:
用于创建模型的对象关系映射;
为最终用户设计较好的管理界面;
URL 设计;
设计者友好的模板语言;
缓存系统。
Django(发音:[`dʒæŋɡəʊ]) 是用python语言写的开源web开发框架(open source web framework),它鼓励快速开发,并遵循MVC设计。Django遵守BSD版权,初次发布于2005年7月, 并于2008年9月发布了第一个正式版本1.0 。
Django 根据比利时的爵士音乐家Django Reinhardt命名,他是一个吉普赛人,主要以演奏吉它为主,还演奏过小提琴等。
由于Django在近年来的迅速发展,应用越来越广泛,被著名IT开发杂志SD Times评选为2013 SD Times 100,位列“API、库和框架”分类第6位,被认为是该领域的佼佼者。
1.9 Django架构设计:
Django已经成为web开发者的首选框架,是一个遵循 MVC 设计模式的框架。MVC是Model、View、Controller三个单词的简写,分别代表模型、视图、控制器。Django其实也是一个MTV 的设计模式。MTV是Model、Template、View三个单词的简写,分别代表模型、模版、视图。但是在Django中,控制器接受用户输入的部分由框架自行处理,所以 Django 里更关注的是模型(Model)、模板(Template)和视图(Views),称为 MTV模式。它们各自的职责如下:
层次 |
职责 |
模型(Model),即数据存取层 |
处理与数据相关的所有事务: 如何存取、如何验证有效性、包含哪些行为以及数据之间的关系等。 |
模板(Template),即表现层 |
处理与表现相关的决定: 如何在页面或其他类型文档中进行显示。 |
视图(View),即业务逻辑层 |
存取模型及调取恰当模板的相关逻辑。模型与模板的桥梁。 |
从以上表述可以看出Django 视图不处理用户输入,而仅仅决定要展现哪些数据给用户,而Django 模板 仅仅决定如何展现Django视图指定的数据。或者说, Django将MVC中的视图进一步分解为 Django视图 和 Django模板两个部分,分别决定 “展现哪些数据” 和 “如何展现”,使得Django的模板可以根据需要随时替换,而不仅仅限制于内置的模板。
至于MVC控制器部分,由Django框架的URLconf来实现。URLconf机制是使用正则表达式匹配URL,然后调用合适的Python函数。URLconf对于URL的规则没有任何限制,你完全可以设计成任意的URL风格,不管是传统的,RESTful的,或者是另类的。框架把控制层给封装了,无非与数据交互这层都是数据库表的读,写,删除,更新的操作。在写程序的时候,只要调用相应的方法就行了,感觉很方便。程序员把控制层东西交给Django自动完成了。 只需要编写非常少的代码完成很多的事情。所以,它比MVC框架考虑的问题要深一步,因为我们程序员大都在写控制层的程序。这个工作交给了框架,仅需写很少的调用代码,大大提高了工作效率。
1.10 Django工作机制:
1.用manage .py runserver 启动Django服务器时就载入了在同一目录下的settings .py。该文件包含了项目中的配置信息,如前面讲的URLConf等,其中最重要的配置就是ROOT_URLCONF,它告诉Django哪个Python模块应该用作本站的URLConf,默认的是urls .py
2.当访问url的时候,Django会根据ROOT_URLCONF的设置来装载URLConf。
3.然后按顺序逐个匹配URLConf里的URLpatterns。如果找到则会调用相关联的视图函数,并把HttpRequest对象作为第一个参数(通常是request)
4.最后该view函数负责返回一个HttpResponse对象。