예제 #1
0
 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)
예제 #2
0
 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__))
예제 #3
0
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__))
예제 #4
0
def creat_excel(req):
    rep = BaseResponse()

    # 获取uid
    user_info = req.session['user_info']
    u_nid = user_info['nid']

    # 实例化对象 采用单例模式
    excel_analysis = ExcelAnalysis()

    # 如果post发送的请求直接执行 上传相关操作
    if req.method == 'POST':
        # 创建数据库对象
        obj_mi = models.ModalInfo.objects.get(user_info_id=u_nid)
        # 传入两个关键参数 excel解析对象 和 数据库对象
        try:
            # 返回的两个参数分别为 信息、状态
            message, flag = excel_file_upload(req, excel_analysis, obj_mi)

            if flag:
                rep.status = True
            else:
                rep.status = False

            rep.message = message
        except Exception as e:
            print("Excel上传报错内容为:", e)
            rep.message = "未知异常"
            rep.status = False

    return HttpResponse(json.dumps(rep.__dict__))
예제 #5
0
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__))
예제 #6
0
 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__))
예제 #7
0
    def post(self, *args, **kwargs):
        rep = BaseResponse()

        form = CommentForm()

        if form.valid(self):
            form._value_dict['ctime'] = datetime.datetime.now()

            conn = ORM.session()
            obj = ORM.Comment(user_info_id=self.session['user_info']['nid'],
                              news_id=form._value_dict['news_id'],
                              reply_id=form._value_dict['reply_id'],
                              content=form._value_dict['content'],
                              up=0,
                              down=0,
                              ctime=datetime.datetime.now())

            conn.add(obj)
            # 获取nid
            conn.flush()
            conn.refresh(obj)

            rep.data = {
                'user_info_id': self.session['user_info']['nid'],
                'username': self.session['user_info']['username'],
                'nid': obj.nid,
                'news_id': obj.news_id,
                'ctime': obj.ctime.strftime("%Y-%m-%d %H:%M:%S"),
                'reply_id': obj.reply_id,
                'content': obj.content,
            }
            # 将评论数+1
            conn.query(ORM.News).filter(
                ORM.News.nid == form._value_dict['news_id']).update(
                    {"comment_count": ORM.News.comment_count + 1},
                    synchronize_session="evaluate")
            conn.commit()
            conn.close()

            rep.status = True
        else:
            rep.message = form._error_dict
        print(rep.__dict__)
        self.write(json.dumps(rep.__dict__))
예제 #8
0
    def post(self, *args, **kwargs):
        rep = BaseResponse()

        form = IndexForm()
        if form.valid(self):
            # title,content,href,news_type,user_info_id

            input_dict = copy.deepcopy(form._value_dict)
            input_dict['ctime'] = datetime.datetime.now()
            input_dict['user_info_id'] = self.session['user_info']['nid']
            conn = ORM.session()
            conn.add(ORM.News(**input_dict))
            conn.commit()
            conn.close()
            rep.status = True
        else:
            rep.message = form._error_dict

        self.write(json.dumps(rep.__dict__))
예제 #9
0
파일: account.py 프로젝트: zyu911/chouti
    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__))
예제 #10
0
    def post(self, *args, **kwargs):
        rep = BaseResponse()
        form = account.RegisterForm()
        if form.valid(self):
            current_date = datetime.datetime.now()
            # timedelta(): used to express difference between two datetime values
            limit_day = current_date - datetime.timedelta(minutes=1)
            conn = ORM.session()
            # SendMsg表的邮箱、验证码、创建时间
            is_valid_code = conn.query(ORM.SendMsg).filter(
                ORM.SendMsg.email == form._value_dict['email'],
                ORM.SendMsg.code == form._value_dict['email_code'],
                ORM.SendMsg.ctime > limit_day).count()
            if not is_valid_code:
                rep.message['email_code'] = '邮箱验证码不正确或过期'
                self.write(json.dumps(rep.__dict__))
                return
            has_exists_email = conn.query(ORM.UserInfo).filter(
                ORM.UserInfo.email == form._value_dict['email']).count()
            if has_exists_email:
                rep.message['email'] = '邮箱已经存在'
                self.write(json.dumps(rep.__dict__))
                return
            has_exists_username = conn.query(ORM.UserInfo).filter(
                ORM.UserInfo.username == form._value_dict['username']).count()
            if has_exists_username:
                rep.message['email'] = '用户名已经存在'
                self.write(json.dumps(rep.__dict__))
                return
            form._value_dict['ctime'] = current_date
            form._value_dict.pop('email_code')
            obj = ORM.UserInfo(**form._value_dict)

            conn.add(obj)
            conn.flush()
            conn.refresh(obj)

            user_info_dict = {
                'nid': obj.nid,
                'email': obj.email,
                'username': obj.username
            }

            conn.query(ORM.SendMsg).filter_by(
                email=form._value_dict['email']).delete()
            conn.commit()
            conn.close()

            self.session['is_login'] = True
            self.session['user_info'] = user_info_dict
            rep.status = True

        else:
            rep.message = form._error_dict

        self.write(json.dumps(rep.__dict__))
