liangfengshuang

dft实战和源码剖析-学习笔记2

4. 初步编写API

3-02 drf-初步使用

drf项目下创建虚拟环境

1.PS D:> django-admin startproject drf d盘下创建drf项目
2.PS D:> cd drf
3.PS D:\drf> virtualenv -p "C:\Program Files\Python311\python.exe" .venv
4.d:\pyproject 项目目录下,虚拟环境执行pip freeze >requirements.txt(很多类似包)
5.剪切requirements.txt 到d:\dfr
6.(.venv) D:\drf>pip3 install -r requirements.txt

1. 基于django实现:

vscode下创建app01

(.venv) D:\drf>python manage.py startapp app01
  • 剔除setting中暂用不到的条目(#),数据库本次使用默认
# Application definition

INSTALLED_APPS = [
    #'django.contrib.admin',
    #'django.contrib.auth',
    #'django.contrib.contenttypes',
    #'django.contrib.sessions',
    #'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    #'django.contrib.auth.middleware.AuthenticationMiddleware',
    #'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'drf.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                #'django.contrib.auth.context_processors.auth',
                #'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'drf.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

setting

INSTALLED_APPS = [
    #'django.contrib.admin',
    #'django.contrib.auth',
    #'django.contrib.contenttypes',
    #'django.contrib.sessions',
    #'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config'

·urls

#from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    #path('admin/', admin.site.urls),
    path('auth/', views.auth),
    
]

views

#from django.shortcuts import render,不需要前端了
from django.http import JsonResponse

# Create your views here.


def auth(request):
    return JsonResponse({'status':True,'message':"success"})
(.venv) D:\drf>python manage.py runserver

image-20231130102607846

image-20231130105433718

2. 基于drf实现:

安装drf,本质是一个app

(.venv) D:\drf>pip3 install djangorestframework
...
Successfully installed djangorestframework-3.14.0
  • 先注册settings
# Application definition

INSTALLED_APPS = [
    #'django.contrib.admin',
    #'django.contrib.auth',
    #'django.contrib.contenttypes',
    #'django.contrib.sessions',
    #'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework'
]

2.1 基于函数#基于函数FBV(function base view)

urls:

#from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    #path('admin/', admin.site.urls),
    path('auth/', views.auth),
    path('login/', views.login),
    
]

views:

#from django.shortcuts import render,不需要前端了
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import api_view #需增加装饰器

# Create your views here.


def auth(request):
    return JsonResponse({'status':True,'message':"success"})

@api_view(["GET"]) #注意列表中字符串
def login(request):
    return Response({'status':True,'message':"success"})

嵌套数据,返回好看页面(drf)

http://127.0.0.1:8000/login/?format=json
#返回json格式

运行报错:

    raise RuntimeError(
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
[30/Nov/2023 11:11:57] "GET /login/ HTTP/1.1" 500 185811

settings:

# Application definition

INSTALLED_APPS = [
    #'django.contrib.admin',
    #'django.contrib.auth',
    #'django.contrib.contenttypes',
    #'django.contrib.sessions',
    #'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework'
]
REST_FRAMEWORK = {
    "UNAUTHENTICATED_USER": None,
    "UNAUTHENTICATED_TOKEN": None,
}

重启python

image-20231130113724599

image-20231130111944348

image-20231130113220482

但是:postman:

image-20231130112120215

以上正常

2.2 基于类class(CBV)

urls:(path('loginclass/', views.InfoView.as_view()),#基于类 )

#from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    #path('admin/', admin.site.urls),
    path('auth/', views.auth),
    path('login/', views.login),#基于函数
    path('loginclass/', views.InfoView.as_view()),#基于类    
    
]

views:(from rest_framework.views import APIView #基于类,class InfoView(APIView)😃

后面多用此法

#from django.shortcuts import render,不需要前端了
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import api_view #需增加装饰器

from rest_framework.views import APIView  #基于类

# Create your views here.


def auth(request):
    return JsonResponse({'status':True,'message':"success"})

@api_view(["GET"])
def login(request):
    return Response({'status':True,'message':"success"})

#基于类
class InfoView(APIView): 
    def get(self,request):    
        return Response({'status':True,'message':"success"})

image-20231130115225359

posted on 2023-12-14 08:53  liangfengshuang  阅读(115)  评论(0编辑  收藏  举报

导航