代码之家  ›  专栏  ›  技术社区  ›  Alberto Diaz

如何使用django rest框架在选项请求中返回动作和参数

  •  1
  • Alberto Diaz  · 技术社区  · 7 年前

    我尝试返回使用django countries和django rest框架的国家的选择选项列表。我使用JWT\u 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
            }
        }
    }
    

    }

    有人能帮我吗?谢谢

    3 回复  |  直到 5 年前
        1
  •  1
  •   Linovia    7 年前

    • name 是视图的 get_view_name
    • description 是视图的 get_view_description 它重写了视图的docstring。

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

        2
  •  0
  •   Alberto Diaz    7 年前

    我找到了解决办法。

    我将视图类类型从 APIView generics.CreateAPIView 并且知道它是有效的。非常感谢你。

        3
  •  0
  •   Samira N    3 年前

    添加另一个答案,因为我最近遇到了同一个问题,并发现它有点神秘-当作出一个 OPTIONS 请求时,Django Rest框架使用视图的 Metadata 类来构造响应。默认值 元数据 班级是 SimpleMetadata ,如前所述 in the docs . 然而 , 单纯形数据 actions 如果有问题的视图定义了方法,则返回响应体的键 get_serializer() . 我不知道为什么会这样,但是你看 here 有关代码。

    rest_framework.generics.GenericAPIView defines a get_serializer() method ,so(已验证) 对这些视图的请求将返回带有 行动 钥匙但是 rest_framework.views.APIView 没有定义此方法,因此 钥匙总是不在。

    如果你必须使用 rest_框架。意见。APIView公司 ,您可以通过定义 get_serializer() 方法。这感觉有点粗糙,但我测试了它,它工作了:

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