【Django进阶】Django--restframework学习

发布时间 2023-11-15 08:22:28作者: 小C学安全

创建Django项目

django-admin.exe startproject restf

创建Django应用程序

django-admin.exe startapp restf01

安装

版本要求:djangorestframework==3.12.4
    Python (3.5, 3.6, 3.7, 3.8, 3.9)
    Django (2.2, 3.0, 3.1)
    
版本要求:djangorestframework==3.11.2
    Python (3.5, 3.6, 3.7, 3.8)
    Django (1.11, 2.0, 2.1, 2.2, 3.0)

注册rest_framework

INSTALLED_APPS = [
    ...
    # 注册rest_framework(drf)
    'rest_framework',
]
 
# drf相关配置以后编写在这里 必须是这个名字
REST_FRAMEWORK = {
   
}

基本使用

项目目录下url.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'users/',include(('users.urls', 'users'), namespace='users'))
]

应用程序下新建urls.py

from django.urls import path,re_path,include
from users import views

urlpatterns = [
    re_path(r'info', views.UserInfoViewSet.as_view(), name='user'),
]

views.py

from rest_framework.views import APIView
from django.http import JsonResponse

class UserInfoViewSet(APIView):
    def __init__(self):
        super(UserInfoViewSet, self).__init__()

    def get(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'get data'
        }
        return JsonResponse(result, status=200)

    def post(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'post data'
        }
        return JsonResponse(result, status=200)

http://127.0.0.1:8000/users/info GET访问