Django-rest-framework

凌经赋
2023-12-01

django-rest-framework简介

django-rest-framework,是一套基于Django 的 REST 框架,是一个强大灵活的构建 Web API 的工具包

官网:http://www.django-rest-framework.org/

使用django restful framework的原因

image 图片保存的是相当队列,访问的时候需要加上http://域名+图片相对路径

serializers没有帮我们加上,但是django-rest-framework帮我加上

serializers也没有排序,django-rest-framework帮我排序

文档生成等等很多功能

安装依赖的包

安装coreapi命令:pip install coreapi 

安装django-guardian命令:pip install django-guardian

安装 django-rest-framework 命令:pip install django-rest-framework

其它依赖包

The following packages are optional:

以下软件包是可选的:

1.setting.py注册app: 

#在项目的settings.py

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

    # demo add
    'rest_framework',
    'books',
]

2.配置url url.py: 

from django.contrib import admin
from django.conf.urls import url, include
from quickstart import views
from rest_framework import routers
from rest_framework.documentation import include_docs_urls 

router = routers.DefaultRouter() #路由
router.register(r'users', views.UserViewSet) #路由地址与接口配置
router.register(r'groups', views.GroupViewSet)

#注:path是新写法,url为老写法,若要使用正则,则使用re_path
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^', include(router.urls)), #包含进路由配置的url
    
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) #浏览器测试接口配置
]

3.返回json数据的方式:

在app应用中新建good/quickstart/serializers.py来重写serializers方法:

#方法1.基本序列化器
class Goodserializer(serializers.Serializer): 
    name = serializers.CharField(max_length=50) #字段需要自己写 
    #或
    class Meta:
        #Model
        model = GoodsCategory
        #把所有的属性都用上的写法
        fields = ('url', 'username', 'email', 'groups') #设置字段
#方法2:全部的序列化器,会自动调出所有字段
#(外键表)
class GoodsCategorySerializer(serializers.ModelSerializer):
   class Meta:
      #Model
      model = GoodsCategory
      #把所有的属性都用上的写法
      fields = "__all__"
 #(主表)
class Goodserializer(serializers.ModelSerializer):
    #关联外键
    category = GoodsCategorySerializer()
    class Meta:
        model = Goods
        fields = '__all__'

tutorial/quickstart/views.py视图中调用序列serializers 

from rest_framework import viewsets #引入viewsets,类似controllers
# from tutorial.quickstart.serializers import UserSerializer, GroupSerializer 官网模块引入写法,有误
from quickstart.serializers import UserSerializer, GroupSerializer #引入刚刚定义的序列化器

class GoodsListAPIView(generics.ListAPIView): 
    queryset = Goods.objects.all() 
    serializer_class = Goodserializer 

seeting中配置每页显示的数量

REST_FRAMEWORK = {
    #rest_framework目录下的pagination.py文件PageNumberPagination类
    'DEFAULT_PAGINATION_CLASS': "rest_framework.pagination.PageNumberPagination",
    # #每页显示10条数据
    'PAGE_SIZE': 2,
}

配置动态显示数据,动态设置每页数量: views.py:

class GoodsListPagination(PageNumberPagination):
   #默认返回10条
   page_size = 10
   #每页返回多少条的参数变量
   page_size_query_param = 'page_size'
   page_query_param = "p"#页码的定义
   #最大返回100条
   # max_page_size = 100
class GoodsListAPIView(generics.ListAPIView):
    queryset = Goods.objects.all()
    serializer_class = Goodserializer
    # 添加分页配置,settings.py就可以省略了
    pagination_class = GoodsListPagination

 #url访问格式:http://127.0.0.1:8000/goods/?p=3&page=2

viwes中viewsets方法及过滤,模糊查找,查询,排序.

#新建filters.py重写filters方法
from django_filters import rest_framework as filters
from .models import Goods
#商品的过滤器
class GoodsFilter(filters.FilterSet):
   #最低价格
   min_price = filters.NumberFilter(name="shop_price", lookup_expr='gte')
   #最大价格
   max_price = filters.NumberFilter(name="shop_price", lookup_expr='lte')
    #模糊查询
   name = filters.CharFilter(name='name',lookup_expr='icontains')
   class Meta:
      model = Goods
      fields = [ 'min_price', 'max_price','name']


#views.py (上述views中方法的替代)
class GoodsListAPIViewSet(viewsets.GenericViewSet,mixins.ListModelMixin):
    queryset = Goods.objects.all()
    serializer_class = Goodserializer
    # 添加分页配置,settings.py就可以省略了
    pagination_class = GoodsListPagination

    #过滤器
    filter_backends = (DjangoFilterBackend,filters.OrderingFilter,filters.SearchFilter)
    filter_class = GoodsFilter
    ordering_fields = ('shop_price','add_time')
    # '^name'必须以name开头才会满足搜索条件,'=name'为精确搜索
    search_fields = ('name', 'goods_brief','goods_desc')
#排序
from rest_framework import filters
class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
   """
   返回商品列表,自定义序列化器,分页,过滤,搜索,排序
   """   
   #支持搜索和过滤,写在一起
   filter_backends = (filters.OrderingFilter,filters.SearchFilter,DjangoFilterBackend)
   ordering_fields = ('shop_price', 'add_time')

Django的跨域问题,后端部分比较常用的做法就是利用django-cors-headers模块来解决,这里也不能免俗,操作如下

先在命令行中进行对应模块的安装:

pip install django-cors-headers

然后在项目中添加该模块:

# books_demo/settings.py
INSTALLED_APPS = [
    ...
    # demo
    'corsheaders',
    ...
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware', # 需注意与其他中间件顺序,这里放在最前面即可
    ...
]

# 支持跨域配置开始
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True 

 

 

 类似资料: