统一使用的utils,serializers:

class BaseResponse:

    def __init__(self):
self.code = 1000
self.data = None
self.error = None @property
def dict(self):
return self.__dict__

版本1:

from django.conf.urls import url
from api.views import course
from api import views urlpatterns = [
url(r"courses/$",course.CoursesView.as_view()),
url(r"courses/(?P<pk>\d+)/$",course.CourseDetailView.as_view()), ]

urls

from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from rest_framework.versioning import URLPathVersioning
from rest_framework.response import Response
from api.serializers import course
from api import models
from api.utils.response import BaseResponse
from rest_framework.pagination import PageNumberPagination class CoursesView(APIView): def get(self,request,*args,**kwargs):
result = BaseResponse()
try:
queryset = models.Course.objects.all()
# 分页
page = PageNumberPagination()
course_list = page.paginate_queryset(queryset,request,self) # 分页之后的结果执行序列化
# 分页之后必须在序列化类中加上:instance=course_list
ser = course.CourseSerializers(instance=course_list,many=True)
# ser_obj = course.CourseSerializers(queryset,many=True) result.data = ser.data
# result.data = ser_obj.data
except Exception as e:
result.code = 500
result.error = "无法获取数据"
return Response(result.dict) class CourseDetailView(APIView):
def get(self,request,pk,*args,**kwargs):
result = BaseResponse()
try:
course_obj = models.Course.objects.get(id=pk)
ser_obj = course.CourseSerializers(instance=course_obj)
result.data = ser_obj.data
except Exception as e:
result.code = 500
result.error = "无法获取数据" return Response(result.dict)

views

# from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from api import models class CourseSerializers(serializers.ModelSerializer):
level = serializers.CharField(source="get_level_display")
class Meta:
model = models.Course
fields = "__all__"
depth = 5 class DegreeSerializers(serializers.ModelSerializer):
teacher_name = serializers.SerializerMethodField()
# teacher_name = serializers.CharField(source="teachers.")
class Meta:
model = models.DegreeCourse
fields = ["name","teacher_name"] def get_teacher_name(self,row):
teacher_list = row.teachers.all()
return [{"name": i.name } for i in teacher_list] class DegreeScholarSerializers(serializers.ModelSerializer):
# scholar = serializers.CharField(source="scholarship_set.all")
scholar = serializers.SerializerMethodField()
class Meta:
model = models.DegreeCourse
fields = ["name","scholar"] def get_scholar(self,row):
scholar_list = row.scholarship_set.all()
return [{"scholar": i.value} for i in scholar_list] class DegreeMokuaiSerializers(serializers.ModelSerializer):
# degree_mokuai = serializers.CharField(source="")
# print(111)
class Meta:
model = models.DegreeCourse
fields = ["name"]
# fields = "__all__" class Course_Serializers(serializers.ModelSerializer):
level = serializers.CharField(source="get_level_display")
why_study = serializers.CharField(source="coursedetail.why_study")
what_to_study_brief = serializers.CharField(source="coursedetail.what_to_study_brief")
recommend_courses = serializers.SerializerMethodField()
class Meta:
model = models.Course
fields = ["name","level","why_study","what_to_study_brief","recommend_courses"] def get_recommend_courses(self,row):
recomment_list = row.coursedetail.recommend_courses.all()
return [{"id":item.id,"name":item.name} for item in recomment_list] class CourseQuestionSerializer(serializers.ModelSerializer):
# question = serializers.CharField(source="asked_question.all")
question = serializers.SerializerMethodField()
class Meta:
model = models.Course fields = ["name","question"] def get_question(self,row):
question_list = row.asked_question.all()
return [{"question":i.question,"answer":i.answer} for i in question_list] class CourseOutlineSerializers(serializers.ModelSerializer):
courseoutline = serializers.SerializerMethodField()
class Meta:
model = models.Course
fields = ["name","courseoutline"]
# fields = "__all__" def get_courseoutline(self,row):
outline_list = row.coursedetail.courseoutline_set.all()
return [{"courseoutline":i.title,"content":i.content} for i in outline_list] class CourseChapterSerializers(serializers.ModelSerializer):
course_chapter = serializers.SerializerMethodField() class Meta:
model = models.Course
fields = ["name","course_chapter"] def get_course_chapter(self,row):
course_chapter_list = row.coursechapters.all()
return [{"chapter": i.name} for i in course_chapter_list]