예제 #11
0
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__))
예제 #12
0
    def post(self, *args, **kwargs):
        rep = BaseResponse()
        form = account.LoginForm()
        if form.valid(self):
            if form._value_dict['code'].lower() != self.session["CheckCode"].lower():
                rep.message = {'code': '验证码错误'}
                self.write(json.dumps(rep.__dict__))
                return
            conn = ORM.session()
            obj = conn.query(ORM.UserInfo).filter(
                or_(
                    and_(ORM.UserInfo.email == form._value_dict['user'],
                         ORM.UserInfo.password == form._value_dict['pwd']),
                    and_(ORM.UserInfo.username == form._value_dict['user'],
                         ORM.UserInfo.password == form._value_dict['pwd'])
                )).first()
            conn.close()
            if not obj:
                rep.message = {'user': '******'}
                self.write(json.dumps(rep.__dict__))
                return

            self.session['is_login'] = True
            self.session['user_info'] = obj.__dict__
            rep.status = True
        else:
            rep.message = form._error_dict
        self.write(json.dumps(rep.__dict__))
예제 #13
0
def register(request):
    """
    注册
    :param request:
    :return:
    """
    rep = BaseResponse()
    form = RegisterForm(request.POST)
    if form.is_valid():
        current_date = datetime.datetime.now()
        limit_day = current_date - datetime.timedelta(minutes=1)
        _value_dict = form.clean()

        is_valid_code = models.SendMsg.objects.filter(
            email=_value_dict['email'],
            code=_value_dict['email_code'],
            ctime__gt=limit_day).count()
        if not is_valid_code:
            rep.message['email_code'] = '邮箱验证码不正确或过期'
            return HttpResponse(json.dumps(rep.__dict__))

        has_exists_email = models.UserInfo.objects.filter(
            email=_value_dict['email']).count()

        if has_exists_email:
            rep.message['email'] = '邮箱已经存在'
            return HttpResponse(json.dumps(rep.__dict__))

        has_exists_username = models.UserInfo.objects.filter(
            username=_value_dict['username']).count()
        if has_exists_username:
            rep.message['email'] = '用户名已经存在'
            return HttpResponse(json.dumps(rep.__dict__))

        _value_dict['ctime'] = current_date
        _value_dict.pop('email_code')
        # 当前用户的所有信息
        obj = models.UserInfo.objects.create(**_value_dict)

        user_info_dict = {
            'nid': obj.nid,
            'email': obj.email,
            'username': obj.username
        }

        models.SendMsg.objects.filter(email=_value_dict['email']).delete()

        request.session['is_login'] = True
        request.session['user_info'] = user_info_dict
        rep.status = True

    else:
        error_msg = form.errors.as_json()
        rep.message = json.loads(error_msg)
    return HttpResponse(json.dumps(rep.__dict__))
예제 #14
0
파일: account.py 프로젝트: zyu911/chouti
    def post(self, *args, **kwargs):
        rep = BaseResponse()
        form = account.LoginForm()
        if form.valid(self):
            if form._value_dict['code'].lower(
            ) != self.session["CheckCode"].lower():
                rep.message = {'code': '验证码错误'}
                self.write(json.dumps(rep.__dict__))
                return

            obj = AccountServer().loginHandel(form._value_dict['user'],
                                              form._value_dict['user'],
                                              form._value_dict['pwd'])
            if not obj:
                rep.message = {'user': '******'}
                self.write(json.dumps(rep.__dict__))
                return
            user_info_dict = {
                'nid': obj.nid,
                'username': obj.username,
                'email': obj.email,
                'img': obj.img
            }
            self.session['is_login'] = True
            self.session['user_info'] = user_info_dict
            rep.status = True
        else:
            rep.message = form._error_dict
        self.write(json.dumps(rep.__dict__))
