一、安装django和djangorestframework
一般将需要的包以及版本写入文本批量安装,方便环境迁移
eg:
django==1.11.15
djangorestframework==3.5.4
命令
pip install -r requirement.txt
二、创建项目
1. 创建项目fault
django-admin startproject fault
2. 创建子应用core
python manage.py startapp core
3. settings注册应用以及配置rest_framework
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
'rest_framework'
]
REST_FRAMEWORK = {
# 异常请求处理
'EXCEPTION_HANDLER': 'backend.core.apis.views.custom_exception_handler',
# 分页格式
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 分页大小
'PAGE_SIZE': 15,
# 接口默认权限
'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
'rest_framework.permissions.IsAuthenticated',
],
# 用户验证
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'backend.performance.apis.permissions.CsrfExemptSessionAuthentication',
),
# 默认渲染
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
}
4. 第一次同步数据库
python manage.py migrate
5. 创建一个管理员
python manage.py createsuperuser
三、直接用Django自带的User,Group模块
1. Serializers(fault/core/serializers.py下)
定义一些序列化User,Group数据表Serializers
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'email')
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name')
2. Views(fault/core/views.py下)
可以写视图代码了
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from core.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
允许用户查看或编辑的API路径。
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
允许组查看或编辑的API路径。
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
def custom_exception_handler(exc, context):
"""
自定义的异常处理
:param exc: 本次请求发送的异常信息
:param context: 本次请求发送异常的执行上下文【本次请求的request对象,异常发送的时间,行号等....】
:return:
"""
response = exception_handler(exc, context)
# 在此处补充自定义的异常处理
if response is not None:
response.data['status_code'] = response.status_code
return response
if response is None:
"""来到这只有2中情况,要么程序没出错,要么就是出错了而Django或者restframework不识别"""
view = context['view']
if isinstance(exc, DatabaseError):
# 数据库异常
"""有5个方法发debug info error critical warning"""
logger.error('[%s] %s' % (view, exc))
response = Response({'message': '服务器内部错误,请联系客服工作人员!'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
3. urls
from django.contrib import admin
from django.conf.urls import include, url
from rest_framework import routers
from core import views
router = routers.DefaultRouter()
router.register(r'users',views.UserViewSet)
router.register(r'groups',views.GroupViewSet)
# 使用自动URL路由链接我们的API
# 支持浏览器浏览API
urlpatterns = [
url('admin/', admin.site.urls),
url('^api/',include(router.urls)),
url(r'^api/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
4. 启动服务器
python3 manage.py runserver 0.0.0.0:8080
5. 请求接口测试
http://127.0.0.1:8080/api/users/