示例#1
0
    def put(self, request, *args, **kwargs):
        """
            单条查询详细信息
            传入当前点击的机构名称  可换成机构号
            传入整形数字为参照,0、1、2、   详情、通过、退回
        """
        user = request.user
        data = request.PUT
        ins_nm = data.get("keyword", "")
        state = data.get("state", 0)

        retu_data = dict()
        try:
            acceptcheck = AcceptCheck.objects.get(ins_nm=ins_nm, check_state=0)
        except Exception as e:
            return json_response({"msg": str(e)})
        if state == 0:
            if acceptcheck:
                try:
                    soft_info = SoftInfo.objects.get(acceptcheck=acceptcheck)
                except Exception as e:
                    return json_response({"msg": str(e)})
                retu_data = {
                    "id": acceptcheck.id,
                    "ins_nm": acceptcheck.ins_nm,
                    "reply": acceptcheck.reply,
                    "contacts": acceptcheck.contacts,
                    "phone": acceptcheck.phone,
                    "email": acceptcheck.email,
                    "computer_adr": acceptcheck.computer_adr,
                    "company_adr": acceptcheck.company_adr,
                    "zip_code": acceptcheck.zip_code,
                    "fax": acceptcheck.fax,
                    "soft_nm": soft_info.soft_nm,
                    "soft_ty": soft_info.soft_ty,
                    "mid_ty": soft_info.mid_ty,
                    "database": soft_info.database,
                    "operat_sys": soft_info.operat_sys,
                    "cd_num": soft_info.cd_num,
                    "instruct_num": soft_info.instruct_num,
                    "enclosure_num": soft_info.enclosure_num,
                    "acces_sys": soft_info.acces_sys,
                    "acce_ty": soft_info.acces_type,
                    "test_descrip": soft_info.test_descrip
                }
        elif state == 1:
            acceptcheck.check_state = 1
            acceptcheck.save()
            username_recv = acceptcheck.email
            content = "您所提交的测试申请以审核成功,请注意查看官网动态"
            email(username_recv, content)
            retu_data["state"] = "200"
        else:
            acceptcheck.check_state = 2
            acceptcheck.save()
            username_recv = acceptcheck.email
            content = "您所提交的测试申请被退回,请注意查看官网动态"
            email(username_recv, content)
            retu_data["state"] = "200"
        return json_response(retu_data)
示例#2
0
def search(keyword, search_date, accept_info, retu_data):
    try:
        if keyword:
            all_ins = Insinfo.objects.filter(ins_nm__contains=keyword)
            for per_ins in all_ins:
                try:
                    apply = AcceptCheck.objects.get(check_state=0, ins_nm=per_ins.ins_nm)
                    accept_info.append(apply)
                except:
                    pass
        if search_date:
            start_date = datetime.strptime(search_date.split()[0], '%Y-%m-%d')
            end_date = datetime.strptime(search_date.split()[2], '%Y-%m-%d')
            if accept_info:
                for per_ins in accept_info:
                    if not (per_ins.start_time >= start_date and per_ins.end_time <= end_date):
                        accept_info.remove(per_ins)
            else:
                accept_info = AcceptCheck.objects.filter(check_state=0, apply_date__gte=start_date,
                                                            apply_date__lte=end_date)
    except Exception as e:
        return json_response({"msg": str(e)})

    if not accept_info:
        return json_response(retu_data)
    return accept_info
示例#3
0
def view_show(show):
    log_event(request, "ViewShow")
    add_epguides_key_to_redis(show)
    try:
        return json_response(get_show_by_key(show).get_show_data())
    except EpisodeNotFoundException:
        return json_response({'error': 'Show not found'}, 404)
    except SeasonNotFoundException:
        return json_response({'error': 'Season not found'}, 404)
示例#4
0
def last(show):
    log_event(request, "ViewShowLastEpisode")
    add_epguides_key_to_redis(show)
    try:
        return json_response({'episode': get_show_by_key(show).last_episode()})
    except EpisodeNotFoundException:
        return json_response({'error': 'Show not found'}, 404)
    except SeasonNotFoundException:
        return json_response({'error': 'Season not found'}, 404)
