当前位置:   article > 正文

基于python的电影推荐系统源码_基于python电影推荐系统源码

基于python电影推荐系统源码

目录

一、整体目录(示范):

文档含项目技术介绍、E-R图、数据字典、项目功能介绍与截图等

二、运行截图

三、代码部分(示范):

四、数据库表(示范):

数据库表有注释,可以导出数据字典及更新数据库时间,欢迎交流学习

五、主要技术介绍:

六、项目调试学习(点击查看)

七、项目交流


一、整体目录(示范):

文档含项目技术介绍、E-R图、数据字典、项目功能介绍与截图等

 

二、运行截图

三、代码部分(示范):

注册较验代码:

  1. // 注册
  2. async register() {
  3. if((!this.ruleForm.yonghuzhanghao) && `yonghu` == this.tableName){
  4. this.$utils.msg(`用户账号不能为空`);
  5. return
  6. }
  7. if(`yonghu` == this.tableName && (this.ruleForm.yonghuzhanghao.length<8)){
  8. this.$utils.msg(`用户账号长度不能小于8`);
  9. return
  10. }
  11. if(`yonghu` == this.tableName && (this.ruleForm.yonghuzhanghao.length>12)){
  12. this.$utils.msg(`用户账号长度不能大于12`);
  13. return
  14. }
  15. if((!this.ruleForm.mima) && `yonghu` == this.tableName){
  16. this.$utils.msg(`密码不能为空`);
  17. return
  18. }
  19. if(`yonghu` == this.tableName && (this.ruleForm.mima!=this.ruleForm.mima2)){
  20. this.$utils.msg(`两次密码输入不一致`);
  21. return
  22. }
  23. if((!this.ruleForm.yonghuxingming) && `yonghu` == this.tableName){
  24. this.$utils.msg(`用户姓名不能为空`);
  25. return
  26. }
  27. if(`yonghu` == this.tableName && this.ruleForm.nianling&&(!this.$validate.isIntNumer(this.ruleForm.nianling))){
  28. this.$utils.msg(`年龄应输入整数`);
  29. return
  30. }
  31. if((!this.ruleForm.schoolname) && `yonghu` == this.tableName){
  32. this.$utils.msg(`学校名称不能为空`);
  33. return
  34. }
  35. if(`yonghu` == this.tableName && this.ruleForm.shouji&&(!this.$validate.isMobile(this.ruleForm.shouji))){
  36. this.$utils.msg(`手机应输入手机格式`);
  37. return
  38. }
  39. if(`yonghu` == this.tableName && this.ruleForm.youxiang&&(!this.$validate.isEmail(this.ruleForm.youxiang))){
  40. this.$utils.msg(`邮箱应输入邮件格式`);
  41. return
  42. }
  43. await this.$api.register(`${this.tableName}`, this.ruleForm, this.emailcode);
  44. this.$utils.msgBack('注册成功');;
  45. }
  46. }
  47. }
  48. </script>

