django-rest-framework
环境的配置1、官网地址下查看支持的django
版本及安装几个主要的包
pip install coreapi
pip install Markdown
pip install django-filter
pip install django-crispy-forms
pip install django-guardian
2、利用pycharm
创建一个django
项目
3、setting.py
的基本配置
1、配置编码
#!/usr/bin/env python
# encoding: utf-8
2、修改国内时间及支持中文
#设置时区
LANGUAGE_CODE = 'zh-hans' #中文支持,django1.8以后支持;1.8以前是zh-cn
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False #默认是Ture,时间是utc时间,由于我们要用本地时间,所用手动修改为false
3、配置mysql
数据库引擎
# 配置数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'vueshop',
'USER': 'root',
'PASSWORD': "root",
'HOST': "127.0.0.1",
'OPTIONS': {'init_command': 'SET storage_engine=INNODB;'} # 数据库引擎
}
}
4、把rest_framework
加入到注册的app
中
5、在urls.py
中配置下
from django.conf.urls import url, include
from rest_framework.documentation import include_docs_urls
urlpatterns = [
....
url(r'^api-auth/', include('rest_framework.urls')),
url(r'docs/', include_docs_urls(title='接口学习'))
]
APIView
创建返回第一个接口1、关于serializers
的认识
在传统的使用模板开发中我相信我们一个
app
里面都会创建一个forms.py
的文件,来校验客户端传递过来的数据,serializers
则是django-rest-framework
封装了一层类似forms.py
的功能,只是对json
的校验
2、书写一个serializers
(字段要和models.py
中保持一致,一个app
下一个serializers.py
文件)
from rest_framework import serializers
class GoodsSerializer(serializers.Serializer):
name = serializers.CharField(required=True, max_length=100)
click_num = serializers.IntegerField(default=0)
3、定义view
继承APIView
from .serializers import GoodsSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Goods
class GoodsListView(APIView):
def get(self, request, format=None):
goods = Goods.objects.all()[:10] # 只查询10条数据
goods_serializer = GoodsSerializer(goods, many=True)
return Response(goods_serializer.data)
4、配置url
from goods.views import GoodsListView
urlpatterns = [
url(r'^goods/$', GoodsListView.as_view()),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'docs/', include_docs_urls(title='接口测试学习'))
]
post
提交数据,保存到数据库中1、在serializers.py
中添加一个create
的函数
class GoodsSerializer(serializers.Serializer):
name = serializers.CharField(required=True, max_length=100)
click_num = serializers.IntegerField(default=0)
market_price =serializers.FloatField(default=0)
def create(self, validated_data):
"""
validated_data会把上面全部的字段接收
"""
return Goods.objects.create(**validated_data)
2、视图层使用post
from rest_framework import status
class GoodsListView(APIView):
def get(self, request, format=None):
goods = Goods.objects.all()[:10]
goods_serializer = GoodsSerializer(goods, many=True)
return Response(goods_serializer.data)
def post(self, request,format=None):
serializer = GoodsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
ModelSerializer
来书写serializer
1、书写serializer
from rest_framework import serializers
from .models import Goods
class GoodsSerializersModel(serializers.ModelSerializer):
"""
使用ModelSerializer更加简便的返回自己想要的字段
"""
class Meta:
model = Goods
fields = ('name', 'click_num', 'market_price', 'add_time')
2、视图层跟上面APIView
中一样的写
url
也跟上面APIView
的goods
的一样ModelSerializer
如果要返回全部的字段1、修改上面的serializer
class GoodsSerializersModel(serializers.ModelSerializer):
"""
使用ModelSerializer更加简便的返回自己想要的字段
"""
class Meta:
model = Goods
# fields = ('name', 'click_num', 'market_price', 'add_time')
fields = '__all__'
2、其它的都保持不变
json
外键都是一个id
并没有把外键关联的表的数据也返回1、序列化外键的表
class CategorySerializer(serializers.ModelSerializer):
"""
序列化分类表
"""
class Meta:
model = GoodsCategory
fields = '__all__'
2、在别的serializers
中实例化
class GoodsSerializersModel(serializers.ModelSerializer):
"""
使用ModelSerializer更加简便的返回自己想要的字段
"""
# 实例化上面的分类表的序列号
category = CategorySerializer()
class Meta:
model = Goods
# fields = ('name', 'click_num', 'market_price', 'add_time')
fields = '__all__'