示例#5
0
 def delete(self, request, *args, **kwargs):
     user = request.user
     file_name = request.DELETE.get("file_nm", "")
     try:
         file_obj = TestFile.objects.get(file_nm=file_name)
         os.remove(file_obj.file_url)
         TestFile.objects.get(file_nm=file_name).delete()
         return json_response({"msg": "删除成功"})
     except Exception as e:
         return json_response({"msg": str(e)})
示例#6
0
 def get(self, request, *args, **kwargs):
     user = request.user
     data = {
         "page_per": [],
         "apply_info": [],
         "user": [],
     }
     error = {"error": "请求数据不存在"}
     try:
         cur_apply = ApplyInfo.objects.all().exclude(
             Q(check_state=1) | Q(check_state=2))
         # 构建分页器对象,cur_apply=所有数据,3=每页显示的个数
         paginator = Paginator(cur_apply, 10)
         num_page = request.GET.get("page", 1)
         page_nums = paginator.count
         data["user"] = [{
             "username": user.username,
             "role": user.role,
             "eamil": user.email,
         }]
         data["page_per"] = [{
             "page_nums": page_nums,
         }]
         try:
             content = paginator.page(num_page)
         except EmptyPage:
             return json_response(error)
         else:
             for all_ins in content.object_list:
                 print(all_ins)
                 new_dic = dict()
                 new_dic["id"] = all_ins.id
                 new_dic["ins_name"] = all_ins.ins.ins_nm
                 new_dic["ins_cd"] = all_ins.ins.ins_cd
                 new_dic["port"] = all_ins.ins.port
                 new_dic["access_port"] = all_ins.ins.access_port
                 new_dic["phone"] = all_ins.phone
                 new_dic["email"] = all_ins.email
                 new_dic["bank_num"] = all_ins.bank_num
                 new_dic["test_num"] = all_ins.test_num
                 new_dic["production_ccpc"] = all_ins.production_ccpc
                 new_dic["start_time"] = all_ins.start_time.strftime(
                     "%Y-%m-%d")
                 new_dic["end_time"] = all_ins.end_time.strftime("%Y-%m-%d")
                 new_dic["soft_nm"] = all_ins.soft_nm
                 new_dic["mid_message"] = all_ins.mid_message
                 new_dic["mid_apply"] = all_ins.mid_apply
                 new_dic["first_access"] = all_ins.first_access
                 new_dic["net_ty"] = all_ins.net_ty
                 new_dic["access_obj"] = all_ins.access_obj
                 data["apply_info"].append(new_dic)
     except Exception as e:
         print(e)
         # return json_response({"msg": str(e)})
     return json_response(data)
示例#7
0
    def post(self, request, *args, **kwargs):
        """
        :param request:
        :param args: end_time(有效时间), up_type(上传功能传参数, 更新时不传参) file_name(更新时传递此参数,文件名称)
        """
        user = request.user
        end_time = request.POST.get("end_time")
        up_type = request.POST.get("up_type", "")

        ret = {"status": "0"}
        target = "media/upload/testing/"

        try:
            # 获取文件对象
            file_obj = request.FILES.get("file")
            raw_name = file_obj.name
        except Exception as e:
            ret["summary"] = str(e)
        else:

            # 检查目录存不存在,如果不存在新建一个
            if not os.path.exists(os.path.dirname(target)):
                os.makedirs(target)
            file_path = os.path.join(target, raw_name)
            with open(file_path, "wb") as f:
                for chunk in file_obj.chunks():  # chuck是分块写入文件
                    f.write(chunk)
            ret["status"] = "200"

            if up_type:
                try:
                    TestFile.objects.get(up_user=user.username,
                                         file_nm=raw_name)
                except:
                    test_file = TestFile()
                    test_file.up_user = user
                    test_file.file_nm = raw_name
                    test_file.file_url = file_path
                    test_file.end_time = end_time
                    test_file.save()
                    ret["msg"] = "上传成功"
                else:
                    return json_response({"msg": "此文件已存在"})
            else:
                file_name = request.POST.get("file_nm", "")
                try:
                    TestFile.objects.filter(up_user=user,
                                            file_nm=file_name).update(
                                                file_nm=raw_name,
                                                file_url=file_path)
                    ret["msg"] = "更新成功"
                except Exception as e:
                    return json_response({"msg": str(e)})

        return json_response(ret)
