python - 为 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 请求的明确端点。任何人都可以帮助我发现我可以在哪里配置我需要的正确标题?
解决方案
您可以轻松覆盖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
在您的视野中。您还可以覆盖元数据。请参阅此元数据文档
推荐阅读
- string - 如何检查用于解密消息的算法
- python - 如何使我的课程在 Python 中具有可比性?
- javascript - 角度,与控制台结果混淆
- angularjs - 使用 Angular 下载本地文件夹
- flutter - 如何确保在 Flutter 插件的本机视图中关闭键盘?
- firebase - 如何在firebase上为razorpay创建order_id?我正在将 react-native 与 firebase 一起用于移动应用程序
- laravel - 如何使用 Vue、Axios 和 Laravel 更新产品记录
- java - 单击后如何以几乎完整的模式显示图像?
- android - 线性和相对布局
- quantum-computing - 关于 QDK 中受控操作中令人惊讶的行为的查询