예제 #1
0
파일: crud.py 프로젝트: showurl/newbee
def delete_data_to_database(model,
                            find_dict,
                            set_default_delete_data_to_database=None):
    """

    :param model:
    :param find_dict:
    :return:
    """
    sid = transaction.savepoint()  # 开启事务设置事务保存点
    try:
        if set_default_delete_data_to_database:
            model, find_dict = set_default_delete_data_to_database(
                model, find_dict)
        objs = model.objects.filter(**find_dict)
        if not objs:
            return_json_j = status_dict.get_FAIL_BY_NOTHING_TO_DO_4040(
                "没找到需要删除的对象")
            return_json_j.update({
                "status": "FAIL",
                "type": model.__name__,
            })
            return return_json_j, 400
            # 模型备份
        for obj in objs:
            NewBeeDeleteRecord.objects.create(model_name=model.__name__,
                                              record_json=json.dumps(
                                                  models_to_json(obj)))
        objs.delete()

    except Exception as e:
        transaction.savepoint_rollback(sid)  # 失败回滚事务(如果数据库操作发生异常,回滚到设置的事务保存点)
        return {
            # "msg": "%s文件%s行发生%s错误" % (
            #     e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e),
            "msg": "%s" % e,
            "code": status_dict.SERVER_ERROR,
            "status": "FAIL",
            "type": model.__name__,
        }, 500
    else:
        transaction.savepoint_commit(sid)  # 如果没有异常,成功提交事物
        logger.info("%s模型删除了一条数据%s成功" % (model.__str__, str(find_dict)))
        return_json = status_dict.get_DELETE_SUCCESS_2001()
        return_json.update({
            "status": "OK",
            "type": model.__name__,
        })
        return return_json, 200
예제 #2
0
파일: crud.py 프로젝트: tchigher/newbee
def add_data_to_database(model,
                         add_dict,
                         many_to_many_dict,
                         return_data_key,
                         return_data_dict,
                         default_add_data_to_database=None):
    """
    增加一条记录到数据库
    :param model:
    :param add_dict:
    :param many_to_many_dict:
    :param return_data_dict:
    :return:
    """
    sid = transaction.savepoint()  # 开启事务设置事务保存点
    try:
        if default_add_data_to_database:
            model, add_dict, many_to_many_dict, return_data_key, return_data_dict = default_add_data_to_database(
                model, add_dict, many_to_many_dict, return_data_key,
                return_data_dict)
        obj = model.objects.create(**add_dict)
        for k, v in many_to_many_dict.items():
            attr = getattr(obj, k)
            if isinstance(v, list):
                v = [int(l) for l in v]
                attr.add(*v)
            else:
                attr.add(int(v))
    except Exception as e:
        transaction.savepoint_rollback(sid)  # 失败回滚事务(如果数据库操作发生异常,回滚到设置的事务保存点)
        return {
            # "msg": "%s文件%s行发生%s错误" % (
            #     e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e),
            "msg": "%s" % e,
            "code": status_dict.SERVER_ERROR,
            "status": "FAIL",
            "type": model.__name__,
        }, 500
    else:
        transaction.savepoint_commit(sid)  # 如果没有异常,成功提交事物
        add_data = get_model_data_by_id(model=model,
                                        id=obj.id,
                                        return_data_dict=return_data_dict)
        logger.info("%s模型%s添加了一条数据%s成功" %
                    (model.__str__, return_data_key, str(add_dict)))
        if not add_data:
            return_json = status_dict.get_ADD_SUCCESS_2000(
                msg="添加成功, 但查询新增数据时失败")
            return_json.update({
                "status": "OK",
                "type": model.__name__,
            })
        else:
            return_json = status_dict.get_ADD_SUCCESS_2000()
            return_json.update({
                "status": "OK",
                "type": model.__name__,
            })
        data = {}
        data[return_data_key] = models_to_json(data=add_data)
        return_json["data"] = data
        return return_json, 200