示例#8
0
def released(show, season, episode):
    log_event(request, "ViewReleased")
    add_epguides_key_to_redis(show)
    try:
        show = get_show_by_key(show)
        return json_response(
            {'status': show.episode_released(int(season), int(episode))})
    except EpisodeNotFoundException:
        return json_response({'error': 'Show not found'}, 404)
    except SeasonNotFoundException:
        return json_response({'error': 'Season not found'}, 404)
示例#9
0
def next_from_given_episode(show, season, episode):
    log_event(request, "ViewNextFromGivenEpisode")
    add_epguides_key_to_redis(show)
    try:
        show = get_show_by_key(show)
        return json_response(
            {'episode': show.get_episode(int(season), int(episode)).next()})
    except EpisodeNotFoundException:
        return json_response({'error': 'Show not found'}, 404)
    except SeasonNotFoundException:
        return json_response({'error': 'Season not found'}, 404)
示例#10
0
def episode(show, season, episode):
    log_event(request, "ViewEpisode")
    add_epguides_key_to_redis(show)
    try:
        return json_response({
            'episode':
            get_show_by_key(show).get_episode(int(season), int(episode))
        })
    except EpisodeNotFoundException:
        return json_response({'error': 'Show not found'}, 404)
    except SeasonNotFoundException:
        return json_response({'error': 'Season not found'}, 404)
示例#11
0
def next_released_from_given_episode(show, season, episode):
    log_event(request, "ViewNextReleasedFromGivenEpisode")
    add_epguides_key_to_redis(show)
    try:
        show = get_show_by_key(show)
        next_episode = show.get_episode(season, episode).next()
        if not next_episode:
            raise EpisodeNotFoundException
        return json_response({'status': next_episode.released()})
    except EpisodeNotFoundException:
        return json_response({'error': 'Show not found'}, 404)
    except SeasonNotFoundException:
        return json_response({'error': 'Season not found'}, 404)
示例#12
0
 def put(self, request, *args, **kwargs):
     """
         预览用户上传pdf文件, 筛选条件为行号 不是机构名称
     """
     # user = request.user
     data = request.PUT
     info_id = data.get("id")
     try:
         ins = ApplyInfo.objects.get(id=info_id).ins
         file_url = UserForm.objects.get(
             bank_num=ins.pay_num).file_url.split("/", 4)[-1]
     except Exception as e:
         return json_response({"msg": str(e)})
     return json_response({"url": file_url})
示例#13
0
    def get(self, request, *args, **kwargs):
        user = request.user
        retu_data = {
            "retu_info": [],
            "page_nums": "",
        }
        accept_info = AcceptCheck.objects.filter(check_state=0)
        if not accept_info:
            return json_response(retu_data)

        # 构建分页器对象,cur_apply=所有数据,2=每页显示的个数
        paginator = Paginator(accept_info, 10)
        num_page = request.GET.get("page", 1)
        page_nu = paginator.count
        retu_data["page_nums"] = page_nu
        try:
            content = paginator.page(num_page)
        except EmptyPage:
            content = paginator.page(paginator.num_pages)
        for acceptcheck in content.object_list:
            try:
                soft_info = SoftInfo.objects.get(acceptcheck=acceptcheck)
            except Exception as e:
                return json_response({"msg": str(e)})
            retu_dic = {
                "id": acceptcheck.id,
                "ins_nm": acceptcheck.ins_nm,
                "reply": acceptcheck.reply,
                "contacts": acceptcheck.contacts,
                "phone": acceptcheck.phone,
                "email": acceptcheck.email,
                "computer_adr": acceptcheck.computer_adr,
                "company_adr": acceptcheck.company_adr,
                "zip_code": acceptcheck.zip_code,
                "fax": acceptcheck.fax,
                "soft_nm": soft_info.soft_nm,
                "soft_ty": soft_info.soft_ty,
                "mid_ty": soft_info.mid_ty,
                "database": soft_info.database,
                "operat_sys": soft_info.operat_sys,
                "cd_num": soft_info.cd_num,
                "instruct_num": soft_info.instruct_num,
                "enclosure_num": soft_info.enclosure_num,
                "acces_sys": soft_info.acces_sys,
                "acce_ty": soft_info.acces_type,
                "test_descrip": soft_info.test_descrip
            }
            retu_data["retu_info"].append(retu_dic)
            retu_data["status"] = "200"
        return json_response(retu_data)
