一、请求对象
REST 框架引入Request来扩展常规的HttpRequest,并提供了更灵活的请求解析。Request对象的核心功能是request.data属性。
导入方式: from rest_framework.response import Response
request.POST # Only handles form data. Only works for ‘POST‘ method. request.data # Handles arbitrary data. Works for ‘POST‘, ‘PUT‘ and ‘PATCH‘ methods.
二、响应对象
三、状态码
在Response返回中使用数字HTTP状态码并不总是有助于明显的阅读,REST框架为每一个状态码更明确的标识符,如 HTTP_404_NOT_FOUND 。
导入方式: from rest_framework import status
四、视图装饰器
REST框架提供了两个可用于编写API视图的装饰器
- @api_view # 函数装饰器
- APIView # 类装饰器
These wrappers provide a few bits of functionality such as making sure you receive Request
instances in your view, and adding context to Response
objects so that content negotiation can be performed.
The wrappers also provide behaviour such as returning 405 Method Not Allowed
responses when appropriate, and handling any ParseError
exception that occurs when accessing request.data
with malformed input.
五、Pulling it all together
这里不在需要使用JSONResponse来格式化返回数据
from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from test_app import serializer from test_app import models @api_view([‘GET‘, ‘POST‘]) def game_list(request): if request.method == ‘GET‘: games = models.Game.objects.all() games_serializer = serializer.Test_app_model_serializer(instance=games, many=True) return Response(games_serializer.data) elif request.method == ‘POST‘: game_serializer = serializer.Test_app_model_serializer(data=request.data) if game_serializer.is_valid(): game_serializer.save() return Response(game_serializer.data, status=status.HTTP_201_CREATED) return Response(game_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
想相对于之前写的视图函数,这样更加简明扼要,这里是@api_view装饰器的功劳。
这是views.py模块中里一个视图代码
@api_view([‘GET‘, ‘PUT‘, ‘DELETE‘]) def game_info(request, game_id): try: game_obj = models.Game.objects.get(id=game_id) except models.Game.DoesNotExist as e: return Response(status=status.HTTP_404_NOT_FOUND) # return HttpResponse(e,status=status.HTTP_404_NOT_FOUND) if request.method == ‘GET‘: game_serializer = serializer.Test_app_model_serializer(instance=game_obj) return Response(game_serializer.data) elif request.method == ‘PUT‘: game_serializer = serializer.Test_app_model_serializer(instance=game_obj,data=request.data) if game_serializer.is_valid(): game_serializer.save() return Response(game_serializer.data) return Response(game_serializer.errors) elif request.method == ‘DELETE‘: game_obj.delete() return Response(status=status.HTTP_204_NO_CONTENT)
离开家按理说发动机