Evandro Lacerda
Evandro Lacerda

Reputation: 238

Overwrite Django Rest Framework header for OPTION requests

When I send a http OPTION request to an endpoint, Django rest Framework responds with the following paylod:

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

And The Following headers:

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

Here's the code:

@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"}

Url definition:

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

I need to overwrite this headers. I don't Know from where this is coming since I don't have an explicit endpoint for OPTIONS request. Anyone can help me to discover where I can configure the correct headers I need?

Upvotes: 2

Views: 2186

Answers (1)

Jrog
Jrog

Reputation: 1527

You can override options easily.

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!'})

If you don't know about view in REST framework? Check this doc

And you want to override headers? You can give your own header by Response. Check this Response doc

Your OPTIONS payload is metadata of your view. You can also override metadata. See this Metadata doc

Upvotes: 5

Related Questions