示例#14
0
def data_put(path):
    """
    Handle HTTP PUT for data

    Overwrite the existing resource or create a new one. In either case the
    received object will be validated against the schema for this resource type.
    If no schema exists, will return an error.

    Returns the path of the file that was written and a bulk write token which
    can be used to add more writes to the branch corresponding to this token.

    Example to create or update student with id 1234:
    PUT /student/1234
    """
    # check schema exists, and validate against schema
    # if ok, create resource
    data = yaml.load(request.get_json())
    # check if the request is adding to an existing branch
    if WRITE_TOKEN_HEADER in request.headers:
        token = request.headers[WRITE_TOKEN_HEADER]
    else:
        token = str(uuid4())

    file_path = os.path.join('data', path) + config['DATA_FILE_EXT']
    repo.write_file(file_path, data, token)
    return utils.json_response({'href': path, WRITE_TOKEN_HEADER: token})
示例#15
0
    def post(self, request, *args, **kwargs):
        user = request.user
        data = request.POST
        keyword = data.get("search_keyword", "")
        search_date = data.get("search_date", "")
        column = data.get("search_column", "")
        apply_info = []
        retu_data = {"retu_info": [], "status": "0"}
        search(keyword, search_date, column, apply_info, retu_data)

        for ai in apply_info:
            pri_time = int(ai.start_time.strftime('%m'))
            retu_dic = dict()
            retu_dic["id"] = ai.id
            retu_dic["ins_nm"] = ai.ins.ins_nm
            retu_dic["ins_sysytem"] = ai.ins.ins_sysytem
            for j in range(1, 13):
                if j > pri_time:
                    start = j
                else:
                    start = pri_time
                for per_mo in range(start, 14):
                    month = ""
                    if per_mo == j:
                        month = "√"
                    retu_dic[str(j)] = month
                    break
            retu_data["retu_info"].append(retu_dic)
        return json_response(retu_data)
示例#16
0
def create_log_record():
    """
    Добавляет новую запись лога в таблицу log, с содержанием,
    полученным в теле запроса
    :return: dictionary {"code_error": "Created_new_log_record"}
    """
    req = request.json
    time_created = req["time_created"]
    logger_name = req["logger_name"]
    level_name = req["level_name"]
    file_name = req["file_name"]
    func_name = req["func_name"]
    line_number = req["line_number"]
    msg = req["msg"]
    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute(
        "INSERT INTO log (time_created, logger_name, level_name, file_name, func_name, line_number, msg)"
        " VALUES (%s, %s, %s, %s, %s, %s, %s)",
        (time_created, logger_name, level_name, file_name, func_name,
         line_number, msg),
    )
    cur.close()
    conn.commit()
    conn.close()

    return json_response(json.dumps({"code_error": "Created_new_log_record"}))
示例#17
0
def get_author_id(author_id):
    """
    По запросу GET с author_id автора найти его в базе и вернуть словарь с данными
    :param author_id:
    :return: Dictionary author_dic
    """
    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute("SELECT * FROM author WHERE id = %s", (author_id, ))
    auth_cur = cur.fetchone()
    if auth_cur is not None:
        author_dic = tp_to_dict(auth_cur, cur)
        return json_response(json.dumps(author_dic))
    cur.close()
    conn.close()
    return json_response(json.dumps({"author_id": "Not_Found"}))
示例#18
0
def discover_shows():
    result = []
    log_event(request, "ViewShowsOverview")

    for epguides_name in list_all_epguides_keys_redis():
        try:
            show = {
                'episodes':
                "{0}show/{1}/".format(app.config['BASE_URL'], epguides_name),
                'first_episode':
                "{0}show/{1}/first/".format(app.config['BASE_URL'],
                                            epguides_name),
                'next_episode':
                "{0}show/{1}/next/".format(app.config['BASE_URL'],
                                           epguides_name),
                'last_episode':
                "{0}show/{1}/last/".format(app.config['BASE_URL'],
                                           epguides_name),
                'epguides_url':
                "http://www.epguides.com/{0}".format(epguides_name)
            }
            result.append(show)
        except EpisodeNotFoundException:
            continue

    return json_response(result)
示例#19
0
    def post(self, request, *args, **kwargs):
        news_check = request.POST
        data = {"statu": "200"}
        check_state = news_check.get("check_state")
        info_id = news_check.get("id")

        ApplyInfo.objects.filter(id=info_id).update(check_state=check_state)
        if ApplyInfo.objects.get(id=info_id).check_state == 1:
            # 邮箱服务器地址
            mailserver = "smtp.163.com"

            username_sender = "*****@*****.**"
            password = "******"
            username_recv = "*****@*****.**"
            mail = MIMEText("您所提交的测试申请以审核,请注意查看官网动态")
            mail["Subject"] = "上海票据交易所回复邮件"
            mail["From"] = username_sender  # 发件人
            mail["To"] = username_recv
            smtp = smtplib.SMTP(mailserver, port=25)
            smtp.login(username_sender, password)  # 登录邮箱
            smtp.sendmail(
                username_sender, username_recv,
                mail.as_string())  # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
            smtp.quit()  # 发送完毕后退出smtp
            print('success')
        return json_response(data)
示例#20
0
 def get(self, request, *args, **kwargs):
     user = request.user
     now_time = datetime.now()
     try:
         all_txt = TestFile.objects.filter(end_time__gte=now_time)
     except Exception as e:
         return json_response({"msg": str(e)})
     retu_data = dict()
     retu_data["user_nm"] = user.username
     retu_data["file_text"] = [{
         "file_name": item.file_nm,
         "date": item.up_date.strftime("%Y-%m-%d"),
         "up_user": item.up_user,
         "status": item.check_status
     } for item in all_txt]
     return json_response(retu_data)
示例#21
0
def data_get(path):
    """
    HTTP method GET for data
    """

    metadata = {}

    file_path = os.path.join('data', path)
    latest_version = repo.get_latest_commit()
    # default request version to the latest
    version = latest_version
    # check if the request specified a version via header
    accept_pattern = re.compile('application/(.+)\+json')
    match = accept_pattern.match(request.headers['Accept'])
    if match is None:
        match = request.accept_mimetypes.best_match(['application/json'])
        if match is None:
            raise wz_err.NotAcceptable
    else:
        if match.group(2) is not None:
            cid = match.group(2)
            try:
                version = repo.get_commit(cid)
            except (KeyError, ValueError) as e:
                raise wz_err.NotAcceptable

    if repo.path_files(file_path + config['DATA_FILE_EXT'], version.id) is None:
        # .yml file doesn't exist, check if path matches a directory
        f_list = repo.path_files(file_path, version.id)
        if f_list is None:
            raise wz_err.NotFound
        data = utils.file_list_to_links(f_list, request.host_url, 'data/')

        metadata['data_type'] = 'directory listing'
    else:
        raw = repo.file_contents(file_path + config['DATA_FILE_EXT'], version.id)
        data = yaml.load(raw)
        data = utils.refs_to_links(data, request.host_url)

        metadata['data_type'] = 'file content'
        metadata['version'] = {
            'id': str(version.id),
            'date': datetime.fromtimestamp(version.commit_time).isoformat()
        }
        if version.id != latest_version.id:
            metadata['latest_version'] = {
                'id': str(latest_version.id),
                'date': datetime.fromtimestamp(latest_version.commit_time).isoformat()
            }

    ret_obj = {
        'data': data,
        'metadata': metadata
    }
    return utils.json_response(ret_obj)