serializers

版本2:

  urls:

from django.conf.urls import url
from api.views import course
from api import views urlpatterns = [
# 如果as_view()里面要传参数的话,前提视图CBV必须继承 ViewSetMixin ,这样才能往as_view()中传入参数。
# 键值对的形式,表明了各请求方式对应的方法,所以特定的请求方式,便可执行相应的方法。
# 如果as_view()里写了相应的键值对,在视图CBV中必须写出相应的方法。 url(r'courses/$',course.CoursesView.as_view({'get':'list','post':'create'})), url(r'courses/(?P<pk>\d+)/$',course.CoursesView.as_view({'get':'retrieve','put':'update','delete':'destroy'}))
]

  views:

from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from rest_framework.versioning import URLPathVersioning
from rest_framework.response import Response
from api.serializers import course
from api import models
from api.utils.response import BaseResponse
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ViewSetMixin # 继承ViewSetMixin
class CoursesView(ViewSetMixin,APIView):
def list(self,request,*args,**kwargs):
result = BaseResponse()
try:
# 从数据库中获取数据
queryset = models.Course.objects.all()
ser_obj = course.CourseSerializers(queryset,many=True) result.data = ser_obj.data
except Exception as e:
result.code = 500
result.error = "无法获取数据"
return Response(result.dict) def create(self,request,*args,**kwargs):
'''
post方式,增加
:param request:
:param args:
:param kwargs:
:return:
'''
def retrieve(self,request,pk,*args,**kwargs):
'''
详细显示
:param request:
:param pk:
:param args:
:param kwargs:
:return:
'''
result = BaseResponse()
try:
course_obj = models.Course.objects.get(id=pk)
ser_obj = course.CourseSerializers(instance=course_obj)
# print(ser_obj)
result.data = ser_obj.data
# print(result.data)
except Exception as e:
result.code = 500
result.error = "无法获取数据"
return Response(result.dict) def update(self,pk,*args,**kwargs):
'''
put,更改
:param pk:
:param args:
:param kwargs:
:return:
''' def destroy(self,pk,*args,**kwargs):
'''
delete ,删除
:param pk:
:param args:
:param kwargs:
:return:
'''

版本3:

  urls:

from django.conf.urls import url
from api.views import course
from api import views urlpatterns = [
# 如果as_view()里面要传参数的话,前提视图CBV必须继承 ViewSetMixin ,这样才能往as_view()中传入参数。
# 键值对的形式,表明了各请求方式对应的方法,所以特定的请求方式,便可执行相应的方法。
# 如果as_view()里写了相应的键值对,在视图CBV中必须写出相应的方法。 url(r'courses/$',course.CoursesView.as_view({'get':'list'})), url(r'courses/(?P<pk>\d+)/$',course.CoursesView.as_view({'get':'retrieve'}))
]

  views:

from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from rest_framework.versioning import URLPathVersioning
from rest_framework.response import Response
from api.serializers import course
from api import models
from api.utils.response import BaseResponse
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ViewSetMixin
from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,ListModelMixin
from rest_framework.viewsets import GenericViewSet class CoursesView(ListModelMixin,GenericViewSet):
queryset = models.Course.objects.all()
def list(self,request,*args,**kwargs):
result = BaseResponse()
try:
course_list = models.Course.objects.all()
ser_obj = course.CourseSerializers(course_list,many=True)
result.data = ser_obj.data
except Exception as e:
result.code = 500
result.error = "无法获取数据"
return Response(result.dict) def retrieve(self,request,pk,*args,**kwargs):
result = BaseResponse()
try:
course_obj = models.Course.objects.get(id=pk)
ser_obj = course.CourseSerializers(course_obj)
result.data = ser_obj.data
except Exception as e:
result.code = 500
result.error = "无法获取数据"
return Response(result.dict)

