如何在 Django 中间件中执行内容协商?
How to perform content negotiation in django middleware?
假设我有一个自定义 Django Middleware
,如果没有 return rest_framework Response
., [=14=,则检查请求 header 有 jwt 令牌]
middleware.py
@staticmethod
def process_view(request, view_func, view_args, view_kwargs):
try:
jwt_token = request.headers["token"]
except KeyError:
response = Response(status=status.HTTP_403_FORBIDDEN)
return response
但我收到类似
的错误
.accepted_renderer not set on Response
如何在这里执行content-negotiation?
我认为您使用的是 DRF's Response
class.
你应该使用 Django's HttpResponse
class 作为,
# middleware.py
<b>from django.http.response import HttpResponse</b>
@staticmethod
def process_view(request, view_func, view_args, view_kwargs):
try:
jwt_token = request.headers["token"]
except KeyError:
<b>response = HttpResponse(status=403)</b>
return response
更新-1
我不确定这个方法是好还是坏,但效果很好。
创建一个虚拟视图,即 return DRF Response
并将其用于 return 响应。
from rest_framework.response import Response
from rest_framework.decorators import api_view
<b>@api_view()
def custom_view(request):
return Response(status=403)</b>
class Foo(...):
@staticmethod
def process_view(request, view_func, view_args, view_kwargs):
try:
jwt_token = request.headers["token"]
except KeyError:
<b>return custom_view(request)</b>
假设我有一个自定义 Django Middleware
,如果没有 return rest_framework Response
., [=14=,则检查请求 header 有 jwt 令牌]
middleware.py
@staticmethod
def process_view(request, view_func, view_args, view_kwargs):
try:
jwt_token = request.headers["token"]
except KeyError:
response = Response(status=status.HTTP_403_FORBIDDEN)
return response
但我收到类似
的错误.accepted_renderer not set on Response
如何在这里执行content-negotiation?
我认为您使用的是 DRF's Response
class.
你应该使用 Django's HttpResponse
class 作为,
# middleware.py
<b>from django.http.response import HttpResponse</b>
@staticmethod
def process_view(request, view_func, view_args, view_kwargs):
try:
jwt_token = request.headers["token"]
except KeyError:
<b>response = HttpResponse(status=403)</b>
return response
更新-1
我不确定这个方法是好还是坏,但效果很好。
创建一个虚拟视图,即 return DRF Response
并将其用于 return 响应。
from rest_framework.response import Response
from rest_framework.decorators import api_view
<b>@api_view()
def custom_view(request):
return Response(status=403)</b>
class Foo(...):
@staticmethod
def process_view(request, view_func, view_args, view_kwargs):
try:
jwt_token = request.headers["token"]
except KeyError:
<b>return custom_view(request)</b>