예제 #15
0
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__))
예제 #16
0
    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__))
예제 #17
0
def custom_file_upload(req):
    rep_cfu = BaseResponse()
    time.sleep(1)  # 让文件生成后再执行下载操作

    # 需要获取文件存储路径
    user_info = req.session['user_info']
    u_nid = user_info['nid']
    obj_ufp = models.UserFilesPaths.objects.get(user_info_id=u_nid)
    filePath = obj_ufp.word_resultFile_path

    if req.method == 'POST':
        f = open(filePath, 'wb')  #  打开即将要修改的文件
        try:
            file_obj = req.FILES.get('file')
            # print(file_obj,type(file_obj))  # 测试文件的类型
            for chunk in file_obj.chunks():
                f.write(chunk)
            rep_cfu.message = "修改文件上传成功!"
            rep_cfu.status = True
        except Exception as e:
            print("报错内容:", e)
            rep_cfu.message = "修改文件上传失败!"
            rep_cfu.status = False
        finally:
            f.close()

    return HttpResponse(json.dumps(rep_cfu.__dict__))
예제 #18
0
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__))
예제 #19
0
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格式返回给前端
예제 #20
0
def register(request):
    """用户注册"""
    rep = BaseResponse()
    form = RegisterForm(request.POST)
    if form.is_valid():
        # 如果格式正确,先检查验证码是否匹配或过期
        _value_dict = form.clean()
        current_date = datetime.datetime.now()
        limit_date = current_date - datetime.timedelta(minutes=5)
        is_valid_code = models.SendMsg.objects.filter(ctime__gt=limit_date,
                                                      email=_value_dict["email"],
                                                      code=_value_dict["email_code"])
        # 如果没有匹配的记录,则表示验证码错误或过期
        if not is_valid_code:
            rep.message["email_code"] = "验证码错误或已过期"
            return HttpResponse(json.dumps(rep.__dict__))

        # 防止注册过程中修改邮箱,再次验证邮箱是否已注册
        has_exists_email = models.UserInfo.objects.filter(email=_value_dict["email"]).count()
        if has_exists_email:
            rep.message["email"] = "邮箱已注册"
            return HttpResponse(json.dumps(rep.__dict__))

        # 检查用户名是否已存在
        has_exists_username = models.UserInfo.objects.filter(username=_value_dict["username"]).count()
        if has_exists_username:
            rep.message["username"] = "******"
            return HttpResponse(json.dumps(rep.__dict__))

        # 修改_value_dict字典信息,通过字典直接创建用户信息
        _value_dict["ctime"] = current_date
        _value_dict.pop("email_code")
        obj = models.UserInfo.objects.create(**_value_dict)
        user_info_dict = {"nid": obj.nid, "username": obj.username, "email": obj.email}

        # 删除SendMsg表中的记录
        models.SendMsg.objects.filter(email=_value_dict["email"]).delete()

        # 设置session,保存用户登录状态
        request.session["is_login"] = True
        request.session["user_info"] = user_info_dict

        rep.status = True

        # 发送邮件通知注册成功
        send_email(_value_dict["email"], "恭喜您注册成功!")
    else:
        # 如果格式不正确,则返回错误信息
        # 先将错误信息转换成字符串,再转换成字典
        error_str = form.errors.as_json()
        rep.message = json.loads(error_str)
    return HttpResponse(json.dumps(rep.__dict__))
