• django 修改 request 对象中的请求参数, 并重新赋值给 request 对象


    直接上代码, 实现流程看代码及注释

    def your_view(self, request):
    
        method = request.method
    
        if method == "GET":
            # 使用 querydict对象的copy()方法, 获取一个可修改的querydict
            data = request.GET.copy()
            # 修改参数值
            data = params_replace(data)
            if data:
                request.GET = data
    
        # 当请求方式是其他请求方法时
        else:
            try:
                # 如果body是json数据, 先转换为字典
          # 注意:这里如果是上传文件, 会报 UnicodeDecodeError 异常, 需要根据实际业务决定是否需要进行异常处理
    params = eval(request.body.decode(encoding="utf-8")) machine_version = params.get("username") if machine_version: params["username"] = machine_version.replace("-", " ")
          # 重新构造请求体, 进行编码后, 重新赋值给 request._body
          # 注意是 request._body, 因为 request.body 是不可修改的, 但是 body 属性继承自 _body 属性, 所以直接修改 _body 属性
    request._body
    = json.dumps(params).encode(encoding="utf-8") except: # 如果body是key1=value1&key2=value2的参数形式 new_params = list() # 直接获取 body, 请求体里的二进制数据, 解码后, 进行切割 for param in request.body.decode().split("&"): if "username" in param: # 修改参数值, 并重新拼接参数 new_str = "username=" + param.split("=")[1].replace("-", " ") new_params.append(new_str) else: new_params.append(param) # 重新构造请求体, 进行编码后, 重新赋值给 request._body # 注意是 request._body, 因为 request.body 是不可修改的, 但是 body 属性继承自 _body 属性, 所以直接修改 _body 属性 request._body = "&".join(new_params).encode(encoding="utf-8") ... def params_replace(self, data): # 按需求, 对请求参数中的值做出修改 name = data.get("username") if name: data["username"] = name.replace("-", " ") return data else: return None

    HttpRequest 部分源码(关于body属性), 完整源码: https://docs.djangoproject.com/en/2.0/_modules/django/http/request/#HttpRequest

    class HttpRequest:
        @property
        def body(self):
            if not hasattr(self, '_body'):
                if self._read_started:
                    raise RawPostDataException("You cannot access body after reading from request's data stream")
        
                # Limit the maximum request data size that will be handled in-memory.
                if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
                        int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
                    raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
    
                try:
                    self._body = self.read()
                except IOError as e:
                    raise UnreadablePostError(*e.args) from e
                self._stream = BytesIO(self._body)
            return self._body
  • 相关阅读:
    Android Studio同时监听多个Button实现activity跳转
    Android Studio--Activity实现跳转功能
    Gym 101170F Free Weights(二分)题解
    Gym 101170I Iron and Coal(BFS + 思维)题解
    Gym 101128F Landscaping(网络流)题解
    Gym 101128A Promotions(思维 + dfs)题解
    Gym 101480I Ice Igloos(思维乱搞)题解
    Gym 101480F Frightful Formula(待定系数)题解
    Gym 101128J Saint John Festival(凸包 + 二分判点和凸包关系)题解
    CodeForces 348D Turtles(LGV定理)题解
  • 原文地址:https://www.cnblogs.com/lowmanisbusy/p/11813072.html
Copyright © 2020-2023  润新知