Django Rest Framework-如何路由到函数视图 [英] Django Rest Framework - How to route to a function view

查看:88
本文介绍了Django Rest Framework-如何路由到函数视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 Django Django Rest Framework 一起使用.

Django==2.0.2
djangorestframework==3.7.7

我正在尝试转到功能视图.

我当前的设置如下:

- project
    - project
        - urls
    - app
        - urls
        - views

project/urls 中,我像这样引用 app的 url:

In project/urls, I reference the app's urls like this:

url(r'^ app_api/',include('app_api.urls',namespace ='app_api'))

app/urls 中,我转到以下视图:

In app/urls, I route to the views like this:

router.register(r'', views.app_api, base_name="app_api")
url(r'', include(router.urls)),

app/views 中,我定义了一个名为 app_api 的函数,并用 api_view 装饰它.

In app/views I have defined a function called app_api and decorated it with api_view.

@api_view(['GET'])
def app_api(request):

例如,如果我运行服务器并使用 curl http://localhost:8080/app_api/,则会收到状态为200和空JSON的响应.

If I run the server and curl http://localhost:8080/app_api/ for example, I get a response with status 200 and a empty JSON.

"GET/app_api/HTTP/1.1" 200 2 {}

我不明白为什么会这样.如果我使用基于类的视图集,则可以使用,但不能用于函数视图.

I do not understand why this is happening. If I use a class based viewset, it works, but not with a function view.

使用 Django Rest Framework 时,路由到函数视图的正确方法是什么?

What is the correct way of routing to a function view when using Django Rest Framework?

谢谢!

推荐答案

我不明白您为什么在这里使用路由器.这些用于视图集:路由器为视图集生成所有URL端点.您只有一个视图;不管是类还是函数,都没有什么区别,就像在普通Django中一样,您需要为其声明一个显式终结点.

I don't understand why you are using a router here. Those are for viewsets: the router generates all URL endpoints for the viewset. You have a single view; it makes no difference if it's a class or function, you need to declare an explicit endpoint for it just like in plain Django.

这篇关于Django Rest Framework-如何路由到函数视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