gpt4 book ai didi

python - 覆盖 OPTION 请求的 Django Rest Framework header

转载 作者:行者123 更新时间:2023-12-02 03:21:44 30 4
gpt4 key购买 nike

当我向端点发送 http OPTION 请求时,Django Rest Framework 使用以下 paylod 进行响应:

{
"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'),

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

最佳答案

您可以轻松地覆盖选项

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框架中的 View ?检查this doc

你想覆盖标题吗?您可以通过Response给出您自己的 header 。检查这个Response doc

您的OPTIONS负载是您 View 的元数据。您还可以覆盖元数据。看这个Metadata doc

关于python - 覆盖 OPTION 请求的 Django Rest Framework header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592970/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com