Django2.0生成接口文档
1.创建模型
models.py
from django.db import models
# Create your models here.
class UserInfo(models.Model):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=255)
password = models.CharField(max_length=255)
2.创建序列化:
serializer.py
from rest_framework import serializers
from app import models
class MySerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = ['id', 'username', 'password']
depth = 0
extra_kwargs = {
'username': {
'min_length': 2,
'max_length': 12,
'error_messages': {
'min_length': '6个字符',
'max_length': '12个字符',
},
},
'password': {
'help_text': '密码6-8位',
}
}
3.创建视图
views.py
####执行简单的增删改查
@method_decorator(csrf_exempt,name="dispatch") class UserInfoView(viewsets.ModelViewSet):
"""
list:
返回所有项目信息
create:
创建项目
retrieve:
获取某个项目的详细信息
update:
更新项目
destroy:
删除项目
queryset = models.UserInfo.objects.all()
serializer_class = MySerializer
####执行复杂的查询建议使用APIView
class UserDetailView(APIView):
"""
根据id和username查询
"""
def get(self,request,id,username):
id = id
username = username
datas = models.UserInfo.objects.filter(username=username).first()
res = MySerializer1(instance=datas,many=False)
return Response(res.data)
4.编写路由
urls.py
from rest_framework.documentation import include_docs_urls
from app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/order/',views.UserInfoView.as_view({'get': 'list',"post":'create'})),
path('api/v1/user/<int:id>/<str:username>', views.UserDetailView.as_view()),
path('docs/',include_docs_urls(title="接口测试平台API"))
]
5.页面


浙公网安备 33010602011771号