def post(self, *args, **kwargs): rep = BaseResponse() form = account.SendMsgForm() if form.valid(self): email = form._value_dict['email'] conn = ORM.session() has_exists_email = conn.query(ORM.UserInfo).filter( ORM.UserInfo.email == form._value_dict['email']).count() print(has_exists_email, "@@@@", form._value_dict['email']) if has_exists_email: rep.summary = "此邮箱已经被注册" self.write(json.dumps(rep.__dict__)) return current_date = datetime.datetime.now() code = commons.random_code() count = conn.query( ORM.SendMsg).filter_by(**form._value_dict).count() if not count: insert = ORM.SendMsg(code=code, email=email, ctime=current_date) conn.add(insert) conn.commit() rep.status = True else: limit_day = current_date - datetime.timedelta(hours=1) times = conn.query(ORM.SendMsg).filter( ORM.SendMsg.email == email, ORM.SendMsg.ctime > limit_day, ORM.SendMsg.times >= 10, ).count() if times: rep.summary = "'已经超过今日最大次数(1小时后重试)'" else: unfreeze = conn.query(ORM.SendMsg).filter( ORM.SendMsg.email == email, ORM.SendMsg.ctime < limit_day).count() if unfreeze: conn.query(ORM.SendMsg).filter_by(email=email).update( {"times": 0}) conn.query(ORM.SendMsg).filter_by(email=email).update( { "times": ORM.SendMsg.times + 1, "code": code, "ctime": current_date }, synchronize_session="evaluate") conn.commit() rep.status = True conn.close() else: rep.summary = form._error_dict['email'] self.write(json.dumps(rep.__dict__))
def send_msg(req): ''' 该功能主要用于注册时候发送,邮箱验证码 :param req: :return: ''' rep = BaseResponse() # 拿取接口需要返回的字段以及初始默认值 form = SendMsgForm(req.POST) # 拿取前端返回的数据进行邮箱校验 if form.is_valid(): _value_dict = form.clean() # 如果信息正确输入,则拿取到正确的信息 email = _value_dict['email'] email_list = [email] has_exists_email = models.UserInfo.objects.filter( email=email).count() # 如果有值则提示用户已经注册了 if has_exists_email: rep.summary = "此邮箱号,已被注册!" return HttpResponse(json.dumps(rep.__dict__)) current_date = datetime.datetime.now() # 获取一个当前时间 code = commons.random_code() # 产生一个4位的随机验证码 count = models.SendMsg.objects.filter( email=email).count() # 统计发送了短信验证码的次数 if not count: # 如果没有发送则发送,在表中记录 models.SendMsg.objects.create(code=code, email=email, ctime=current_date) send_email(email_list, code) rep.status = True else: limit_day = current_date - datetime.timedelta( hours=1) # 将创建时间减去一小时前的时间=一小时 times = models.SendMsg.objects.filter( email=email, ctime__gt=limit_day, # 如果数据库中的时间大于 一小时前的时间(此时表明在1小时以内) times__gt=9).count() # 获取数据库中满足要求的数据(次数大于9) if times: rep.summary = "'已经超过发送的最大次数(请1小时后重试)'" else: unfreeze = models.SendMsg.objects.filter( email=email, ctime__lt=limit_day).count( ) # 获取一小时前的时间小于当前时间的数据(此时重置次数times) if unfreeze: models.SendMsg.objects.filter(email=email).update(times=0) from django.db.models import F # 导入F查询 # 更新数据库中的数据 models.SendMsg.objects.filter(email=email).update( code=code, ctime=current_date, times=F('times') + 1) send_email(email_list, code) rep.status = True else: rep.summary = form.errors['email'][0] # 如果不正确 则修改返回字段中的summary信息 return HttpResponse(json.dumps(rep.__dict__)) # 返回时 把状态信息转换成json格式返回给前端
def send_msg(request): """ 注册时,发送邮箱验证码 :param request: :return: """ rep = BaseResponse() form = SendMsgForm(request.POST) if form.is_valid(): _value_dict = form.clean() email = _value_dict['email'] has_exists_email = models.UserInfo.objects.filter(email=email).count() if has_exists_email: rep.summary = "此邮箱已经被注册" return HttpResponse(json.dumps(rep.__dict__)) current_date = datetime.datetime.now() code = commons.random_code() count = models.SendMsg.objects.filter(email=email).count() if not count: models.SendMsg.objects.create(code=code, email=email, ctime=current_date) rep.status = True else: limit_day = current_date - datetime.timedelta(hours=1) times = models.SendMsg.objects.filter(email=email, ctime__gt=limit_day, times__gt=9).count() if times: rep.summary = "'已超最大次数(1小时后重试)'" else: unfreeze = models.SendMsg.objects.filter( email=email, ctime__lt=limit_day).count() if unfreeze: models.SendMsg.objects.filter(email=email).update(times=0) from django.db.models import F models.SendMsg.objects.filter(email=email).update( code=code, ctime=current_date, times=F('times') + 1) rep.status = True else: #error_dict = json.loads(form.errors.as_json()) #rep.summary = error_dict['email'][0]['message'] rep.summary = form.errors['email'][0] return HttpResponse(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() form = account.SendMsgForm() # 判断输入是否合法 if form.valid(self): email = form._value_dict['email'] conn = ORM.session() # 判断该邮箱是否已注册 has_exists_email = conn.query(ORM.UserInfo).filter(ORM.UserInfo.email == email).count() if has_exists_email: rep.summary = '该邮箱已被注册' self.write(json.dumps(rep.__dict__)) return current_datetime = datetime.datetime.now() code = commons.random_code() # 判断该邮箱之前是否发送过验证码 has_send_count = conn.query(ORM.SendMsg).filter(ORM.SendMsg.email == email).count if not has_send_count: message.email([email, ], code) insert_obj = ORM.SendMsg(email = email, code = code, ctime = current_datetime) conn.add(insert_obj) conn.commit() rep.status = True else: # 发送过则判断是否过于频繁 limit_hour = current_datetime - datetime.timedelta(hours=1) times = conn.query(ORM.SendMsg).filter(ORM.SendMsg.email == email, ORM.SendMsg.ctime > limit_hour, ORM.SendMsg.times >= 10,).count() if times: rep.summary = "已经超过今日最大次数(1小时后重试)" else: # 判断是否超过间隔时间,是则清零 unforzen = conn.query(ORM.SendMsg).filter(ORM.SendMsg.email == email, ORM.SendMsg.ctime < limit_hour).count() if unforzen: # filter_by 里面是键值对; filter 里面是条件 conn.query(ORM.SendMsg).filter_by(email = email).update({"times": 0}) message.email([email,], code) conn.query(ORM.SendMsg).filter_by(email = email).update({"times": ORM.SendMsg.times + 1, "code": code, "ctime": current_datetime}) conn.commit() rep.status = True conn.close() else: rep.summary = form._error_dict['email'] self.write(json.dumps(rep.__dict__))
def creat_report(req): ''' 初始化变量 :param req: :return: ''' # global filePath rep = BaseResponse() user_info = req.session['user_info'] u_nid = user_info['nid'] u_name = user_info['username'] ePassword = models.UserInfo.objects.get(nid=u_nid).password headLine = req.POST.get('itemName') create_word = CreateWord(u_nid, headLine) obj_ufp = models.UserFilesPaths.objects.get(user_info_id=u_nid) if req.method == "POST": try: create_word.create_word() # 生成报告 obj_ufp.word_resultFile_path = create_word.return_filePath( ) # 将获取的文件名存入数据库 obj_ufp.save() rep.message = "word生成成功!" rep.summary = "操作成功!" rep.status = True except Exception as e: rep.status = False rep.message = "word生成失败!" rep.summary = "操作失败!" print("报错原因:", e) if req.method == "GET": obj_ri = models.ReportInfo.objects.get(user_info_id=u_nid) emailCount = obj_ri.emailContent email_list = create_word.buffer_func(obj_ri.emailList) authorEmail = '*****@*****.**' % u_name rep.message = "报告发送成功!" rep.status = True filePath = obj_ufp.word_resultFile_path # 获取报告地址 email_report(filePath, emailCount, email_list, authorEmail=authorEmail, ePassword=ePassword) return HttpResponse(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() news_id = self.get_argument('news_id', None) if not news_id: rep.summary = "新闻ID不能为空." else: user_info_id = self.session['user_info']['nid'] conn = ORM.session() has_favor = conn.query(ORM.Favor).filter(ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).count() if has_favor: conn.query(ORM.Favor).filter(ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).delete() conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count - 1}, synchronize_session="evaluate") rep.code = StatusCodeEnum.FavorMinus else: conn.add(ORM.Favor(user_info_id=user_info_id, news_id=news_id, ctime=datetime.datetime.now())) conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count + 1}, synchronize_session="evaluate") rep.code = StatusCodeEnum.FavorPlus conn.commit() conn.close() rep.status = True self.write(json.dumps(rep.__dict__))
def inner(self, *args, **kwargs): if not self.session['is_login']: rep = BaseResponse() rep.summary = "auth failed" self.write(json.dumps(rep.__dict__)) return func(self, *args, **kwargs)
def favor(request): """ 点赞 :param request: :return: """ rep = BaseResponse() news_id = request.POST.get('news_id', None) if not news_id: rep.summary = "新闻ID不能为空." else: user_info_id = request.session['user_info']['nid'] has_favor = models.Favor.objects.filter(user_info_id=user_info_id, news_id=news_id).count() if has_favor: models.Favor.objects.filter(user_info_id=user_info_id, news_id=news_id).delete() models.News.objects.filter(nid=news_id).update(favor_count=F('favor_count') - 1) rep.code = StatusCodeEnum.FavorMinus else: models.Favor.objects.create(user_info_id=user_info_id, news_id=news_id, ctime=datetime.datetime.now()) models.News.objects.filter(nid=news_id).update(favor_count=F('favor_count') + 1) rep.code = StatusCodeEnum.FavorPlus rep.status = True return HttpResponse(json.dumps(rep.__dict__))
def favor(request): """新闻点赞""" rep = BaseResponse() news_id = request.POST.get("news_id", None) if not news_id: rep.summary = "新闻ID不能为空" else: user_info_id = request.session["user_info"]["nid"] has_favor = models.Favor.objects.filter(user_info_id=user_info_id, news_id=news_id).count() if has_favor: models.Favor.objects.filter(user_info_id=user_info_id, news_id=news_id).delete() models.News.objects.filter(nid=news_id).update(favor_count=F("favor_count")-1) rep.code = StatusCodeEnum.FavorMinus else: models.Favor.objects.create(user_info_id=user_info_id, news_id=news_id, ctime=datetime.datetime.now()) models.News.objects.filter(nid=news_id).update(favor_count=F("favor_count")+1) rep.code = StatusCodeEnum.FavorPlus # 获取当前点赞数返回给前端 obj = models.News.objects.get(nid=news_id) rep.counts = obj.favor_count rep.status = True return HttpResponse(json.dumps(rep.__dict__))
def send_msg(request): """发送邮件验证码""" rep = BaseResponse() form = SendMsgForm(request.POST) # 一、先检查邮箱格式 if form.is_valid(): _value_dict = form.clean() email = _value_dict["email"] # 二、再检查邮箱是否已被注册 has_exists_email = models.UserInfo.objects.filter(email=email).count() if has_exists_email: rep.summary = "此邮箱已被注册" return HttpResponse(json.dumps(rep.__dict__)) # 三、再检查此邮箱发送验证码的次数,并生成当前时间以及验证码 current_date = datetime.datetime.now() code = commons.random_code() count = models.SendMsg.objects.filter(email=email).count() if not count: # 如果此邮箱从没有发送过验证码,则在数据库SendMsg表创建一条新记录,并发送邮件 models.SendMsg.objects.create(code=code, email=email, ctime=current_date, times=1) rep.status = True # 发送邮件 send_email(email, "验证码:" + str(code)) else: # 如果之前发送过验证码,先检查有没有超过限制,一小时只能发10次 limit_time = current_date - datetime.timedelta(hours=1) current_times = models.SendMsg.objects.filter(email=email, ctime__gt=limit_time, times__gt=9).count() if current_times: # 如果已经发送超过9次,并且最后一次发邮件到现在还没有超过一小时,提示错误,等待一小时后重试 rep.summary = "已超过最大次数,请一小时后重试" else: # 如果最后一次发送邮件时间到现在已经超过一小时了,则将计数归零,重新计算 # 然后更新数据库记录 unfreeze = models.SendMsg.objects.filter(email=email, ctime__lt=limit_time).count() if unfreeze: models.SendMsg.objects.filter(email=email).update(times=0) models.SendMsg.objects.filter(email=email).update(code=code, ctime=current_date, times=F("times")+1) rep.status = True # 发送邮件 send_email(email, "验证码:" + str(code)) else: rep.summary = form.errors["email"][0] return HttpResponse(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() try: file_metas = self.request.files["img"] for meta in file_metas: file_name = meta['filename'] file_path = os.path.join('statics', 'upload', commons.generate_md5(file_name)) with open(file_path, 'wb') as up: up.write(meta['body']) rep.status = True rep.data = file_path except Exception as ex: rep.summary = str(ex) self.write(json.dumps(rep.__dict__))
def servers_info_extract(req): rep = BaseResponse() # 创建 回调类对象 user_info = req.session['user_info'] # 从session中拿取 用户ID u_nid = user_info['nid'] # 拿取该表对象 ser_obj = models.PertestingServersTable.objects.get(user_info_id=u_nid) # 实例化服务器对象 ser = servers(ser_obj.server_add, ser_obj.server_port, ser_obj.server_username, ser_obj.server_password) try: res_mem, res_sys = ser.info_dispose() # 计算内存占用比 ser_obj.memory_used_per = (int(res_mem['used']) / int(res_mem['total'])) * 100 # 计算系统负债的情况 ser_obj.sysLoad_time = res_sys[0] ser_obj.sysLoad_runTime = res_sys[2] + res_sys[3].replace(",", "") ser_obj.sysLoad_userNum = res_sys[5].replace(",", "") ser_obj.sysLoad_loadLevel_1min = res_sys[9].replace(",", "") ser_obj.sysLoad_loadLevel_5min = res_sys[10].replace(",", "") ser_obj.sysLoad_loadLevel_15min = res_sys[11].replace("\n", "") ser_obj.save() rep.status = True rep.data = [ ser_obj.sysLoad_time, ser_obj.sysLoad_runTime, ser_obj.sysLoad_userNum ] rep.message = [ ser_obj.memory_used_per, ser_obj.sysLoad_loadLevel_1min, ser_obj.sysLoad_loadLevel_5min, ser_obj.sysLoad_loadLevel_15min ] except Exception as e: print('错误内容:', e) rep.status = False rep.data = [] rep.message = [] rep.summary = '运行错误!servers_info_extract 接口请求失败。' finally: ser.server_linke_close() return HttpResponse(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): print("我到了!!!") rep = BaseResponse() try: file_metas = self.request.files["fafafa"] for meta in file_metas: file_name = meta['filename'] xxx = file_name.split(".")[-1] username = self.session['user_info']["username"] file_path = os.path.join('statics', 'upload', username, 'temp', commons.generate_md5(file_name) + '.' + xxx) with open(file_path, 'wb') as up: up.write(meta['body']) rep.status = True rep.data = file_path except Exception as ex: rep.summary = str(ex) self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() # 前端对应index.html中的DoFavor方法中的ajax请求 news_id = self.get_argument('news_id', None) if not news_id: rep.summary = "新闻ID不能为空." else: # 从session中获取用户信息 user_info_id = self.session['user_info']['nid'] conn = ORM.session() # 在Favor表中查询是否有该用户的点赞记录 has_favor = conn.query(ORM.Favor).filter( ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).count() if has_favor: # 用户已点过赞,则此时用户的点击操作代表消除自己的点赞 # 因此先从数据库中删除点赞该用户的点赞记录 # 分别从Favor和News表中同时删除,保持数据一致 conn.query(ORM.Favor).filter( ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).delete() conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count - 1}, synchronize_session="evaluate") # 要给前端发送的code信息,以便前端做出相应的效果改变 rep.code = StatusCodeEnum.FavorMinus else: # 否则用户执行点赞操作,数据库内记录+1 conn.add( ORM.Favor(user_info_id=user_info_id, news_id=news_id, ctime=datetime.datetime.now())) conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count + 1}, synchronize_session="evaluate") rep.code = StatusCodeEnum.FavorPlus conn.commit() conn.close() rep.status = True # 将返回信息写入前端 self.write(json.dumps(rep.__dict__))
def upload_image(request): """ 上传图片 :param request: :return: """ rep = BaseResponse() try: obj = request.FILES.get('img') file_path = os.path.join('statics', 'upload', commons.generate_md5(obj.name)) f = open(file_path, 'wb') for chunk in obj.chunks(): f.write(chunk) f.close() rep.status = True rep.data = file_path except Exception as ex: rep.summary = str(ex) return HttpResponse(json.dumps(rep.__dict__))
def per_data_extract(req): """ 前端页面点击发送请求 后 执行的操作 :param req: :return: """ rep = BaseResponse() # 创建 回调类对象 user_info = req.session['user_info'] # 从session中拿取 用户ID u_nid = user_info['nid'] # 拿取该表对象 per_obj = models.PertestingTable.objects.get(user_info_id=u_nid) # 将部分数据进行处理 协议类型\并发数\请求头\请求体类型转换 url = per_obj.hosts + per_obj.paths if not url.find('https'): flag = False else: flag = True # 查询到最大并发数 与 每次启动的并发数 并且进行计算 maxNum = int(per_obj.maxnum) onceNum = int(per_obj.oncenum) if onceNum < maxNum: per_obj.oncenum += onceNum else: per_obj.oncenum = maxNum # print('此时的并发数为:',onceNum) # 请求头进行预处理 try: headers = json.loads(per_obj.headers) except Exception: headers = {"Content-Type": "application/json"} # 请求体进行预处理 try: datas = json.loads(per_obj.datas) except Exception: datas = '' # 请求断言进行预处理 try: assert_dic = json.loads(per_obj.assert_dic) # 对断言数据进行预处理 except Exception: assert_dic = {} maxTime = per_obj.maxTime # 接口响应的最大时间 # 将表中的数据 初始化到 数据统计类中 ds = DataStatistics(method=per_obj.method, url=url, headers=headers, data=datas, count=onceNum, flag=flag, assert_dic=assert_dic, maxTime=maxTime) if req.method == 'POST': loop_num = req.POST.get('loop_num') # 收集前端请求中的循环次数 per_obj.loop_num += int(loop_num) # 进行累加求值 try: ds.together_send() # 计算出来的指标 rep.status = True data = ds.data_response() # 提取指标 # 数据存储与计算 per_obj.success_req += data[0] # 成功请求数 per_obj.lose_req += data[1] # 失败请求数 per_obj.total_req += data[0] + data[1] # 总请求数 per_obj.total_time += data[2] # 总共花销的时间 per_obj.avg_time = per_obj.total_time / per_obj.loop_num # 平均花销的时间 # 以下数据 属于图表使用 per_obj.count_time = data[3] # 每次请求用时 per_obj.rps = onceNum / data[3] # 每次的并发数 / 每次请求用时 # 保存数据入库 per_obj.save() # 获取当前的系统时间 lt = '{0}{1}:{2}:{3}' localtime = time.localtime() if localtime.tm_hour < 12: lti = lt.format('上午', localtime.tm_hour, localtime.tm_min, localtime.tm_sec) elif 12 <= localtime.tm_hour < 14: lti = lt.format('中午', localtime.tm_hour, localtime.tm_min, localtime.tm_sec) else: lti = lt.format('下午', localtime.tm_hour, localtime.tm_min, localtime.tm_sec) # 将数据存入 前端回调类对象中(这里存在读写消耗) rep.data = [ per_obj.success_req, per_obj.lose_req, per_obj.total_req, per_obj.avg_time, per_obj.total_time, per_obj.oncenum ] rep.message = [per_obj.count_time, per_obj.rps, lti] # print(rep.data) rep.summary = '运行ing...' except (IndexError): rep.status = False rep.data = [] rep.summary = '运行错误!per_data_extract 接口请求失败。' return HttpResponse(json.dumps(rep.__dict__))