推荐算法代码

  1. //智能推荐商品业务步骤
  2. 1.获取当前用户信息
  3. 2.判断当前是否有收藏信息
  4. 3.如有收藏信息按收藏推荐信息推荐,无推荐信息默认按点击次数
  5. //================以下是相关类和方法==============
  6. //商品信息后端接口类
  7. com.controller.ShangpinxinxiController
  8. /**
  9. * 商品信息前端智能排序
  10. */
  11. @IgnoreAuth
  12. @RequestMapping("/autoSort")
  13. public R autoSort(@RequestParam Map<String, Object> params,ShangpinxinxiEntity shangpinxinxi, HttpServletRequest request,String pre){
  14. EntityWrapper<ShangpinxinxiEntity> ew = new EntityWrapper<ShangpinxinxiEntity>();
  15. Map<String, Object> newMap = new HashMap<String, Object>();
  16. Map<String, Object> param = new HashMap<String, Object>();
  17. boolean flag = false;
  18. String isRecommend =(String) params.get("isRecommend");
  19. if("1".equals(isRecommend)){ //是否推荐
  20. String userId = (String) params.get("userId");
  21. YonghuEntity user = yonghuService.selectById(Long.valueOf(userId));
  22. params.remove("isRecommend");
  23. params.remove("userId");
  24. StringBuffer refIds = new StringBuffer();
  25. List<StoreupView> storeupList = storeupService.selectListView(new EntityWrapper<StoreupEntity>().eq("userid",userId));
  26. if(storeupList!=null && storeupList.size()>0){
  27. for(StoreupView storeupView: storeupList){
  28. refIds.append(storeupView.getRefid()+",");
  29. }
  30. flag =true;
  31. ew.in("id",refIds.toString());
  32. }
  33. }
  34. Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
  35. while (it.hasNext()) {
  36. Map.Entry<String, Object> entry = it.next();
  37. String key = entry.getKey();
  38. String newKey = entry.getKey();
  39. if (pre.endsWith(".")) {
  40. newMap.put(pre + newKey, entry.getValue());
  41. } else if (StringUtils.isEmpty(pre)) {
  42. newMap.put(newKey, entry.getValue());
  43. } else {
  44. newMap.put(pre + "." + newKey, entry.getValue());
  45. }
  46. }
  47. params.put("sort", "clicknum");
  48. params.put("order", "desc");
  49. PageUtils page = shangpinxinxiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, shangpinxinxi), params), params));
  50. return R.ok().put("data", page);
  51. }
  52. //收藏表后端接口
  53. com.controller.StoreupController
  54. /**
  55. * 收藏表后端保存方法
  56. */
  57. @RequestMapping("/save")
  58. public R save(@RequestBody StoreupEntity storeup, HttpServletRequest request){
  59. storeup.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
  60. //ValidatorUtils.validateEntity(storeup);
  61. storeup.setUserid((Long)request.getSession().getAttribute("userId"));
  62. storeupService.insert(storeup);
  63. return R.ok();
  64. }
  65. /**
  66. * 收藏表删除方法
  67. */
  68. @RequestMapping("/delete")
  69. public R delete(@RequestBody Long[] ids){
  70. storeupService.deleteBatchIds(Arrays.asList(ids));
  71. return R.ok();
  72. }

