Django中间件对象不可呼应

发布于 2025-01-31 11:45:59 字数 2147 浏览 4 评论 0原文

我正在尝试编写自定义中间件以捕获异常并返回正确的HTTP响应对象。但是由于某种原因,我得到了一个“中间件对象”是不可呼应的错误。

我在图层中提出一个例外,如下

class MyView(APIView):
  def post(self, request):
    result = some_func(request) #this func raises an exception
    return Response({"status": "Success", "data": result})

日志。

backend_1          | INFO:django:BEGIN -> c25db666-e89c-43a5-9f28-48001e301829 - /myapp/settings/create
backend_1          | {"message": "Internal Server Error: /myapp/settings/create", "exc_info": "Traceback (most recent call last):\n  File \"/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py\", line 47, in inner\n    response = get_response(request)\nTypeError: 'MyAppResponseMiddleware' object is not callable", "status_code": 500, "request": "<WSGIRequest: POST '/myapp/settings/create'>"}
backend_1          | ERROR:django.request:Internal Server Error: /crystal/settings/create
backend_1          | Traceback (most recent call last):
backend_1          |   File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
backend_1          |     response = get_response(request)
backend_1          | TypeError: 'MyAppResponseMiddleware' object is not callable 
  

文件

#myapp/middleware.py
class MyAppResponseMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        
    def process_exception(self, request, exception):
        absolute_path = request.get_full_path()
        print(absolute_path)
        print(exception.__class__.name)
        print(exception.message)
    
#settings.py
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    ...
    ...
    <some custom middleware>
    ...
    "myapp.middleware.MyAppResponseMiddleware",
        ]    
        

我在最后一个中添加了中间件,以便我的中间件在其他中间件处理响应之前捕获响应/异常。

debug屏幕截图 我猜呼叫到达中间件时,它本身是一个httpresponse对象,而不是异常。我不确定,为什么它没有达到process_exception

I'm trying to write custom middleware for catching exceptions and returning the proper HTTP Response object. But for some reason, I'm getting a "middleware object is not callable" error.

I'm raising an exception in view layer like below

class MyView(APIView):
  def post(self, request):
    result = some_func(request) #this func raises an exception
    return Response({"status": "Success", "data": result})

logs.

backend_1          | INFO:django:BEGIN -> c25db666-e89c-43a5-9f28-48001e301829 - /myapp/settings/create
backend_1          | {"message": "Internal Server Error: /myapp/settings/create", "exc_info": "Traceback (most recent call last):\n  File \"/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py\", line 47, in inner\n    response = get_response(request)\nTypeError: 'MyAppResponseMiddleware' object is not callable", "status_code": 500, "request": "<WSGIRequest: POST '/myapp/settings/create'>"}
backend_1          | ERROR:django.request:Internal Server Error: /crystal/settings/create
backend_1          | Traceback (most recent call last):
backend_1          |   File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
backend_1          |     response = get_response(request)
backend_1          | TypeError: 'MyAppResponseMiddleware' object is not callable 
  

files

#myapp/middleware.py
class MyAppResponseMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        
    def process_exception(self, request, exception):
        absolute_path = request.get_full_path()
        print(absolute_path)
        print(exception.__class__.name)
        print(exception.message)
    
#settings.py
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    ...
    ...
    <some custom middleware>
    ...
    "myapp.middleware.MyAppResponseMiddleware",
        ]    
        

I've added middleware in the last so that my middleware catches the response/exception before other middleware process the response.

debug screenshot
I guess when the call reaches the middleware, it itself is an HTTPresponse object instead of an exception. I'm not sure, why it is not reaching process_exception

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七禾 2025-02-07 11:45:59

根据文档,中间件应该是可召唤的(__call__方法的功能或类) https://docs.djangoproject.com/en/4.0/topics/http/http/middleware/#writing-your-your-your-your-your-now-middleware

结构应该像:

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

According to docs Middleware should be a callable (function or class with __call__ method) https://docs.djangoproject.com/en/4.0/topics/http/middleware/#writing-your-own-middleware

Structure should be like:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文