예제 #3
0
파일: crud.py 프로젝트: tchigher/newbee
def find_util(request,
              action,
              page=0,
              pageSize=config.FINDDEFUALTPAGESIZE,
              order_by="id"):
    """
    执行查询业务时  你需要调用的方法
    :param request: 前端发送的请求
    :param action: 路径传参携带的action
    :param page: 分页查询的页码
    :param pageSize: 分页查询每页的最大行数
    :param order_by: 通过??排序
    :return:
    """
    # 解析request数据  先转json
    json_data = get_request_body_dict(request)
    if not json_data:
        json_data = request.GET
    # 转json成功
    # 判断前端是否传递id
    request_id = json_data.get("id")
    page = json_data.get("page") or page
    pageSize = json_data.get("pageSize") or json_data.get(
        "page_size") or pageSize
    order_by = json_data.get("order_by") or order_by
    # 拿到model信息
    model = get_model_by_model_info(action)  # 模型
    find_default_dict = get_find_default_dict(
        request, action)  # 查询附加{"is_deleted": False}
    find_parent_field_list = get_find_parent_field_dict_list(action)  # 返回的父亲字段
    find_child_field_list = get_find_child_field_dict_list(action)  # 返回的孩子字段
    find_return_key = get_find_return_key(
        action)  # 查询成功 组成json时 的key  默认为 action+"_list"
    find_response_normal_field_dict = get_find_response_normal_field_dict(
        model)
    can_find = get_can_find(action)
    find_add_dict_list = get_find_add_dict(action)
    id_key = get_find_id_key(action)  # 默认是id
    if not model:
        return {
            "msg": "找不到%s模型" % action,
            "status": "FAIL",
            "type": action,
            "code": 404
        }, 404
    if not can_find:
        return {
            "msg": "%s模型不允许进行查询操作" % action,
            "status": "FAIL",
            "type": action,
            "code": 500
        }, 500
    # 先组成查询字典
    find_request_allow_field_dict = get_find_request_allow_field_dict(model)
    find_dict__ = find_default_dict if find_default_dict else {}
    find_dict = find_dict__.copy()
    find_data_list = []
    for k, v in find_request_allow_field_dict.items():
        value = json_data.get(v.get("request_key"))
        if not value:
            continue
        # 组字典
        find_dict[v.get("find_by_self_key")] = value
    # 去查询
    if request_id:
        find_dict = {"id": request_id}
    if find_dict == find_dict__:
        find_dict.update(get_if_find_dict_none(request, action))
    logger.debug("查询字典是: %s" % find_dict)
    if not find_dict:
        objs = model.objects.all().order_by(order_by)
    else:
        objs = model.objects.filter(**find_dict).order_by(order_by)
    # 拼装查询数据
    for obj in objs:
        obj_data = {}
        obj_data[id_key] = obj.id
        for find_add_dict in find_add_dict_list:
            for k, v in find_add_dict.items():
                obj_data[k] = obj.__dict__[v]
        for k, v in find_response_normal_field_dict.items():
            obj_data[v.get("response_key")] = obj.__dict__[k]
        if find_parent_field_list:
            for find_parent_field in find_parent_field_list:
                key, this_field_name, new_model_fields = find_parent_field
                try:
                    new_models = getattr(obj, this_field_name).all()
                    new_model_values = []
                    for new_model in new_models:
                        new_model_value = {}
                        for nk, nv in new_model.__dict__.items():
                            for new_model_field in new_model_fields:
                                if isinstance(new_model_field, dict):
                                    for dk, dv in new_model_field.items():
                                        if nk == dv:
                                            new_model_value[dk] = nv
                            if nk in new_model_fields:
                                new_model_value[nk] = nv
                        if new_model_value:
                            new_model_values.append(new_model_value)
                    if new_model_values:
                        obj_data[key] = new_model_values
                except AttributeError:
                    new_model = getattr(obj, this_field_name)
                    new_model_value = {}
                    for nk, nv in new_model.__dict__.items():
                        if nk in new_model_fields:
                            new_model_value[nk] = nv
                    obj_data[key] = new_model_value
        if find_child_field_list:
            for find_parent_field in find_child_field_list:
                key, this_field_name, new_model_fields = find_parent_field
                try:
                    new_models = getattr(obj, this_field_name).all()
                    new_model_values = []
                    for new_model in new_models:
                        new_model_value = {}
                        for nk, nv in new_model.__dict__.items():
                            for new_model_field in new_model_fields:
                                if isinstance(new_model_field, dict):
                                    for dk, dv in new_model_field.items():
                                        if nk == dv:
                                            new_model_value[dk] = nv
                            if nk in new_model_fields:
                                new_model_value[nk] = nv
                        if new_model_value:
                            new_model_values.append(new_model_value)
                    if new_model_values:
                        obj_data[key] = new_model_values
                except AttributeError:
                    new_model = getattr(obj, this_field_name)
                    if new_model:
                        # print(new_model)
                        new_model_value = {}
                        for nk, nv in new_model.__dict__.items():
                            if nk in new_model_fields:
                                new_model_value[nk] = nv
                        obj_data[key] = new_model_value
        if obj_data:
            find_data_list.append(obj_data)
    if page == 0:
        return {
            "msg": "查询成功",
            "code": 200,
            "status": "OK",
            "type": action,
            "data": {
                find_return_key: models_to_json(find_data_list)
            }
        }, 200
    else:
        # 分页
        page = int(page)
        pageSize = int(pageSize)
        range_start = (page - 1) * pageSize  # 开始下标
        range_end = page * pageSize  # 结束下标
        max_len = len(find_data_list)  # 数据总行数
        page_count = int(max_len / pageSize) + (1 if max_len % pageSize else 0
                                                )  # 总页数
        if page > page_count:  # page超出下标  下标越界
            return status_dict.get_FAIL_BY_NOT_FOUND_404(), 404
        if range_start <= range_end < 0:  # pageSize不正常
            range_start = range_end = 0
        model_data_page = find_data_list[range_start:range_end]
        return {
            "msg": "查询成功",
            "code": 200,
            "status": "OK",
            "type": action,
            "page": page,
            "page_count": page_count,
            "data": {
                find_return_key: models_to_json(model_data_page)
            }
        }, 200
