framework —— 基础框架
1.结构目录:
2.urls.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>[v1|v2]+)/',include('api.urls')) ]
3.api/urls.py:
from django.conf.urls import url,include from django.contrib import admin from api import views urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^index/$',views.IndexView.as_view()), ]
4.api/views.py:
from django.shortcuts import render from rest_framework.versioning import URLPathVersioning from rest_framework import views from rest_framework.response import Response from api import models from api.serializer.index import IndexSerializer #对象方法 class BaseResponse(object): def __init__(self,code=1000,data=None,error=None): self.code = code self.data = data self.error = error class IndexView(views.APIView): def get(self, request, *args, **kwargs): ret = BaseResponse() try: user_list = models.Userinfo.objects.all() ser = IndexSerializer(instance=user_list, many=True) ret.data = ser.data except Exception as e: ret.code = 1001 ret.error= 'xxxx错误' return Response(ret.__dict__) #1.普通方法 # class IndexView(views.APIView): # def get(self,request,*args,**kwargs): # ret = {'code':1000,'data':None} # try: # user_list = models.Userinfo.objects.all() # ser = IndexSerializer(instance=user_list,many=True) # ret['data'] = ser.data # except Exception as e: # ret['code'] = 1001 # ret['error'] = 'xxxx错误' # return Response(ret)
5.settings.py:
6.models.py:
from django.db import models # Create your models here. class Userinfo(models.Model): name = models.CharField(max_length=32) pwd = models.CharField(max_length=32)
验证: