# 初始搭建开发环境
mkdir drf_learn5
cd drf_learn5/
virtualenv venv
source venv/bin/activate
pip install --upgrade pip
pip install django
pip install djangorestframework
pip install drf-yasg
pip freeze > requirements.txt
django-admin startproject myproject .
python manage.py startapp myapp
echo "success"
# 创建数据库并测试
python manage.py makemigrations myapp
python manage.py migrate
python manage.py runserver
# 创建用户的代码
python manage.py createsuperuser --username=joe --email=[email protected]
具体步骤
设置setting.py
INSTALLED_APPS = [
......
"rest_framework",
"drf_yasg",
"myapp",
]
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 10,
}
MIDDLEWARE = [
......
# "django.middleware.csrf.CsrfViewMiddleware",
......
]
编写model.py
from django.db import models
# Create your models here.
class book(models.Model):
book_name = models.TextField(verbose_name="书名")
file = models.FileField(verbose_name="书的文件", upload_to="book/uploads/%Y/%m/%d/")
编写serializers.py
from rest_framework import serializers
from myapp.models import book
class bookSerializers(serializers.ModelSerializer):
class Meta:
model = book
fields = "__all__"
编写 view.py
from django.http import FileResponse
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.decorators import action
from myapp.models import book
from myapp.serializers import bookSerializers
# Create your views here.
class bookViewSets(viewsets.ModelViewSet):
queryset = book.objects.all()
serializer_class = bookSerializers
@action(methods=["get", "post"], detail=True)
def download(self, request, pk=None, *args, **kwargs):
file_obj = self.get_object()
response = FileResponse(open(file_obj.file.path, "rb"), as_attachment=True)
return response
编写urls.py
from django.contrib import admin
from django.urls import include, path, re_path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from myapp.views import bookViewSets
from rest_framework import permissions
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r"books", bookViewSets, basename="books")
schema_view = get_schema_view(
openapi.Info(
title="Snippets API",
default_version="v1",
description="Test description",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="[email protected]"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path("admin/", admin.site.urls),
path("", include(router.urls)),
re_path(r"^swagger(?P<format>\.json|\.yaml)$", schema_view.without_ui(cache_timeout=0), name="schema-json"),
re_path(r"^swagger/$", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"),
re_path(r"^redoc/$", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"),
]
postman测试
查看apidoc
得到book列表
得到单个book
上传一本书
修改一个记录
修改一部分
删除
下载book
文档参考
electron下载并更新数据
https://juejin.cn/post/6959775555210346503
django文件上传实例
https://www.geeksforgeeks.org/django-upload-files-with-filesystemstorage/
django自带的文件管理类
https://docs.djangoproject.com/zh-hans/4.1/ref/files/storage/#django.core.files.storage.FileSystemStorage
django下载类
https://docs.djangoproject.com/zh-hans/4.1/ref/request-response/#fileresponse-objects
DRF下载实例
https://www.jianshu.com/p/369798f8e06e
api文档
https://pypi.org/project/drf-yasg/
下期预告
使用tokenauthentication完成用户系统
https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication