Django REST框架是一个用于构建Web API的功能强大且灵活的工具包html
REST框架的强大功能:前端
使用REST框架的要求git
如下软件包是可选的github
安装django
使用pip安装,以及任何你须要安装的软件包 注:安装djangorestframework以前必定要先安装djangoapi
pip install djangorestframework
pip install markdown
pip install django-filter
或者从github克隆项目浏览器
git clone git@github.com:encode/django-rest-framework.git
将'rest_framework'添加的django的settings.py的INSTALLED_APPS设置中markdown
INSTALLED_APPS = ( ... 'rest_framework', )
添加到urls.py文件中,便可使用可浏览的API框架
from django.conf.urls import url, include urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls')) ]
REST框架API的任何全局设置都保存在一个名为REST_FRAMEWORK的配置字典中,首先要将内容配置到settings.py模块中工具
举例说明:
咱们来建立一个API来对咱们对数据进行分页
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, # 每页显示多少条数据 }
首先对咱们对数据进行序列化,在当前项目中建立serializers.py文件
from rest_framework import serializers from goods.models import Goods, GoodsCategory # django的model class GoodsCategorySerializer(serializers.ModelSerializer): class Meta: model = GoodsCategory fields = "__all__" # fields须要在页面显示的数据内容 class GoodsSerializer(serializers.ModelSerializer): category = GoodsCategorySerializer() class Meta: model = Goods # fields = ("category", "name", "market_price", "add_time", "goods_front_image") fields = "__all__"
建立视图,views.py
from .models import Goods from .serializers import GoodsSerializer from rest_framework import mixins from rest_framework import viewsets class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Goods.objects.all() serializer_class = GoodsSerializer
urls.py
from django.conf.urls import url, include from rest_framework.documentation import include_docs_urls from goods.views import GoodsListViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'goods', GoodsListViewSet) urlpatterns =[ url(r'^api-auth/', include('rest_framework.urls')), url(r'^', include(router.urls)), ]
如今就能够经过http://127.0.0.1:8000/goods/的浏览器中打开该API,并查看新的“用户”API。若是您使用右上角的登陆控件,您还能够从系统添加,建立和删除用户。
拓展功能,若是你须要自定制分页内容,好比:每页最多显示多少条数据,你想要在这一页像后台指定访问多少条数据,下一页页码标示等
views.py更改以下
from .models import Goods from .serializers import GoodsSerializer from rest_framework import mixins, generics from rest_framework.pagination import PageNumberPagination from rest_framework import viewsets class GoodsSetPagination(PageNumberPagination): page_size = 10 # 每一天显示10条数据 page_size_query_param = 'page_size' # 像后台请求前端要显示页码的大小(条数) page_query_param = 'p' # 浏览器导航栏下一页的提示 max_page_size = 100 # 每页最多显示多少条 class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Goods.objects.all() serializer_class = GoodsSerializer pagination_class = GoodsSetPagination
将settings.py模块中如下内容注释掉,由于views.py中的
class GoodsSetPagination(PageNumberPagination)以及继承了
PageNumberPagination
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, # 每页显示多少条数据 }
组成REST框架的构建块,它会让你全面了解全部内容组合到一块儿的强大功能,强烈推荐学习
API指南