示例#22
0
    def get(self, request, *args, **kwargs):
        username = request.session.get("username")
        try:
            user = Commentuser.objects.get(username=username)
            ins_nm = user.ins.ins_nm
            acceptcheck = AcceptCheck.objects.get(ins_nm=ins_nm)
            softinfo = SoftInfo.objects.get(acceptcheck=acceptcheck)
        except Exception as e:
            return json_response({"msg": str(e)})

        # 打印模板
        path = "media/upload/apply_temp/技术验收软件信息表01.docx"
        # 创建邮件合并文档并查看所有字段
        document_1 = MailMerge(path)
        document_1.merge(
            ins_nm=ins_nm,
            company_adr=acceptcheck.company_adr,
            computer_adr=acceptcheck.computer_adr,
            zip_code=acceptcheck.zip_code,
            fax=acceptcheck.fax,
            contacts=acceptcheck.contacts,
            phone=acceptcheck.phone,
            email=acceptcheck.email,
            reply=acceptcheck.reply,
            soft_nm=softinfo.soft_nm,
            soft_ty=softinfo.soft_ty,
            database=softinfo.database,
            operat_sys=softinfo.operat_sys,
            cd_num=softinfo.cd_num,
            instruct_num=softinfo.instruct_num,
            enclosure_num=softinfo.enclosure_num,
            acces_sys=softinfo.acces_sys,
            acce_ty=acceptcheck.acce_ty,
            pro_line_num=softinfo.pro_line_num,
            pro_acc_num=softinfo.pro_acc_num,
            test_line_num=softinfo.test_line_num,
            test_acc_num=softinfo.test_acc_num,
            front_info=softinfo.front_info,
            MBFE=softinfo.MBFE,
            apply_mid=softinfo.apply_mid,
            message_mid=softinfo.message_mid,
        )
        target = 'media/upload/tec_accept/'
        raw_name = ins_nm + ".docx"
        if not os.path.exists(os.path.dirname(target)):
            os.makedirs(target)
        file_path = os.path.join(target, raw_name)
        document_1.write(file_path)

        file = open(file_path, 'rb')
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename=' + raw_name
        return response
示例#23
0
    def put(self, request, *args, **kwargs):
        """
            查询详细信息
        """
        user = request.user
        data = request.PUT
        keyword = data.get("search_keyword", "")
        search_date = data.get("search_date", "")
        column = data.get("search_column", "")
        retu_data = {"retu_info": [], "status": "0"}

        apply_info = []
        search(keyword, search_date, column, apply_info, retu_data)
        for ai in apply_info:
            retu_dic = dict()
            netinfo = NetInfo.objects.get(aply_info=ai)
            for_pro = FornPro.objects.get(aply_info=ai)

            retu_dic["id"] = ai.id
            retu_dic["ins_nm"] = ai.ins.ins_nm
            retu_dic["contact"] = [{
                "name": items.name,
                "role": items.role,
                "phone": items.phone,
                "email": items.email
            } for items in ai.ins.contactsinfo_set.all()]
            retu_dic["net_ty"] = ai.net_ty
            retu_dic["IP_R2C1"] = netinfo.ip
            retu_dic["system_name"] = netinfo.system_name
            retu_dic["pro_num"] = netinfo.pro_num
            retu_dic["ip"] = netinfo.IP_R2C1
            retu_dic["laboratory_ip"] = netinfo.laboratory_ip
            retu_dic["server_ip"] = netinfo.server_ip
            retu_dic["pro_EquiInfo"] = netinfo.pro_EquiInfo
            retu_dic["test_ins"] = ai.ins.ins_nm
            retu_dic["bank_num"] = ai.bank_num
            retu_dic["acc_ecds"] = ai.acc_ecds
            retu_dic["test_num"] = ai.test_num
            retu_dic["test_ccpc"] = ai.test_ccpc
            retu_dic["product_num"] = ai.product_num
            retu_dic["production_ccpc"] = ai.production_ccpc
            retu_dic["mid_message"] = ai.mid_message
            retu_dic["mid_apply"] = ai.mid_apply
            retu_dic["port"] = for_pro.port
            retu_dic["pro_version"] = for_pro.pro_version
            retu_dic["pro_system"] = for_pro.pro_system
            retu_dic["acc_month"] = ai.acc_month
            retu_dic["support_name"] = ai.support_name

            retu_data["retu_info"].append(retu_dic)
        return json_response(retu_data)
