def decrypt_oralce(key, text): if not text: return None unpad = lambda s: s[0:-s[-1]] aes = AES.new(add_to_16(key), AES.MODE_ECB) # 优先逆向解密base64成bytes base64_decrypted = base64.decodebytes(bytes(text, encoding='utf-8')) decrypted_text = unpad( aes.decrypt(base64_decrypted)).decode('utf-8').replace('\0', '') try: logger.debug("解密之后的数据是:%s" % json.loads(decrypted_text)) return json.loads(decrypted_text) except: logger.debug("解密之后的数据是:%s" % decrypted_text) return decrypted_text
def encrypt_oracle(key, text): if not text: return None logger.debug("加密之前的数据是:%s" % text) if not isinstance(text, str): text = json.dumps(text).replace(" ", "") text = text.replace(" ", "") cipher = AES.new(add_to_16(key), AES.MODE_ECB) x = AES.block_size - (len(text) % AES.block_size) if x != 0: text = text + chr(x) * x msg = cipher.encrypt(text.encode(encoding="utf-8")) # msg = base64.urlsafe_b64encode(msg).replace('=', '') msg = base64.b64encode(msg) # print(msg.decode("utf-8")) return msg.decode("utf-8")
def process_response(self, request, response): path = str(request.path) if path not in exclude_path and [path, str(request.method).upper() ] not in exclude_path: if response: if is_send_text: try: if response["Content-Type"] in ("application/json", ): str_data = encrypt_oracle(sign_key, response.data) http_response = HttpResponse( str_data.encode("utf-8"), content_type="text/plain,charset=utf-8") http_response.status_code = response.status_code return http_response else: logger.debug("不是返回的json, 返回的:%s" % response["Content-Type"]) return response except Exception as e: logger.error("加密时发生错误:%s" % e) return response else: return response
def add_util(request, action, write_database_func=None): """ 执行增加业务时 你需要调用的方法 :param request: 前端发送的请求 :param action: 路径传参携带的action :param write_database_func: 你可以重写写入数据库的方法 填到此项 :return: """ # 获取json字典 json_data = get_request_body_dict(request) # 获取model model = get_model_by_model_info(action) # 获取增加业务默认的字典 add_default_dict = get_add_default_dict(action) # 获取增加成功时返回的data格式 write_success_return_data_form = get_write_success_return_data_form(action) # 查询该action是否可以执行增加业务 can_add = get_can_add(action) if not model: return { "msg": "找不到%s模型" % action, "status": "FAIL", "type": action, "code": 404 }, 404 if not can_add: return { "msg": "%s模型不允许进行增加操作" % action, "status": "FAIL", "type": action, "code": 500 }, 500 # 组合字典 add_dict = get_add_dict(add_default_dict, request) many_to_many_dict = {} # 非空验证 # 获取 该 model的所有字段 看哪个 新增 要求 必传 normal_fields = get_normal_field_list_by_model(model) logger.debug("增加操作的普通字段为:%s " % normal_fields) for field in normal_fields: # 获取key request_key = newbee_model.get_attr_by_model_field_key( model, field, "request_key") if not request_key: request_key = field # 先看允许传递该字段吗 allow_request_field = newbee_model.get_attr_by_model_field_key( model, field, "new_bee_can_add") if not allow_request_field: # 看看前端是否传递了 re_value = json_data.get(request_key) if re_value: return_data_f = status_dict.get_FAIL_BY_PARA_TYPE_4001( msg="%s字段不能传递数据" % request_key) return_data_f.update({ "status": "FAIL", "type": action, }) return return_data_f, 400 else: continue # 必传验证 if newbee_model.get_attr_by_model_field_key(model, field, "is_add_tran"): # 必传 去验证 require_field = json_data.get(request_key) if not require_field: # 必传验证失败 return_data_f = status_dict.get_FAIL_BY_PARA_NOT_ALL_4000( msg="%s字段为必传字段" % request_key) return_data_f.update({ "status": "FAIL", "type": action, }) return return_data_f, 400 # 普通字段 try: normal_field_value = json_data[request_key] except: continue else: create_key = newbee_model.get_attr_by_model_field_key( model, field, "new_bee_add_key") if not create_key: create_key = request_key add_dict[create_key] = normal_field_value many_to_many_fields = get_many_to_many_field_list_by_model(model) children_field_list = get_children_field_list_by_model(model) many_to_many_fields += children_field_list # 多对多字段 for many_to_many_field in many_to_many_fields: # 获取key request_key = newbee_model.get_attr_by_model_field_key( model, many_to_many_field, "request_key") if not request_key: request_key = many_to_many_field many_to_many_request_value = json_data.get(request_key) # 如果前端没有传递该多对多对象 if not many_to_many_request_value: continue create_key = newbee_model.get_attr_by_model_field_key( model, many_to_many_field, "new_bee_add_key") if not create_key: create_key = request_key many_to_many_dict[create_key] = many_to_many_request_value add_re_realte_dict_list = get_add_re_realte_dict_list(action) if add_re_realte_dict_list: for add_re_realte_dict in add_re_realte_dict_list: if add_re_realte_dict: for rek, rev in add_re_realte_dict.items(): many_to_many_request_value = json_data.get(rek) # 如果前端没有传递该多对多对象 if many_to_many_request_value != [] and not many_to_many_request_value: continue many_to_many_dict[rev] = many_to_many_request_value # 执行数据库操作 增加记录 生成多对多关系 return_data_key = [k for k, v in write_success_return_data_form.items()][0] return_data_form = write_success_return_data_form.get(return_data_key) logger.debug("增加字典是:%s" % add_dict) default_add_data_to_database = get_default_add_data_to_database( action=action) if write_database_func: return write_database_func(model, add_dict, many_to_many_dict, return_data_key, return_data_form, default_add_data_to_database) else: return add_data_to_database(model, add_dict, many_to_many_dict, return_data_key, return_data_form, default_add_data_to_database)
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
def update_util(request, action, func=None): """ 执行更新业务时 你需要调用的方法 :param request: 前端发送的请求 :param action: 路径传参携带的action :param func: 你可以重写写入数据库的方法 填到此项 :return: """ # 解析request数据 先转json json_data = get_request_body_dict(request) # 转json成功 # 拿到model信息 model = get_model_by_model_info(action) update_default_dict = get_update_default_dict(action) write_success_return_data_form = get_write_success_return_data_form(action) find_for_write_default_dict = get_find_for_write_default_dict( request, action) can_update = get_can_update(action) if not model: return { "msg": "找不到%s模型" % action, "status": "FAIL", "type": action, "code": 404 }, 404 if not can_update: return { "msg": "%s模型不允许进行修改操作" % action, "status": "FAIL", "type": action, "code": 500 }, 500 # 组合字典 update_dict = get_update_dict(update_default_dict, request) many_to_many_dict = {} # 非空验证 # 获取 该 model的所有字段 看哪个 新增 要求 必传 normal_fields = get_normal_field_list_by_model(model) for field in normal_fields: # 获取key request_key = newbee_model.get_attr_by_model_field_key( model, field, "request_key") if not request_key: request_key = field # 先看允许传递该字段吗 allow_request_field = newbee_model.get_attr_by_model_field_key( model, field, "new_bee_can_update") if not allow_request_field: # 看看前端是否传递了 re_value = json_data.get(request_key) if re_value: return_data_f = status_dict.get_FAIL_BY_PARA_TYPE_4001( msg="%s字段不能传递数据" % request_key) return_data_f.update({ "status": "FAIL", "type": action, }) return return_data_f, 400 else: continue # 必传验证 if newbee_model.get_attr_by_model_field_key(model, field, "new_bee_is_update_tran"): # 必传 去验证 require_field = json_data.get(request_key) if not require_field: # 必传验证失败 return_data_f = status_dict.get_FAIL_BY_PARA_NOT_ALL_4000( msg="%s字段为必传字段" % request_key) return_data_f.update({ "status": "FAIL", "type": action, }) return return_data_f, 400 # 普通字段 try: normal_field_value = json_data[request_key] except: continue else: create_key = newbee_model.get_attr_by_model_field_key( model, field, "new_bee_update_key") if not create_key: create_key = request_key update_dict[create_key] = normal_field_value many_to_many_fields = get_many_to_many_field_list_by_model(model) children_field_list = get_children_field_list_by_model(model) many_to_many_fields += children_field_list # 多对多字段 for many_to_many_field in many_to_many_fields: # 获取key request_key = newbee_model.get_attr_by_model_field_key( model, many_to_many_field, "request_key") if not request_key: request_key = many_to_many_field many_to_many_request_value = json_data.get(request_key) # 如果前端没有传递该多对多对象 if many_to_many_request_value == []: create_key = newbee_model.get_attr_by_model_field_key( model, many_to_many_field, "new_bee_update_key") if not create_key: create_key = request_key many_to_many_dict[create_key] = [] elif many_to_many_request_value == None: continue else: create_key = newbee_model.get_attr_by_model_field_key( model, many_to_many_field, "new_bee_update_key") if not create_key: create_key = request_key many_to_many_dict[create_key] = many_to_many_request_value update_re_realte_dict_list = get_update_re_realte_dict_list(action) logger.debug("update_re_realte_dict_list: % s" % update_re_realte_dict_list) if update_re_realte_dict_list: for update_re_realte_dict in update_re_realte_dict_list: if update_re_realte_dict: for rek, rev in update_re_realte_dict.items(): many_to_many_request_value = json_data.get(rek) # 如果前端没有传递该多对多对象 if many_to_many_request_value != [] and not many_to_many_request_value: continue many_to_many_dict[rev] = many_to_many_request_value # 执行数据库操作 增加记录 生成多对多关系 return_data_key = [k for k, v in write_success_return_data_form.items()][0] return_data_form = write_success_return_data_form.get(return_data_key) default_update_data_to_database = get_default_update_data_to_database( action) if func: return func(model, find_for_write_default_dict, update_dict, many_to_many_dict, return_data_key, return_data_form, default_update_data_to_database) return update_data_to_database(model, find_for_write_default_dict, update_dict, many_to_many_dict, return_data_key, return_data_form, default_update_data_to_database)
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
def process_request(self, request): path = str(request.path) if path not in exclude_path and [path, str(request.method).upper() ] not in exclude_path: try: if is_recv_json: if request.META["CONTENT_TYPE"] not in ( "application/json", ): try: request.META["CONTENT_TYPE"] = "application/json" logger.debug("收到text:%s" % request.body.decode('utf-8')) json_data = decrypt_oralce( sign_key, request.body.decode('utf-8')) logger.debug("收到json:%s" % json_data) if isinstance(json_data, str): setattr(request, "_body", json_data.encode('utf-8')) setattr(request, "_body", json.dumps(json_data).encode('utf-8')) except Exception as e: str_data = encrypt_oracle(sign_key, { "msg": "解密失败: " + str(e), "code": 400 }) http_response = HttpResponse( str_data.encode('utf-8'), content_type="text/plain,charset=utf-8") http_response.status_code = 400 return http_response else: logger.debug("前端发送了json") else: if request.META["CONTENT_TYPE"] not in ( "application/json", ): try: request.META["CONTENT_TYPE"] = "application/json" json_data = decrypt_oralce( sign_key, request.body.decode('utf-8')) if isinstance(json_data, str): setattr(request, "_body", json_data.encode('utf-8')) setattr(request, "_body", json.dumps(json_data).encode('utf-8')) except Exception as e: str_data = encrypt_oracle(sign_key, { "msg": "解密失败: " + str(e), "code": 400 }) http_response = HttpResponse( str_data.encode('utf-8'), content_type="text/plain,charset=utf-8") http_response.status_code = 400 return http_response else: str_data = encrypt_oracle(sign_key, { "msg": "后端不接受json数据", "code": 400 }) http_response = HttpResponse( str_data.encode('utf-8'), content_type="text/plain,charset=utf-8") http_response.status_code = 400 return http_response except Exception as e: logger.error("解密时发生错误:%s" % e)