最新电影

  1. #coding:utf-8
  2. __author__ = "ila"
  3. import base64, copy, logging, os, time, xlrd
  4. from django.http import JsonResponse
  5. from django.apps import apps
  6. from django.db.models.aggregates import Count,Sum
  7. from .models import zuixindianying
  8. from util.codes import *
  9. from util.auth import Auth
  10. from util.common import Common
  11. import util.message as mes
  12. from django.db import connection
  13. import random
  14. from django.core.mail import send_mail
  15. from alipay import AliPayConfig, AliPay
  16. from django.conf import settings
  17. from django.shortcuts import redirect
  18. def zuixindianying_register(request):
  19. if request.method in ["POST", "GET"]:
  20. msg = {'code': normal_code, "msg": mes.normal_code}
  21. req_dict = request.session.get("req_dict")
  22. error = zuixindianying.createbyreq(zuixindianying, zuixindianying, req_dict)
  23. if error != None:
  24. msg['code'] = crud_error_code
  25. msg['msg'] = "用户已存在,请勿重复注册!"
  26. return JsonResponse(msg)
  27. def zuixindianying_login(request):
  28. if request.method in ["POST", "GET"]:
  29. msg = {'code': normal_code, "msg": mes.normal_code}
  30. req_dict = request.session.get("req_dict")
  31. datas = zuixindianying.getbyparams(zuixindianying, zuixindianying, req_dict)
  32. if not datas:
  33. msg['code'] = password_error_code
  34. msg['msg'] = mes.password_error_code
  35. return JsonResponse(msg)
  36. try:
  37. __sfsh__= zuixindianying.__sfsh__
  38. except:
  39. __sfsh__=None
  40. if __sfsh__=='是':
  41. if datas[0].get('sfsh')=='否':
  42. msg['code']=other_code
  43. msg['msg'] = "账号已锁定,请联系管理员审核!"
  44. return JsonResponse(msg)
  45. req_dict['id'] = datas[0].get('id')
  46. return Auth.authenticate(Auth, zuixindianying, req_dict)
  47. def zuixindianying_logout(request):
  48. if request.method in ["POST", "GET"]:
  49. msg = {
  50. "msg": "登出成功",
  51. "code": 0
  52. }
  53. return JsonResponse(msg)
  54. def zuixindianying_resetPass(request):
  55. '''
  56. '''
  57. if request.method in ["POST", "GET"]:
  58. msg = {"code": normal_code, "msg": mes.normal_code}
  59. req_dict = request.session.get("req_dict")
  60. columns= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
  61. try:
  62. __loginUserColumn__= zuixindianying.__loginUserColumn__
  63. except:
  64. __loginUserColumn__=None
  65. username=req_dict.get(list(req_dict.keys())[0])
  66. if __loginUserColumn__:
  67. username_str=__loginUserColumn__
  68. else:
  69. username_str=username
  70. if 'mima' in columns:
  71. password_str='mima'
  72. else:
  73. password_str='password'
  74. init_pwd = '123456'
  75. eval('''zuixindianying.objects.filter({}='{}').update({}='{}')'''.format(username_str,username,password_str,init_pwd))
  76. return JsonResponse(msg)
  77. def zuixindianying_session(request):
  78. '''
  79. '''
  80. if request.method in ["POST", "GET"]:
  81. msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}
  82. req_dict={"id":request.session.get('params').get("id")}
  83. msg['data'] = zuixindianying.getbyparams(zuixindianying, zuixindianying, req_dict)[0]
  84. return JsonResponse(msg)
  85. def zuixindianying_default(request):
  86. if request.method in ["POST", "GET"]:
  87. msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}
  88. req_dict = request.session.get("req_dict")
  89. req_dict.update({"isdefault":"是"})
  90. data=zuixindianying.getbyparams(zuixindianying, zuixindianying, req_dict)
  91. if len(data)>0:
  92. msg['data'] = data[0]
  93. else:
  94. msg['data'] = {}
  95. return JsonResponse(msg)
  96. def zuixindianying_page(request):
  97. '''
  98. '''
  99. if request.method in ["POST", "GET"]:
  100. msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
  101. req_dict = request.session.get("req_dict")
  102. #获取全部列名
  103. columns= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
  104. #当前登录用户所在表
  105. tablename = request.session.get("tablename")
  106. #authColumn=list(__authTables__.keys())[0]
  107. #authTable=__authTables__.get(authColumn)
  108. # if authTable==tablename:
  109. #params = request.session.get("params")
  110. #req_dict[authColumn]=params.get(authColumn)
  111. '''__authSeparate__此属性为真,params添加userid,后台只查询个人数据'''
  112. try:
  113. __authSeparate__=zuixindianying.__authSeparate__
  114. except:
  115. __authSeparate__=None
  116. if __authSeparate__=="是":
  117. tablename=request.session.get("tablename")
  118. if tablename!="users" and 'userid' in columns:
  119. try:
  120. req_dict['userid']=request.session.get("params").get("id")
  121. except:
  122. pass
  123. #当项目属性hasMessage为”是”,生成系统自动生成留言板的表messages,同时该表的表属性hasMessage也被设置为”是”,字段包括userid(用户id),username(用户名),content(留言内容),reply(回复)
  124. #接口page需要区分权限,普通用户查看自己的留言和回复记录,管理员查看所有的留言和回复记录
  125. try:
  126. __hasMessage__=zuixindianying.__hasMessage__
  127. except:
  128. __hasMessage__=None
  129. if __hasMessage__=="是":
  130. tablename=request.session.get("tablename")
  131. if tablename!="users":
  132. req_dict["userid"]=request.session.get("params").get("id")
  133. # 判断当前表的表属性isAdmin,为真则是管理员表
  134. # 当表属性isAdmin=”是”,刷出来的用户表也是管理员,即page和list可以查看所有人的考试记录(同时应用于其他表)
  135. __isAdmin__ = None
  136. allModels = apps.get_app_config('main').get_models()
  137. for m in allModels:
  138. if m.__tablename__==tablename:
  139. try:
  140. __isAdmin__ = m.__isAdmin__
  141. except:
  142. __isAdmin__ = None
  143. break
  144. # 当前表也是有管理员权限的表
  145. if __isAdmin__ == "是":
  146. if req_dict.get("userid"):
  147. del req_dict["userid"]
  148. else:
  149. #非管理员权限的表,判断当前表字段名是否有userid
  150. if tablename!="users" and 'zuixindianying'[:7]!='discuss'and "userid" in zuixindianying.getallcolumn(zuixindianying,zuixindianying):
  151. req_dict["userid"] = request.session.get("params").get("id")
  152. #当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
  153. try:
  154. __authTables__=zuixindianying.__authTables__
  155. except:
  156. __authTables__=None
  157. if __authTables__!=None and __authTables__!={}:
  158. try:
  159. del req_dict['userid']
  160. except:
  161. pass
  162. for authColumn,authTable in __authTables__.items():
  163. if authTable==tablename:
  164. params = request.session.get("params")
  165. req_dict[authColumn]=params.get(authColumn)
  166. break
  167. msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
  168. msg['data']['pageSize'] =zuixindianying.page(zuixindianying, zuixindianying, req_dict, request)
  169. return JsonResponse(msg)
  170. def zuixindianying_autoSort(request):
  171. '''
  172. .智能推荐功能(表属性:[intelRecom(是/否)],新增clicktime[前端不显示该字段]字段(调用info/detail接口的时候更新),按clicktime排序查询)
  173. 主要信息列表(如商品列表,新闻列表)中使用,显示最近点击的或最新添加的5条记录就行
  174. '''
  175. if request.method in ["POST", "GET"]:
  176. msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
  177. req_dict = request.session.get("req_dict")
  178. if "clicknum" in zuixindianying.getallcolumn(zuixindianying,zuixindianying):
  179. req_dict['sort']='clicknum'
  180. else:
  181. req_dict['sort']='clicktime'
  182. req_dict['order']='desc'
  183. msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
  184. msg['data']['pageSize'] = zuixindianying.page(zuixindianying,zuixindianying, req_dict)
  185. return JsonResponse(msg)
  186. def zuixindianying_list(request):
  187. '''
  188. 前台分页
  189. '''
  190. if request.method in ["POST", "GET"]:
  191. msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
  192. req_dict = request.session.get("req_dict")
  193. #获取全部列名
  194. columns= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
  195. #表属性[foreEndList]前台list:和后台默认的list列表页相似,只是摆在前台,否:指没有此页,是:表示有此页(不需要登陆即可查看),前要登:表示有此页且需要登陆后才能查看
  196. try:
  197. __foreEndList__=zuixindianying.__foreEndList__
  198. except:
  199. __foreEndList__=None
  200. if __foreEndList__=="前要登":
  201. tablename=request.session.get("tablename")
  202. if tablename!="users" and 'userid' in columns:
  203. try:
  204. req_dict['userid']=request.session.get("params").get("id")
  205. except:
  206. pass
  207. #forrEndListAuth
  208. try:
  209. __foreEndListAuth__=zuixindianying.__foreEndListAuth__
  210. except:
  211. __foreEndListAuth__=None
  212. #authSeparate
  213. try:
  214. __authSeparate__=zuixindianying.__authSeparate__
  215. except:
  216. __authSeparate__=None
  217. if __foreEndListAuth__ =="是" and __authSeparate__=="是":
  218. tablename=request.session.get("tablename")
  219. if tablename!="users":
  220. req_dict['userid']=request.session.get("params",{"id":0}).get("id")
  221. tablename = request.session.get("tablename")
  222. if tablename == "users" and req_dict.get("userid") != None:#判断是否存在userid列名
  223. del req_dict["userid"]
  224. else:
  225. __isAdmin__ = None
  226. allModels = apps.get_app_config('main').get_models()
  227. for m in allModels:
  228. if m.__tablename__==tablename:
  229. try:
  230. __isAdmin__ = m.__isAdmin__
  231. except:
  232. __isAdmin__ = None
  233. break
  234. if __isAdmin__ == "是":
  235. if req_dict.get("userid"):
  236. del req_dict["userid"]
  237. else:
  238. #非管理员权限的表,判断当前表字段名是否有userid
  239. if "userid" in columns:
  240. try:
  241. # 本接口可以匿名访问,所以try判断是否为匿名
  242. req_dict['userid']=request.session.get("params").get("id")
  243. except:
  244. pass
  245. #当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
  246. try:
  247. __authTables__=zuixindianying.__authTables__
  248. except:
  249. __authTables__=None
  250. if __authTables__!=None and __authTables__!={} and __foreEndListAuth__=="是":
  251. try:
  252. del req_dict['userid']
  253. except:
  254. pass
  255. for authColumn,authTable in __authTables__.items():
  256. if authTable==tablename:
  257. params = request.session.get("params")
  258. req_dict[authColumn]=params.get(authColumn)
  259. break
  260. if zuixindianying.__tablename__[:7]=="discuss":
  261. try:
  262. del req_dict['userid']
  263. except:
  264. pass
  265. msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
  266. msg['data']['pageSize'] = zuixindianying.page(zuixindianying, zuixindianying, req_dict)
  267. return JsonResponse(msg)
  268. def zuixindianying_save(request):
  269. '''
  270. 后台新增
  271. '''
  272. if request.method in ["POST", "GET"]:
  273. msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
  274. req_dict = request.session.get("req_dict")
  275. if 'clicktime' in req_dict.keys():
  276. del req_dict['clicktime']
  277. tablename=request.session.get("tablename")
  278. __isAdmin__ = None
  279. allModels = apps.get_app_config('main').get_models()
  280. for m in allModels:
  281. if m.__tablename__==tablename:
  282. try:
  283. __isAdmin__ = m.__isAdmin__
  284. except:
  285. __isAdmin__ = None
  286. break
  287. #获取全部列名
  288. columns= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
  289. if tablename!='users' and req_dict.get("userid")!=None and 'userid' in columns and __isAdmin__!='是':
  290. params=request.session.get("params")
  291. req_dict['userid']=params.get('id')
  292. error= zuixindianying.createbyreq(zuixindianying,zuixindianying, req_dict)
  293. if error!=None:
  294. msg['code'] = crud_error_code
  295. msg['msg'] = error
  296. return JsonResponse(msg)
  297. def zuixindianying_add(request):
  298. '''
  299. 前台新增
  300. '''
  301. if request.method in ["POST", "GET"]:
  302. msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
  303. req_dict = request.session.get("req_dict")
  304. #获取全部列名
  305. columns= zuixindianying.getallcolumn( zuixindianying, zuixindianying)
  306. try:
  307. __authSeparate__=zuixindianying.__authSeparate__
  308. except:
  309. __authSeparate__=None
  310. if __authSeparate__=="是":
  311. tablename=request.session.get("tablename")
  312. if tablename!="users" and 'userid' in columns:
  313. try:
  314. req_dict['userid']=request.session.get("params").get("id")
  315. except:
  316. pass
  317. try:
  318. __foreEndListAuth__=zuixindianying.__foreEndListAuth__
  319. except:
  320. __foreEndListAuth__=None
  321. if __foreEndListAuth__ and __foreEndListAuth__!="否":
  322. tablename=request.session.get("tablename")
  323. if tablename!="users":
  324. req_dict['userid']=request.session.get("params").get("id")
  325. error= zuixindianying.createbyreq(zuixindianying,zuixindianying, req_dict)
  326. if error!=None:
  327. msg['code'] = crud_error_code
  328. msg['msg'] = error
  329. return JsonResponse(msg)
  330. def zuixindianying_thumbsup(request,id_):
  331. '''
  332. 点赞:表属性thumbsUp[是/否],刷表新增thumbsupnum赞和crazilynum踩字段,
  333. '''
  334. if request.method in ["POST", "GET"]:
  335. msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
  336. req_dict = request.session.get("req_dict")
  337. id_=int(id_)
  338. type_=int(req_dict.get("type",0))
  339. rets=zuixindianying.getbyid(zuixindianying,zuixindianying,id_)
  340. update_dict={
  341. "id":id_,
  342. }
  343. if type_==1:#赞
  344. update_dict["thumbsupnum"]=int(rets[0].get('thumbsupnum'))+1
  345. elif type_==2:#踩
  346. update_dict["crazilynum"]=int(rets[0].get('crazilynum'))+1
  347. error = zuixindianying.updatebyparams(zuixindianying,zuixindianying, update_dict)
  348. if error!=None:
  349. msg['code'] = crud_error_code
  350. msg['msg'] = error
  351. return JsonResponse(msg)
  352. def zuixindianying_info(request,id_):
  353. '''
  354. '''
  355. if request.method in ["POST", "GET"]:
  356. msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
  357. data = zuixindianying.getbyid(zuixindianying,zuixindianying, int(id_))
  358. if len(data)>0:
  359. msg['data']=data[0]
  360. #浏览点击次数
  361. try:
  362. __browseClick__= zuixindianying.__browseClick__
  363. except:
  364. __browseClick__=None
  365. if __browseClick__=="是" and "clicknum" in zuixindianying.getallcolumn(zuixindianying,zuixindianying):
  366. try:
  367. clicknum=int(data[0].get("clicknum",0))+1
  368. except:
  369. clicknum=0+1
  370. click_dict={"id":int(id_),"clicknum":clicknum}
  371. ret=zuixindianying.updatebyparams(zuixindianying,zuixindianying,click_dict)
  372. if ret!=None:
  373. msg['code'] = crud_error_code
  374. msg['msg'] = ret
  375. return JsonResponse(msg)
  376. def zuixindianying_detail(request,id_):
  377. '''
  378. '''
  379. if request.method in ["POST", "GET"]:
  380. msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
  381. data =zuixindianying.getbyid(zuixindianying,zuixindianying, int(id_))
  382. if len(data)>0:
  383. msg['data']=data[0]
  384. #浏览点击次数
  385. try:
  386. __browseClick__= zuixindianying.__browseClick__
  387. except:
  388. __browseClick__=None
  389. if __browseClick__=="是" and "clicknum" in zuixindianying.getallcolumn(zuixindianying,zuixindianying):
  390. try:
  391. clicknum=int(data[0].get("clicknum",0))+1
  392. except:
  393. clicknum=0+1
  394. click_dict={"id":int(id_),"clicknum":clicknum}
  395. ret=zuixindianying.updatebyparams(zuixindianying,zuixindianying,click_dict)
  396. if ret!=None:
  397. msg['code'] = crud_error_code
  398. msg['msg'] = retfo
  399. return JsonResponse(msg)
  400. def zuixindianying_update(request):
  401. '''
  402. '''
  403. if request.method in ["POST", "GET"]:
  404. msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
  405. req_dict = request.session.get("req_dict")
  406. if req_dict.get("mima") and req_dict.get("password"):
  407. if "mima" not in zuixindianying.getallcolumn(zuixindianying,zuixindianying) :
  408. del req_dict["mima"]
  409. if "password" not in zuixindianying.getallcolumn(zuixindianying,zuixindianying) :
  410. del req_dict["password"]
  411. try:
  412. del req_dict["clicknum"]
  413. except:
  414. pass
  415. error = zuixindianying.updatebyparams(zuixindianying, zuixindianying, req_dict)
  416. if error!=None:
  417. msg['code'] = crud_error_code
  418. msg['msg'] = error
  419. return JsonResponse(msg)
  420. def zuixindianying_delete(request):
  421. '''
  422. 批量删除
  423. '''
  424. if request.method in ["POST", "GET"]:
  425. msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
  426. req_dict = request.session.get("req_dict")
  427. error=zuixindianying.deletes(zuixindianying,
  428. zuixindianying,
  429. req_dict.get("ids")
  430. )
  431. if error!=None:
  432. msg['code'] = crud_error_code
  433. msg['msg'] = error
  434. return JsonResponse(msg)
  435. def zuixindianying_vote(request,id_):
  436. '''
  437. 浏览点击次数(表属性[browseClick:是/否],点击字段(clicknum),调用info/detail接口的时候后端自动+1)、投票功能(表属性[vote:是/否],投票字段(votenum),调用vote接口后端votenum+1)
  438. 统计商品或新闻的点击次数;提供新闻的投票功能
  439. '''
  440. if request.method in ["POST", "GET"]:
  441. msg = {"code": normal_code, "msg": mes.normal_code}
  442. data= zuixindianying.getbyid(zuixindianying, zuixindianying, int(id_))
  443. for i in data:
  444. votenum=i.get('votenum')
  445. if votenum!=None:
  446. params={"id":int(id_),"votenum":votenum+1}
  447. error=zuixindianying.updatebyparams(zuixindianying,zuixindianying,params)
  448. if error!=None:
  449. msg['code'] = crud_error_code
  450. msg['msg'] = error
  451. return JsonResponse(msg)
  452. def zuixindianying_importExcel(request):
  453. if request.method in ["POST", "GET"]:
  454. msg = {"code": normal_code, "msg": "成功", "data": {}}
  455. excel_file = request.FILES.get("file", "")
  456. file_type = excel_file.name.split('.')[1]
  457. if file_type in ['xlsx', 'xls']:
  458. data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())
  459. table = data.sheets()[0]
  460. rows = table.nrows
  461. try:
  462. for row in range(1, rows):
  463. row_values = table.row_values(row)
  464. req_dict = {}
  465. zuixindianying.createbyreq(zuixindianying, zuixindianying, req_dict)
  466. except:
  467. pass
  468. else:
  469. msg.code = 500
  470. msg.msg = "文件类型错误"
  471. return JsonResponse(msg)
  472. def zuixindianying_sendemail(request):
  473. if request.method in ["POST", "GET"]:
  474. req_dict = request.session.get("req_dict")
  475. code = random.sample(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 4)
  476. to = []
  477. to.append(req_dict['email'])
  478. send_mail('用户注册', '您的注册验证码是【'+''.join(code)+'】,请不要把验证码泄漏给其他人,如非本人请勿操作。', 'yclw9@qq.com', to, fail_silently = False)
  479. cursor = connection.cursor()
  480. cursor.execute("insert into emailregistercode(email,role,code) values('"+req_dict['email']+"','用户','"+''.join(code)+"')")
  481. msg = {
  482. "msg": "发送成功",
  483. "code": 0
  484. }
  485. return JsonResponse(msg)
  486. def zuixindianying_autoSort2(request):
  487. if request.method in ["POST", "GET"]:
  488. req_dict = request.session.get("req_dict")
  489. cursor = connection.cursor()
  490. leixing = set()
  491. try:
  492. cursor.execute("select inteltype from storeup where userid = %d"%(request.session.get("params").get("id"))+" and tablename = 'zuixindianying' order by addtime desc")
  493. rows = cursor.fetchall()
  494. for row in rows:
  495. for item in row:
  496. leixing.add(item)
  497. except:
  498. leixing = set()
  499. L = []
  500. cursor.execute("select * from zuixindianying where $intelRecomColumn in ('%s"%("','").join(leixing)+"') union all select * from zuixindianying where $intelRecomColumn not in('%s"%("','").join(leixing)+"')")
  501. desc = cursor.description
  502. data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
  503. for online_dict in data_dict:
  504. for key in online_dict:
  505. if 'datetime.datetime' in str(type(online_dict[key])):
  506. online_dict[key] = online_dict[key].strftime(
  507. "%Y-%m-%d %H:%M:%S")
  508. else:
  509. pass
  510. L.append(online_dict)
  511. return JsonResponse({"code": 0, "msg": '', "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":5,"list": L[0:6]}})
  512. def zuixindianying_value(request, xColumnName, yColumnName, timeStatType):
  513. if request.method in ["POST", "GET"]:
  514. msg = {"code": normal_code, "msg": "成功", "data": {}}
  515. where = ' where 1 = 1 '
  516. sql = ''
  517. if timeStatType == '日':
  518. 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')
  519. if timeStatType == '月':
  520. 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')
  521. if timeStatType == '年':
  522. sql = "SELECT DATE_FORMAT({0}, '%Y') {0}, sum({1}) total FROM zuixindianying {2} GROUP BY DATE_FORMAT({0}, '%Y')".format(xColumnName, yColumnName, where, '%Y')
  523. L = []
  524. cursor = connection.cursor()
  525. cursor.execute(sql)
  526. desc = cursor.description
  527. data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
  528. for online_dict in data_dict:
  529. for key in online_dict:
  530. if 'datetime.datetime' in str(type(online_dict[key])):
  531. online_dict[key] = online_dict[key].strftime(
  532. "%Y-%m-%d %H:%M:%S")
  533. else:
  534. pass
  535. L.append(online_dict)
  536. msg['data'] = L
  537. return JsonResponse(msg)
  538. def zuixindianying_o_value(request, xColumnName, yColumnName):
  539. if request.method in ["POST", "GET"]:
  540. msg = {"code": normal_code, "msg": "成功", "data": {}}
  541. where = ' where 1 = 1 '
  542. sql = "SELECT {0}, sum({1}) AS total FROM zuixindianying {2} GROUP BY {0}".format(xColumnName, yColumnName, where)
  543. L = []
  544. cursor = connection.cursor()
  545. cursor.execute(sql)
  546. desc = cursor.description
  547. data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
  548. for online_dict in data_dict:
  549. for key in online_dict:
  550. if 'datetime.datetime' in str(type(online_dict[key])):
  551. online_dict[key] = online_dict[key].strftime(
  552. "%Y-%m-%d %H:%M:%S")
  553. else:
  554. pass
  555. L.append(online_dict)
  556. msg['data'] = L
  557. return JsonResponse(msg)
  558. def zuixindianying_alipay(request):
  559. if request.method in ["POST", "GET"]:
  560. alipay = AliPay(
  561. appid=settings.ALIPAY_APP_ID,
  562. app_notify_url=None,
  563. app_private_key_string=settings.APP_PRIVATE_KEY_STRING,
  564. alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,
  565. sign_type=settings.ALIPAY_SIGN_TYPE,
  566. debug=True,
  567. config=AliPayConfig(timeout=15)
  568. )
  569. req_dict = request.session.get("req_dict")
  570. order_string = alipay.api_alipay_trade_page_pay(
  571. out_trade_no=req_dict['tradeno'],
  572. total_amount=req_dict['totalamount'],
  573. subject=req_dict['subject'],
  574. return_url='http://localhost:8080/django3yz6u/zuixindianying/notify',
  575. #notify_url=''
  576. )
  577. pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
  578. pay_url = '<form name="punchout_form" method="post" action="{0}"><input type="hidden" name="biz_content" ><input type="submit" value="立即支付" style="display: none"></form>'.format(pay_url)
  579. return JsonResponse({'code': 0, "data": pay_url})
  580. def zuixindianying_notify(request):
  581. if request.method in ["POST", "GET"]:
  582. req_dict = request.session.get("req_dict")
  583. out_trade_no = req_dict['out_trade_no']
  584. cursor = connection.cursor()
  585. 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对象

六、项目调试学习点击查看

七、项目交流

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/531488
推荐阅读
相关标签
  

闽ICP备14008679号