示例#24
0
def delete_post(post_id):
    """
    Удаляет в БД открытый на редактирование пост с номером post_id
    :param post_id:
    :return: Словарь {"code_error": "Deleted_post"}
    """
    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute("DELETE FROM post WHERE id = %s", (post_id, ))
    cur.close()
    conn.commit()
    conn.close()

    return json_response(json.dumps({"code_error": "Deleted_post"}))
示例#25
0
def search(keyword, search_date, column, apply_info, retu_data):
    try:
        if keyword:
            all_ins = Insinfo.objects.filter(ins_nm__contains=keyword)
            for per_ins in all_ins:
                try:
                    apply = ApplyInfo.objects.get(check_state=1, ins=per_ins)
                    apply_info.append(apply)
                except:
                    pass
        if search_date:
            start_date = datetime.strptime(search_date.split()[0], '%Y-%m-%d')
            end_date = datetime.strptime(search_date.split()[2], '%Y-%m-%d')
            if apply_info:
                for per_ins in apply_info:
                    if not (per_ins.start_time >= start_date
                            and per_ins.end_time <= end_date):
                        apply_info.remove(per_ins)
            else:
                apply_info = ApplyInfo.objects.filter(
                    check_state=1,
                    start_time__gte=start_date,
                    end_time__lte=end_date)
        if column:
            if apply_info:
                for per_ins in apply_info:
                    if per_ins.operating != column:
                        apply_info.remove(per_ins)
            else:
                apply_info = ApplyInfo.objects.filter(
                    operating__contains=column)
    except Exception as e:
        return json_response({"msg": str(e)})
    if not apply_info:
        return json_response(retu_data)
    return apply_info
示例#26
0
def delete_user_state(user_id):
    """
    Удаляет из БД  user_state for user_id
    :param user_id:
    :return: Словарь {"response": "Record for user_id {user_id} deleted"}
    """

    with db_session:
        user_state = UserState.get(user_id=user_id)
        if user_state is not None:
            user_state.delete()
            response = f"Record for user_id {user_id} deleted"
        else:
            response = f"Record for user_id {user_id} not found"

    return json_response(json.dumps({"response": response}))
示例#27
0
def create_user_registration_record():
    """
    Добавляет новую запись о зарегистрированном пользователе в таблицу RegistrationUser,
    с содержанием, полученным в теле запроса (name, email)
    :return: Словрь {"response": "Created new registration record for {name} with email:{email}"}
    """
    req = request.json
    name = req["name"]
    email = req["email"]

    with db_session:
        user_registration = RegistrationUser.get(name=name, email=email)
        if user_registration is None:
            us_rg = RegistrationUser(name=name, email=email)
            response = f"Created new registration record for {name} with email:{email}"
        else:
            response = f"Record for user_id {name} with email:{email} already exist"
    return json_response(json.dumps({"response": response}))
示例#28
0
def create_author():
    """
        Запросом POST принимаем параметры для нового пользователя
        из request.json и добавляем его в базу
    """
    req = request.json
    username = req["username"]
    password_hash = req["password_hash"]
    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute(
        "INSERT INTO author (username, password) VALUES (%s, %s)",
        (username, password_hash),
    )
    cur.close()
    conn.commit()
    conn.close()

    return json_response(json.dumps({"code_error": "Created_new_author"}))
