简体   繁体   English

Django Rest Framework API

[英]Django rest framework api

I want to add to my Django project (using Django rest framework ) new get function. 我想将新的get函数添加到我的Django项目中(使用Django rest框架)。 I want it to just send to me in Json "Hello world" without writing or without opening a table in the DB this is my code: 我希望它仅在Json“ Hello world”中发送给我,而无需编写或在DB中打开表,这是我的代码:

@api_view()
def about(request):
    return Response({"message": "Hello, world!"})

i put it in view.py what more i should do the make it work? 我把它放在view.py中,我还应该做些什么呢? when i run the server and write this lines 当我运行服务器并编写此行

http://127.0.0.1:8000/about

i want it to saw me " {"message": "Hello, world!"} " 我希望看到我“ {"message": "Hello, world!"}

Update your 'urls.py': 更新您的“ urls.py”:

urlpatterns = patterns('',
    ...
    url(r'^about/$', views.about),
    ...

I think you should register url path to urls.py first. 我认为您应该先将url路径注册到urls.py And then update settings.py. 然后更新settings.py。

Here are some instructions for you about Django rest framework quickstart. 以下是一些有关Django rest框架快速入门的说明。 http://www.django-rest-framework.org/tutorial/quickstart/ http://www.django-rest-framework.org/tutorial/quickstart/

To send parameters you can added them in the URL and ask for request.GET inside your function, even you can make a POST and ask for request.data inside your function. 要发送参数,您可以将其添加到URL中并在函数内部请求request.GET,甚至可以进行POST并在函数内部请求request.data。

your url: /about/?start_date=2016/08/20&end_date=2016/08/21 您的网址:/ about /?start_date = 2016/08/20&end_date = 2016/08/21

def about(self, request, *args, **kwargs):
    """"
    Is called by a GET method.
    ISO format: YYYY/MM/DD and in UTC.
    """

    start_date_str = request.GET.get("start_date")
    end_date_str = request.GET.get("end_date")

    return Response({"message": "Hello, world!"})

Another way: 其他方式:

Your url: /about/100/ 您的网址:/ about / 100 /

urlpatterns = patterns('',
...
url(r'^about/(?P<object_pk>[0-9]+)/$', views.example),
...

def example(self, request, object_pk, *args, **kwargs):
    """"
    Is called by a GET method.
    """
    # do something with your object

    return Response({"message": "Hello, world!"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM