一、
安装方式:
pip install django
pip install djangorestframework
其他细节就不多说了
在setting中加入配置
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', # 加入api 'rest_framework' # 加入rest_framework ]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'api.cors.CORSMiddleware' # 可以跨域请求
]
# 开restful接口
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': ['rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer',],
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
'ALLOWED_VERSIONS': ['v1', 'v2'], # 允许的版本
'VERSION_PARAM': 'version', # 参数
'DEFAULT_VERSION': 'v1', # 默认版本
}
url.py
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/(?P<version>w+)/', include('api.urls')) ]
apiurls.py url路径
from django.conf.urls import url, include from api.views import course urlpatterns = [ # 方式一 # url(r'^course/', course.CourseView.as_view()), # url(r'^course/(?P<pk>d+)/', course.CourseView.as_view()) # 方式二 url(r'^course/$', course.CourseView.as_view({'get': 'list'})), url(r'^course/(?P<pk>d+)/$', course.CourseView.as_view({'get': 'retreice'})), ]
apiviewscourse.py 视图函数
from rest_framework.views import APIView from rest_framework.response import Response from api import models from rest_framework import serializers class CourseSerializer(serializers.ModelSerializer): level = serializers.CharField(source="get_level_display") # 得到level数字对应的文字 class Meta: model = models.Course fields = ['id', 'title', 'course_img', 'level'] # '__all__' 全部数据 # class CourseDetailSerializer(serializers.ModelSerializer): # class Meta: # model = models.CourseDetail # fields = '__all__' # depth = 2 # 根据关联字段找到表序列化2层(0-10) class CourseDetailSerializer(serializers.ModelSerializer): # 以下这3种方法只适合one2one/foreignkey/choice title = serializers.CharField(source='course.title') img = serializers.CharField(source='course.course_img') level = serializers.CharField(source='course.get_level_display') # many2many recommends = serializers.SerializerMethodField() chapter = serializers.SerializerMethodField() def get_recommends(self, obj): # 获取推荐的所有课程 queryset = obj.recommend_courses.all() return [{'id': row.id, 'title': row.title} for row in queryset] def get_chapter(self, obj): # 获取推荐的所有章节 queryset = obj.course.chapter_set.all() return [{'id': row.id, 'num': row.num, 'name': row.name} for row in queryset] class Meta: model = models.CourseDetail fields = ['why', 'title', 'img', 'level', 'course', 'slogon', 'recommends', 'chapter'] # 指定数据 depth = 2 # 方法一 # class CourseView(APIView): # def get(self, request, *args, **kwargs): # ret = { # 'code': 1000, # 'data': [ # {"id": 1, "title": 'python全栈'}, # {"id": 2, 'title': 'Linux运维'}, # {"id": 3, 'title': '金融分析'} # ] # } # return Response(ret) # 方法一 # ret = {'code': 1000, 'data': None} # try: # pk = kwargs.get('pk') # if pk: # obj = models.Course.objects.filter(id=pk).first() # # 序列化 # ser = CourseSerializer(instance=obj, many=False) # else: # queryset = models.Course.objects.all() # # 序列化 # ser = CourseSerializer(instance=queryset, many=True) # ret['data'] = ser.data # except Exception as e: # ret['code'] = 1001 # ret['data'] = '获取失败' # return Response(ret) # 方法二 # views # APIView # GenericAPIView from rest_framework.viewsets import GenericViewSet, ViewSetMixin class CourseView(ViewSetMixin, APIView): def list(self, request, *args, **kwargs): """ 课程列表接口 :param request: :param args: :param kwargs: :return: """ ret = {'code': 1000, 'data': None} try: queryset = models.Course.objects.all() ser = CourseSerializer(instance=queryset, many=True) ret['data'] = ser.data except Exception as e: ret['code'] = 1001 ret['error'] = '获取失败' return Response(ret) def retreice(self, request, *args, **kwargs): """ 个人信息接口 :param request: :param args: :param kwargs: :return: """ ret = {'code': 1000, 'data': None} try: # 课程ID pk = kwargs.get('pk') # obj = models.Course.objects.filter(id=pk).first() # 通过Course查询ID为pk的信息 # ser = CourseSerializer(instance=obj, many=False) # 序列化obj信息 obj = models.CourseDetail.objects.filter(course_id=pk).first() ser = CourseDetailSerializer(instance=obj, many=False) ret['data'] = ser.data except Exception as e: ret['code'] = 1001 ret['error'] = '获取失败' return Response(ret)
api/serializers/course.py 归类要查找的数据
from api import models from rest_framework import serializers class CourseSerializer(serializers.ModelSerializer): """ 课程信息的类 """ level = serializers.CharField(source="get_level_display") # 得到level数字对应的文字 class Meta: model = models.Course fields = ['id', 'title', 'course_img', 'level'] # '__all__' 全部数据 # class CourseDetailSerializer(serializers.ModelSerializer): # class Meta: # model = models.CourseDetail # fields = '__all__' # depth = 2 # 根据关联字段找到表序列化2层(0-10) class CourseDetailSerializer(serializers.ModelSerializer): """ 课程详情的类 """ # 以下这3种方法只适合one2one/foreignkey/choice title = serializers.CharField(source='course.title') img = serializers.CharField(source='course.course_img') level = serializers.CharField(source='course.get_level_display') # many2many recommends = serializers.SerializerMethodField() chapter = serializers.SerializerMethodField() def get_recommends(self, obj): # 获取推荐的所有课程 queryset = obj.recommend_courses.all() return [{'id': row.id, 'title': row.title} for row in queryset] def get_chapter(self, obj): # 获取推荐的所有章节 queryset = obj.course.chapter_set.all() return [{'id': row.id, 'num': row.num, 'name': row.name} for row in queryset] class Meta: model = models.CourseDetail fields = ['why', 'title', 'img', 'level', 'course', 'slogon', 'recommends', 'chapter'] # 指定数据 depth = 2
api/cors.py 设置跨域请求
from django.utils.deprecation import MiddlewareMixin class CORSMiddleware(MiddlewareMixin): def process_response(self,request,response): # 允许你的域名来访问 response['Access-Control-Allow-Origin'] = "*" # 允许你携带 Content-Type 请求头 不能写* response['Access-Control-Allow-Headers'] = 'Content-Type' # 允许你发送 DELETE PUT请求 response['Access-Control-Allow-Methods'] = 'DELETE,PUT' return response
API接口
课程接口: 127.0.0.1:8000/api/v1/course/ 127.0.0.1:8000/api/v2/course/ 单个课程接口: 127.0.0.1:8000/api/v1/course/1 127.0.0.1:8000/api/v2/course/1 - 路由 as_view 是否添加参数,取决于视图继承的类 - 序列化 - depth - source - 自定义method