예제 #4
0
파일: crud.py 프로젝트: tchigher/newbee
def update_data_to_database(model,
                            find_for_write_default_dict,
                            update_dict,
                            many_to_many_dict,
                            return_data_key,
                            return_data_dict,
                            default_update_data_to_database=None):
    """
    增加一条记录到数据库
    :param model:
    :param add_dict:
    :param many_to_many_dict:
    :param return_data_dict:
    :return:
    """
    logger.debug("更新操作的多对多字典:%s " % many_to_many_dict)
    sid = transaction.savepoint()  # 开启事务设置事务保存点
    try:
        if default_update_data_to_database:
            logger.debug("执行default_update_data_to_database: %s" %
                         default_update_data_to_database)
            model, find_for_write_default_dict, update_dict, many_to_many_dict, return_data_key, \
            return_data_dict = default_update_data_to_database(
                model, find_for_write_default_dict, update_dict, many_to_many_dict, return_data_key,
                return_data_dict)
        logger.debug("更新的查询字典是: %s" % find_for_write_default_dict)
        logger.debug("更新字典是: %s" % update_dict)
        objs = model.objects.filter(**find_for_write_default_dict)
        if not objs:
            return_data_f = status_dict.get_FAIL_BY_NOTHING_TO_DO_4040(
                "没找到需要修改的对象")
            return_data_f.update({
                "status": "FAIL",
                "type": model.__name__,
            })
            return return_data_f, 400
        objs.update(**update_dict)
        for obj in objs:
            for k, v in many_to_many_dict.items():
                attr = getattr(obj, k)
                attr.clear()
                if isinstance(v, list):
                    v = [int(l) for l in v]
                    attr.add(*v)
                else:
                    attr.add(int(v))
    except Exception as e:
        transaction.savepoint_rollback(sid)  # 失败回滚事务(如果数据库操作发生异常,回滚到设置的事务保存点)
        return {
            # "msg": "%s文件%s行发生%s错误" % (
            #     e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e),
            "msg": "%s" % e,
            "code": status_dict.SERVER_ERROR,
            "status": "FAIL",
            "type": model.__name__,
        }, 500
    else:
        transaction.savepoint_commit(sid)  # 如果没有异常,成功提交事物
        logger.info("%s模型修改了一条数据%s, %s成功" %
                    (model.__str__, str(find_for_write_default_dict),
                     str(update_dict)))
        if objs.count() > 1:
            update_data = get_model_data_by_ids(
                model=model,
                ids=[obj.id for obj in objs],
                return_data_dict=return_data_dict)
        else:
            update_data = get_model_data_by_id(
                model=model, id=objs[0].id, return_data_dict=return_data_dict)
        if not update_data:
            return_json = status_dict.get_UPDATE_SUCCESS_2002(
                msg="修改成功, 但查询新增数据时失败")
            return_json.update({
                "status": "OK",
                "type": model.__name__,
            })
        else:
            return_json = status_dict.get_UPDATE_SUCCESS_2002()
            return_json.update({
                "status": "OK",
                "type": model.__name__,
            })
        return_json["data"] = {
            return_data_key: models_to_json(data=update_data)
        }
        return return_json, 200