使用Django REST framework开发RESTful API接口 1

新建项目

修改settings.py文件,后面会贴出完整的文件。

根目录新建static文件夹。
生成数据表

python manage.py makemigrations
python manage.py migrate

创建管理员账号

python manage.py createsuperuser

运行项目,输入http://127.0.0.1:8000/amdin,进入后台,使用账户登陆。

配置项目

安装需要的包
打开 rest framework官方网站,查看需要引入的包。

在项目根目录新建requirements.txt文件,将需要安装的包复制进去。可以参考我这边文章进行安装,Python批量安装.Txt文件中的类库包

asgiref==3.2.7
certifi==2020.4.5.1
chardet==3.0.4
coreapi==2.3.3
coreschema==0.0.4
Django==3.0.6
django-filter==2.2.0
djangorestframework==3.11.0
idna==2.9
importlib-metadata==1.6.0
itypes==1.2.0
Jinja2==2.11.2
Markdown==3.2.2
MarkupSafe==1.1.1
Pygments==2.6.1
pytz==2020.1
requests==2.23.0
sqlparse==0.3.1
uritemplate==3.0.1
urllib3==1.25.9
zipp==3.1.0

打开 rest framework官方网站,参考官方文档对项目进行配置。
完成配置文件,带注释


"""
Django settings for drf-tutorial project.

Generated by "django-admin startproject" using Django 3.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "#3(vjynordxvt)er)h9hk*h#h7z@5wawz$usb^immomrb6e$wi"

# SECURITY WARNING: don"t run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",  # RESTful API
    "rest_framework.authtoken",  # DRF自带的token认证
    "course.apps.CourseConfig",  # 新建项目添加course应用的时候自动生成的
]

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-tutorial.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-tutorial.wsgi.application"

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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = "zh-hans"

TIME_ZONE = "Asia/Shanghai"

USE_I18N = True

USE_L10N = True

USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = "/static/"

# 存放前端文件
STATIC_ROOT = os.path.join(BASE_DIR, "static")
#
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "staticfiles"),
]


# 全局配置
REST_FRAMEWORK = {

    "DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema",
    # 分页类
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    # 每页需要显示多少条数据
    "PAGE_SIZE": 50,
    # 设置时间格式
    "DATETIME_FORMAT": "%Y-%m-%d %H:%M:%S",
    # 返回对象所需要的类 默认就是这个 可以不写
    "DEFAULT_RENDERER_CLASSES": [
        "rest_framework.renderers.JSONRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ],
    "DEFAULT_PARSER_CLASSES": [  # 解析request.data
        "rest_framework.parsers.JSONParser",
        "rest_framework.parsers.FormParser",
        "rest_framework.parsers.MultiPartParser",
    ],
    # 权限
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
    # 认证
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.BasicAuthentication",
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ]
}



修改完成以后执行一下生成数据表命令。

修改路由配置
打开urls.py,在urlpatterns列表里面添加rest_framework.urls路由

urlpatterns = [
  		 path("api-auth/", include("rest_framework.urls")),  # DRF的登录退出
  	 	 path("admin/", admin.site.urls),
   	]

创建模型

from django.db import models
from django.conf import settings


class Course(models.Model):
    name = models.CharField(max_length=255, unique=True, help_text='课程名称', verbose_name='名称')
    introduction = models.TextField(help_text='课程介绍', verbose_name='介绍')
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE
                                , help_text='课程讲师', verbose_name='讲师')
    price = models.DecimalField(max_digits=6, decimal_places=2, help_text='课程价格', verbose_name='价格')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '课程信息'
        verbose_name_plural = verbose_name
        ordering = ('price',)

    def __str__(self):
        return self.name

数据添加到后台,可以方便直接从后台添加数据
打开admin.py,添加

from django.contrib import admin

from .models import Course


@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
    # 需要显示的字段
    list_display = ("name", "introduction", "teacher", "price")
    # 可以搜索的字段
    search_fields = list_display
    # 过滤的字段
    list_filter = list_display

修改完成以后执行一下生成数据表命令。

你可能感兴趣的:(Python)