示例#29
0
def examples():
    base_url = app.config['BASE_URL']
    show = list_all_epguides_keys_redis()[0]
    return json_response([{
        'title': 'All tv shows',
        'path': '{0}show/'.format(base_url),
        'limit': 3,
    }, {
        'title': 'Next episode of show',
        'path': '{0}show/{1}/next/'.format(base_url, show)
    }, {
        'title': 'Last episode of show',
        'path': '{0}show/{1}/last/'.format(base_url, show)
    }, {
        'title': 'First episode of show',
        'path': '{0}show/{1}/first/'.format(base_url, show)
    }, {
        'title': 'Lookup specific episode',
        'path': '{0}show/{1}/1/1/'.format(base_url, show)
    }, {
        'title': 'Meta data for show',
        'path': '{0}show/{1}/info/'.format(base_url, show)
    }, {
        'title':
        'Check if specific episode is released',
        'path':
        '{0}show/{1}/1/1/released/'.format(base_url, show)
    }, {
        'title':
        'Lookup next episode from given episode',
        'path':
        '{0}show/{1}/1/1/next/'.format(base_url, show)
    }, {
        'title':
        'Lookup next episode from given episode (new season)',
        'path':
        '{0}show/{1}/1/1/next/'.format(base_url, show)
    }, {
        'title':
        'Check if next episode from given episode is released',
        'path':
        '{0}show/{1}/1/1/next/released/'.format(base_url, show)
    }])
示例#30
0
def get_logs():
    """
    :return: json с десятью последними записями.
    """
    conn = get_conn_db()
    cur = conn.cursor()

    cur.execute('''
            SELECT time_created, logger_name, level_name, file_name, func_name, line_number, msg FROM log
            ORDER BY created DESC
            LIMIT 10;
            ''')

    post_cur = cur.fetchall()
    tp_bd = list_tp_to_list_dict(post_cur, cur)
    cur.close()
    conn.commit()
    conn.close()
    return json_response(json.dumps(tp_bd, default=convert_dt))
示例#31
0
def update_post(post_id):
    """
    Записывает в БД измененный  пост с номером post_id
    :param post_id:
    :return:
    """

    req = request.get_json()
    title = req["title"]
    body = req["body"]

    conn = get_conn_db()
    cur = conn.cursor()
    cur.execute("UPDATE post SET title = %s, body = %s WHERE id = %s",
                (title, body, post_id))
    cur.close()
    conn.commit()
    conn.close()

    return json_response(json.dumps({"code_error": "Updated_post"}))
示例#32
0
def user_state_record(user_id):
    """
    Отдает запись user_state для запрашиваемого user_id из таблицы userstate
    :return: Словарь {"response": "Record for {user_id} not found"}
             в случае ошибки или словарь с найденной записью
    """

    with db_session:
        user_state_rec = select(
            (item.user_id, item.scenario_name, item.step_name, item.context)
            for item in UserState if item.user_id == user_id).first()
    if user_state_rec is not None:
        dict_for_response = {
            "user_id": user_state_rec[0],
            "scenario_name": user_state_rec[1],
            "step_name": user_state_rec[2],
            "context": user_state_rec[3]
        }
    else:
        dict_for_response = {"response": f"Record for {user_id} not found"}
    return json_response(json.dumps(dict_for_response))
示例#33
0
def data_post(path):
    """
    Handle HTTP POST for data

    Create a new resource if it does not exist. The received object will be
    validated against the schema for this resource type. If no schema exists,
    will return an error.

    Example to create a new student (would generate id):
    POST /student/
    """
    # check if path exists
    file_path = os.path.join('data', path) + config['DATA_FILE_EXT']
    latest_version = repo.get_latest_commit()
    if repo.path_files(file_path, latest_version.id) is None:
        # check schema exists, and validate against schema
        # if ok, create new resource and return location
        pass
    else:
        # return error - already exists
        pass
    return utils.json_response({'posted': 'more stuff'})
示例#34
0
def get_schemas(path):
    # TODO serve schemas
    return utils.json_response({'TODO': 'scheme away'}, wz_err.NotImplemented)