首页 > 解决方案 > 为 OPTION 请求覆盖 ​​Django Rest Framework 标头

问题描述

当我向端点发送 http OPTION 请求时,Django rest Framework 会使用以下有效负载进行响应:

{
    "name": "Get Categorias",
    "description": "",
    "renders": [
        "application/json",
        "text/html"
    ],
    "parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ]
}

以及以下标题:

Date →Fri, 08 Feb 2019 12:25:50 GMT
Server →Apache/2.4.29 (Ubuntu)
Content-Length →173
Vary →Accept
Allow →GET, HEAD, OPTIONS
X-Frame-Options →SAMEORIGIN
Keep-Alive →timeout=5, max=100
Connection →Keep-Alive
Content-Type →application/json

这是代码:

@permission_classes((AllowAny,))
class GetCategorias(APIView):
    def get(self, request):

        query = "SELECT * FROM categoria ORDER BY nome ASC;"

        find = FuncaoCursorFetchAll.queryCursor(query)
        if find:
            result = []
            for cat in find:
                result.append({"id" : cat[0], "categoria" : cat[1]})


            response = JsonResponse({"categorias" : result}, encoder=DjangoJSONEncoder,safe=False,content_type="application/json;charset=utf-8")
            response['Access-Control-Allow-Origin'] = '*'
            response['Access-Control-Allow-Methods'] = 'GET, OPTIONS, HEAD'
            response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
            return response
        else:
            data = {"error": "Nenhum registro encontrado"}

网址定义:

path('categorias/', views.GetCategorias.as_view(), name='categorias'),

我需要覆盖这个标题。我不知道这是从哪里来的,因为我没有 OPTIONS 请求的明确端点。任何人都可以帮助我发现我可以在哪里配置我需要的正确标题?

标签: pythondjangodjango-rest-framework

解决方案


您可以轻松覆盖options

from rest_framework.response import Response

class ClassBasedView(APIView):
    def options(self, request, *args, **kwargs):
        return Response({'foo': 'bar'})

@api_view(['GET', 'POST', 'OPTIONS'])
def func_based_view(request):
    if request.method == 'OPTIONS':
        return Response({'foo': 'bar'})
    else:
        return Response({'message': 'not options!'})

如果您不了解 REST framework 中的视图?检查这个文档

你想覆盖标题?您可以通过Response. 检查此响应文档

您的OPTIONS有效载荷metadata在您的视野中。您还可以覆盖元数据。请参阅此元数据文档


推荐阅读