快速入手-Django-rest-framework(一)

1、安装 Django REST Framework

pip install djangorestframework
2、快速构建django项目基本结构,参考以下链接创建api模块,并注册应用

快速入手-Django项目创建(一)-CSDN博客

3、添加到   INSTALLED_APPS  

 INSTALLED_APPS = [
    ...
    'rest_framework',
]

4、在api模块里创建urls.py

from django.urls import path
from . import views

app_name = "api"
urlpatterns = [
    path("", views.index.as_view(), name="index"),
]

5、在总的urls.py配置



from django.contrib import admin
from django.urls import path, include

from app_drf01 import views

urlpatterns = [
    
    path("api/", include(("api.urls", "api"), namespace="api")),
  
]

6、编写views.py

from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response

# Create your views here.


class index(APIView):
    def get(self, request):
        return Response({"message": "Get Hello, world!"})

    def post(self, request):
        return Response({"message": "Post Hello, world!"})

 7、运行

python manage.py runserver

8、访问http://127.0.0.1:8000/api/

快速入手-Django-rest-framework(一)_第1张图片

你可能感兴趣的:(django)