예제 #21
0
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__))
예제 #22
0
def login(req):
    '''
    用户登录 并且在登录后初始化各个表数据
    :param req:
    :return:
    '''

    rep = BaseResponse()
    form = LoginForm(req.POST)
    if form.is_valid():
        _value_dict = form.clean()
        # print(_value_dict)
        if _value_dict['code'].lower() != req.session['CheckCode'].lower():
            rep.message = {'code': [{'message': '验证码错误'}]}
            return HttpResponse(json.dumps(rep.__dict__))
        '''
        如果验证码正确,则进行Q查询
        '''
        from django.db.models import Q
        con = Q()
        q1 = Q()
        q2 = Q()

        q1.connector = 'AND'  # 在q1中创建逻辑关系符 ,然后把数据库中的值与用户输入的值进行比较
        q1.children.append(('email', _value_dict['user']))
        q1.children.append(('password', _value_dict['pwd']))

        q2.connector = 'AND'
        q2.children.append(('username', _value_dict['user']))
        q2.children.append(('password', _value_dict['pwd']))

        con.add(q1, 'OR')
        con.add(q2, 'OR')

        obj = models.UserInfo.objects.filter(con).first()

        if not obj:
            rep.message = {'user': [{'message': '用户名或邮箱或密码错误!'}]}
            return HttpResponse(json.dumps(rep.__dict__))

        req.session['is_login'] = True
        req.session['user_info'] = {
            'nid': obj.nid,
            'email': obj.email,
            'username': obj.username
        }

        rep.status = True
        # 表检查
        table_verify(obj)
    else:
        error_msg = form.errors.as_json()
        rep.message = json.loads(error_msg)

    return HttpResponse(json.dumps(rep.__dict__))
예제 #23
0
    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__))
예제 #24
0
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__))
예제 #25
0
 def post(self, *args, **kwargs):
     # 定义给前端的返回值对象
     rep = BaseResponse()
     # 声明登陆表单,每个表单内包含了预先定义的验证域
     form = account.LoginForm()
     # 表单的valid()方法会遍历表单内所有的验证域,都满足的话才会返回True
     if form.valid(self):
         # 判断验证码
         print(form._value_dict['code'])
         print(self.session["CheckCode"])
         print(self.session["CheckCode"])
         if form._value_dict['code'].lower(
         ) != self.session["CheckCode"].lower():
             rep.message = {'code': '验证码错误'}
             self.write(json.dumps(rep.__dict__))
             return
         # 验证成功,与数据库建立连接
         conn = ORM.session()
         # 邮箱/密码或用户名/密码匹配任意一对即可
         obj = conn.query(ORM.UserInfo).filter(
             or_(
                 # 邮箱/密码
                 and_(ORM.UserInfo.email == form._value_dict['user'],
                      ORM.UserInfo.password == form._value_dict['pwd']),
                 # 用户名/密码
                 and_(ORM.UserInfo.username == form._value_dict['user'],
                      ORM.UserInfo.password == form._value_dict['pwd']
                      ))).first()
         # 断开与数据库的连接
         conn.close()
         # 如果在数据库中没有找到用户信息
         if not obj:
             rep.message = {'user': '******'}
             self.write(json.dumps(rep.__dict__))
             return
         # 数据库中有匹配的信息,则将用户登陆状态及用户信息存入session,并写给前端状态码
         # 这里ORM连接的__dict__属性返回的字典中有个键是'_sa_instance_state'
         # 其值是一个sqlalchemy对象
         # 我们自定义session时,__setitem__方法会进行要设置值是否是字典的判断
         # 如果是字典的话,会对value使用dumps方法,而json并不知道如何转换sqlalchemy对象
         # 这个错误排查了有一会儿才确定怎么回事
         # 话说我为什么要把obj.__dict__写入session?里面有敏感信息
         # 而且也没什么用
         self.session['is_login'] = True
         self.session['user_info'] = obj.__dict__
         rep.status = True
     else:
         rep.message = form._error_dict
     self.write(json.dumps(rep.__dict__))
