从中间件向视图传递额外参数

3

我想在我的POST(JSON)请求中添加另一个字段。键值对必须为“请求ID”。我得出结论,最好的方法是使用中间件生成随机的请求ID,并将其注入请求对象中。我编写了自定义中间件来实现这一点。但当我尝试访问端点时,遇到了错误。

我尝试通过互联网搜索解决此错误,但没有找到解决方案。

class SimpleMiddleware:
def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    req = json.loads(request.body)
    req_id = random.randint(0,1000000)
    req["req_id"]=req_id

    response = self.get_response(req)

    # Code to be executed for each request/response after
    # the view is called.

    return response

我遇到的错误是'dict' object has no attribute 'is_ajax'。 请帮我修复此问题,如果有更简单、更好的实现方法,请告诉我。

1
好的,你已经获取了请求体,将其反序列化为字典,然后将其作为实际请求传递。但它不是请求,而是一个字典。所以不要这样做。 - Daniel Roseman
2
我不认为这是你想要做的事情的正确方法,但是为了能够正确地帮助你,我们需要知道你实际想要做什么。这是为什么?为什么随机ID需要在JSON内容中呢?它作为一个标题或请求的单独属性会不会更好一些呢? - Daniel Roseman
@DanielRoseman 我想生成请求ID来跟踪每个不同的请求,以便记录。我知道这可能不是正确的方法,但是否有其他方法或正确的方法可以实现?请告诉我。 - Tahseen Rahman
1个回答

2

好的,我已经实现了我想要做的事情。我的自定义中间件代码如下:

Original Answer翻译成"最初的回答"

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response
    
    def process_view(self, request, view_func, *view_args, **view_kwargs):
        request.req_id = random.randint(0,1000000)

更新:我当时是个新手,现在看到评论感到有些尴尬:P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接