如何使用 django rest 框架 return OPTIONS 请求中的操作和参数

How to return actions and parameters in OPTIONS request with django rest framework

我尝试return select 使用 django-countries 和 django rest 框架的国家/地区的选项列表。我使用 JWT_AUTH 进行身份验证。

当我尝试选项请求时:

curl \
  -H "Authentication: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFsYmVydG9fdmVudGEiLCJ1c2VyX2lkIjoyLCJlbWFpbCI6IiIsImV4cCI6MTUwODE2Mzg4Mn0.svxqTThCahSl1Vu27sMjuJyd1PRLk28-Xgn2OKKb5-g"\
  -X OPTIONS \
  -v http://127.0.0.1:8000/api/v1/core/perfilViajeroUserPass/

响应是:

{
 "name":"Perfil Viajero User Pass Create",
 "description":"",
 "renders":["application/json","text/html"],
 "parses":[
           "application/json",
           "application/x-www-form-urlencoded",
           "multipart/form-data"
          ]
}

但我认为默认情况下应该是这样的:

{
"name": "To Do List",
"description": "List existing 'To Do' items, or create a new item.",
"renders": [
    "application/json",
    "text/html"
],
"parses": [
    "application/json",
    "application/x-www-form-urlencoded",
    "multipart/form-data"
],
"actions": {
    "POST": {
        "note": {
            "type": "string",
            "required": false,
            "read_only": false,
            "label": "title",
            "max_length": 100
        }
    }
}

}

有人可以帮助我吗?谢谢。

如果要更改部分内容:

  • name 是视图的 get_view_name,它是视图的名称,稍作修改。
  • description 是视图的 get_view_description,它重写了视图的文档字符串。

否则,如果您想要更复杂的东西,您可能需要自定义视图的元数据,如 http://www.django-rest-framework.org/api-guide/metadata/#custom-metadata-classes

中所述

我找到了解决方案。

我将视图 class 类型从 APIView 更改为 generics.CreateAPIView 并且知道它有效。非常感谢。

添加另一个答案,因为我最近 运行 遇到了同一个问题,发现它有点令人费解——当发出 OPTIONS 请求时,Django Rest Framework 使用视图的 Metadata class 构建响应。默认的Metadataclass是SimpleMetadata,相关代码提到in the docs. However, SimpleMetadata only adds the actions key to the response body if the view in question defines the method get_serializer(). I'm not sure why this is the case, but see here

rest_framework.generics.GenericAPIView defines a get_serializer() method,因此(已验证)OPTIONS 向这些视图发出的请求将 return 带有 actions 键的响应正文。但是 rest_framework.views.APIView 没有定义这个方法,所以 actions 键将永远不存在。

如果您必须使用 rest_framework.views.APIView,您可以通过在 APIView class 上定义一个 get_serializer() 方法来解决这个问题。感觉有点老套,但我测试了它并且有效:

class MyView(views.APIView):
    def get_serializer(self):
        return MySerializer()

    def post(self):
        ...