예제 #26
0
def login(request):
    """
    用户登陆
    :param request:
    :return:
    """
    rep = BaseResponse()
    form = LoginForm(request.POST)
    if form.is_valid():
        _value_dict = form.clean()
        if _value_dict['code'].lower() != request.session["CheckCode"].lower():
            rep.message = {'code': [{'message': '验证码错误'}]}
            return HttpResponse(json.dumps(rep.__dict__))

        from django.db.models import Q

        con = Q()
        q1 = Q()
        q1.connector = 'AND'
        q1.children.append(('email', _value_dict['user']))
        q1.children.append(('password', _value_dict['pwd']))

        q2 = Q()
        q2.connector = 'AND'
        q2.children.append(('username', _value_dict['user']))
        q2.children.append(('password', _value_dict['pwd']))

        con.add(q1, 'OR')
        con.add(q2, 'OR')

        obj = models.UserInfo.objects.filter(con).first()
        if not obj:
            rep.message = {'user': [{'message': '用户名邮箱或密码错误'}]}
            return HttpResponse(json.dumps(rep.__dict__))

        request.session['is_login'] = True
        request.session['user_info'] = {
            'nid': obj.nid,
            'email': obj.email,
            'username': obj.username
        }
        rep.status = True
    else:
        error_msg = form.errors.as_json()
        rep.message = json.loads(error_msg)

    return HttpResponse(json.dumps(rep.__dict__))
예제 #27
0
    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__))
예제 #28
0
def login(request):
    """用户登录"""
    rep = BaseResponse()
    form =LoginForm(request.POST)
    if form.is_valid():
        # 先检查图形验证码是否匹配
        _value_dict = form.clean()
        if _value_dict["code"].lower() != request.session["CheckCode"].lower():
            rep.message = {"code": [{"message": "验证码错误"}]}

        # 如果验证码正确,数据库中匹配用户名&密码或邮箱&密码
        con = Q()
        q1 = Q()
        q1.connector = "AND"
        q1.children.append(("email", _value_dict["user"]))
        q1.children.append(("password", _value_dict["pwd"]))

        q2 = Q()
        q2.connector = "AND"
        q2.children.append(("username", _value_dict["user"]))
        q2.children.append(("password", _value_dict["pwd"]))

        con.add(q1, "OR")
        con.add(q2, "OR")

        obj = models.UserInfo.objects.filter(con).first()
        if not obj:
            rep.message = {"user": [{"message": "用户名邮箱或密码错误"}]}
            return HttpResponse(json.dumps(rep.__dict__))

        # 如果验证正确,设置session
        request.session["is_login"] = True
        request.session["user_info"] = {'nid': obj.nid, 'email': obj.email, 'username': obj.username}

        rep.status = True
    else:
        error_str = form.errors.as_json()
        rep.message = json.loads(error_str)
    return HttpResponse(json.dumps(rep.__dict__))
예제 #29
0
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__))
예제 #30
0
def index(request):
    """
    抽屉主页
    :param request:
    :return:
    """
    if request.method == 'GET':
        page = request.GET.get('page', 1)
        all_count = models.News.objects.all().count()

        obj = Pagination(page, all_count)

        sql = """
        SELECT
            "web_news"."nid",
            "web_news"."title",
            "web_news"."url",
            "web_news"."content",
            "web_news"."ctime",
            "web_userinfo"."username",
            "web_newstype"."caption",
            "web_news"."favor_count",
            "web_news"."comment_count",
            "web_favor"."nid"
        FROM
            "web_news"
        LEFT OUTER JOIN "web_userinfo" ON (
            "web_news"."user_info_id" = "web_userinfo"."nid"
        )
        LEFT OUTER JOIN "web_newstype" ON (
            "web_news"."news_type_id" = "web_newstype"."nid"
        )
        LEFT OUTER JOIN "web_favor" ON
            "web_news"."nid" = "web_favor"."news_id"
        and
            "web_favor"."user_info_id" = %s

        LIMIT 10 OFFSET %s
        """

        from django.db import connection

        cursor = connection.cursor()
        cursor.execute(sql, [request.session['user_info']['nid'] if request.session.get('user_info', None) else 0,
                             obj.start])
        result = cursor.fetchall()
        str_page = obj.string_pager('/index/')

        return render(request, 'index.html', {'str_page': str_page, 'news_list': result})
    else:
        rep = BaseResponse()
        form = IndexForm(request.POST)
        if form.is_valid():
            _value_dict = form.clean()
            input_dict = copy.deepcopy(_value_dict)
            input_dict['ctime'] = datetime.datetime.now()
            input_dict['user_info_id'] = request.session['user_info']['nid']
            models.News.objects.create(**input_dict)
            rep.status = True
        else:

            error_msg = form.errors.as_json()
            rep.message = json.loads(error_msg)

        return HttpResponse(json.dumps(rep.__dict__))