符合RESTful规范的API的更多相关文章

  1. yii2restful规范的api使用

    说明:restful是一套优秀的接口调用规范. 使用规范: 1,安装yii2 使用composer安装 安装完 Composer,运行下面的命令来安装 Composer Asset 插件: php c ...

  2. [01] 浅谈RESTful风格的API

    1.什么是RESTful风格的API REST,即Representational State Transfer,可以理解为"(资源的)表现层状态转化". 在网络上,我们通过浏览器 ...

  3. restful规范和restframework框架

    什么是接口? 接口可以理解为url就是接口. 那么在其他语言里面接口也可以是约束类 restful规范是什么? RESTful是目前最流行的一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便 ...

  4. django中的restful规范

    基于django的原生restful规范 主路由:url.py from django.conf.urls import url, include from django.contrib import ...

  5. restful规范与rest_framework

    django两种开发模式: 一.前后端不分离项目 二.前后端分离项目 什么是restful规范? 在前后端不分离的项目中,网页所需要的数据可以直接通过模板渲染的方式传递到前端页面,并且可以很好的支持d ...

  6. Restframework框架总结及restful规范

    1. django rest framework框架的作用? 帮助开发者可以快速开发出遵循restful规范的API 2. django rest framework框架都有哪些组件(10)? -版本 ...

  7. 基于Django的Rest Framework框架的RESTful规范研究

    一.什么是RESTful规范 总的来说:RESTful规范就是一个非技术,人为约定的一个面向资源的架构理念. REST与技术无关,代表的是一种软件架构风格,REST是Representational ...

  8. 测开大佬告诉你:如何5分钟快速创建restful风格的API接口-使用django restframework框架

    一.思考❓❔ 1.创建API接口难吗? 软件测试工程师: 只测过API接口, 从没创建过 应该需要掌握一门后端开发语言和后端开发框架吧!? 脑容量有限,想想就可怕 2.如何创建API接口呢? 使用Dj ...

  9. RESTful 规范

    RESTful 规范 前言 rest 是一种软件架构风格,如果使用的是 rest 接口,那么就可以说你的接口是 restful. rest接口是围绕''资源''展开的,利用 HTTP 的协议,其实 r ...

随机推荐

  1. [osgearth]oe学习的一些经验(别人的)

    参考:http://bbs.osgchina.org/forum.php?mod=viewthread&tid=5484&extra=page%3D1&_dsign=70b15 ...

  2. xargs -i的用法

    find ... | 后面跟文件,就需要用到xargs,其中-i加{}就能替代管道符之前的文件(标准输出的内容) 在/tmp下创建6个文件,1.txt,2.txt,3.txt,4.txt,5.txt, ...

  3. 安装完Linux Mint后,发现系统中竟没有中文输入法

    安装完Linux Mint后,发现系统中竟没有中文输入法,语言支持之后自动更新过程中有些安装包下载失败. 可以采取下面的方法安装上中文输入法. 1. 安装iBus: sudo add-apt-repo ...

  4. BZOJ2314 士兵的放置

    树形DP,恩然后就不会了... 先写了个错的离谱程序...果然WA了 然后开始乱搞,欸,对了! 令f[i], g[i], h[i]分别表示i号节点自己放士兵,被儿子上的士兵控制,不被儿子上的士兵控制但 ...

  5. openfalcon源码分析之hbs

    openfalcon源码分析之hbs 本节内容 hbs功能 hbs源码分析 hbs设计优劣 1. hbs功能 hbs在整个open-falcon项目中承担的角色就是连接数据库,作为数据库缓存,缓存配置 ...

  6. SharePoint Development - Custom Content Type using Visual Studio 2010 based SharePoint 2010

    博客地址 http://blog.csdn.net/foxdave 本文所述均来自之前实际的项目模块 首先再论述一下SharePoint ContentType内容类型 SharePoint的列表和文 ...

  7. STL标准库-hash

    技术在于交流.沟通,本文为博主原创文章转载请注明出处并保持作品的完整性 hash的结构图如下图 oject通过hashfunc转换成hashcode然后插入到相应篮子中 hash同rb_tree是一种 ...

  8. 转:Android-apt

    转自http://blog.csdn.net/zjbpku/article/details/22976291 What is this? The Android-apt plugin assists ...

  9. iOS-----使用AddressBookUI管理联系人

    使用AddressBookUI管理联系人 iOS SDK为管理地址簿提供的视图控制器位于AddressBookUI框架内.总结来说,AddressBookUI框架提供了如下特殊的视图控制器. ABPe ...

  10. Ubuntu配置SSH服务

    本文主要解决Ubuntu配置SSH服务的问题 1.1.修改可用的agt源 sudo vim /etc/apt/sources.list 1.2.更新代码包 sudo apt-get update 2. ...