写一个Django-rest的测试接口要求返回数据是helloword
时间: 2023-06-26 12:10:28 浏览: 70
好的,以下是一个简单的Django-rest框架中返回"hello world"的测试接口:
首先,安装Django和Django-rest-framework:
```
pip install django
pip install djangorestframework
```
然后,在Django项目中创建一个app,比如叫做"testapp":
```
python manage.py startapp testapp
```
在testapp/views.py中写下以下代码:
```python
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def hello_world(request):
return Response("hello world")
```
这个视图函数使用`@api_view`装饰器来指定HTTP请求的方法,这里使用GET方法。当请求到达这个视图函数时,它将返回一个包含"hello world"的响应,使用`Response`对象实现。
最后,将这个视图函数添加到testapp/urls.py中:
```python
from django.urls import path
from .views import hello_world
urlpatterns = [
path('hello-world/', hello_world),
]
```
这里创建了一个URL路由,将`/hello-world/`映射到`hello_world`视图函数。
现在,启动Django服务器并访问`http://localhost:8000/hello-world/`,您应该会看到"hello world"的响应了。