Exemplo n.º 1
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

            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__))
Exemplo n.º 2
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__))
Exemplo n.º 3
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__))
Exemplo n.º 4
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__))
Exemplo n.º 5
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__))
Exemplo n.º 6
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__))
Exemplo n.º 7
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__))
Exemplo n.º 8
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__))
Exemplo n.º 9
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__))
Exemplo n.º 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__))
Exemplo n.º 11
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__))
Exemplo n.º 12
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__))
Exemplo n.º 13
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__))
Exemplo n.º 14
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__))
Exemplo n.º 15
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__))
Exemplo n.º 16
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__))
Exemplo n.º 17
0
def register(req):
    '''
    注册
    :param req:
    :return:
    '''
    rep = BaseResponse()
    form = RegisterForm(req.POST)
    if form.is_valid():
        current_date = datetime.datetime.now()  # 创建时间
        limit_day = current_date - datetime.timedelta(
            minutes=1)  # 一分钟 (判断验证码是否过期)
        _value_dict = form.clean()
        # 临时表中查询时间超过1分钟的数据
        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')
        '''
            1.把得到的正确数据写入数据库
            2.获取当前用户的所有信息,以便注册成功后直接登录;
            3.删除临时表中无用的验证码数据;
        '''
        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()

        req.session['is_login'] = True
        req.session['user_info'] = user_info_dict
        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__))
Exemplo n.º 18
0
def update_item(req):
    '''
    1. 初始化需要爬虫的准备数据
    2.更新项目 使用get请求 ,爬取项目相关数据 用post请求
    :param req:
    :return:
    '''
    rep = BaseResponse()

    # 旧禅道 爬虫信息初始化
    login_url = r'http://it.bbdservice.com:8280/zentao/user-login.html'
    pro_url = r'http://it.bbdservice.com:8280/zentao/product-all-0-noclosed-order_desc-13-100-1.html'
    bug_url = r'http://it.bbdservice.com:8280/zentao/bug-browse-%s-0-all-0--598-500-1.html'

    user_info = req.session['user_info']
    u_nid = user_info['nid']

    user_obj = models.UserInfo.objects.get(nid=u_nid)

    username = user_obj.username
    password = user_obj.password

    num = req.POST.get('itemId')  # 获取用户选择的项目ID

    # 爬虫信息初始化
    ss = SpiderBugInfo(username, password, num, login_url, pro_url, bug_url)
    # 数据库信息初始化
    mbi = MysqlBugInfo(num)

    if req.method == 'GET':
        zentao_id = req.GET.get('zentao_id')  # 获取用户选择 禅道版本ID号
        print("zentao_id_get:", zentao_id)
        # 根据不同的 禅道版本选择 不同的方式获取项目信息
        if zentao_id == '1':
            try:
                pro_item_1 = ss.product_info()
                models.SpiderProduct.objects.create(pro_info=pro_item_1)
                rep.status = True
                rep.data = pro_item_1
                rep.message = "数据成功获取!"
            except Exception as e:
                print('报错信息:', e)
                rep.status = False
                rep.message = "爬取数据,出错!"
        elif zentao_id == '2':
            try:
                pro_item_2 = mbi.product_info()
                models.SpiderProduct.objects.create(pro_info=pro_item_2)
                rep.status = True
                rep.data = pro_item_2
                rep.message = "数据成功获取!"
            except Exception as e:
                print('报错信息:', e)
                rep.status = False
                rep.message = "远程数据库,拒绝访问!"

        else:
            rep.status = False
            rep.message = "无项目信息!~"

    if req.method == "POST":
        models_obj = models.SpiderTable.objects.get(user_info_id=u_nid)
        zentao_id = req.POST.get('zentao_id')  # 获取用户选择 禅道版本ID号
        print("zentao_id_post:", zentao_id)

        # 根据不同的 禅道版本选择 不同的方式获取BUG信息
        if zentao_id == '1':
            try:
                bug_lis, not_close = ss.bug_info()
                models_obj.bug_info_close = bug_lis
                models_obj.bug_info_not_close = not_close
                models_obj.save()

                rep.status = True
                rep.message = '数据爬取成功'
            except IndexError as e:
                print("报错信息:", e)
                rep.message = '请选择项目 或 该项目内容为空!'
                rep.status = False
        elif zentao_id == '2':
            try:
                bug_lis, not_close = mbi.bug_info()
                models_obj.bug_info_close = bug_lis
                models_obj.bug_info_not_close = not_close
                models_obj.save()

                rep.status = True
                rep.message = '数据爬取成功'
            except IndexError as e:
                print("报错信息:", e)
                rep.message = '锅佬倌,点下拉框选项目!'
                rep.status = False
        else:
            rep.status = False
            rep.message = "无BUG信息!~"

        # print("bug_lis",bug_lis)
        # print("not_close",not_close)
    return HttpResponse(json.dumps(rep.__dict__))
Exemplo n.º 19
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__))