1 drf之请求
1.1 drf 之请求Request类
- request. method 的时候- - - 》实际上 request. _request. 'method' - - - 》反射出来的- 这个类from rest_framework. request import Request没有method,他会触发这个类的__getattr__- - - 》request. _request视图类的方法中: self 是咱们写的视图类的对象,self. request 是新的request
1.2 控制前端请求的编码格式
前端传入的编码: urlencoded, josn, form- data
class BookView ( APIView) : parser_classes = [ JSONParser] REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES' : [ 'rest_framework.parsers.JSONParser' , 'rest_framework.parsers.FormParser' , ]
}
REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES' : [ 'rest_framework.parsers.JSONParser' , 'rest_framework.parsers.FormParser' , 'rest_framework.parsers.MultiPartParser' ] , 'DEFAULT_RENDERER_CLASSES' : [ 'rest_framework.renderers.JSONRenderer' , 'rest_framework.renderers.BrowsableAPIRenderer' , ] ,
}
class BookView ( APIView) : parser_classes = [ MultiPartParser] - drf自己有默认配置- - - 》默认配置就是支持三种
代码解读
from rest_framework. views import APIView
from rest_framework. response import Response
from rest_framework. parsers import JSONParser, FormParser, MultiPartParser
from rest_framework. renderers import JSONRenderer, BrowsableAPIRenderer
class BookView ( APIView) : '''# 方式二:编码格式全局使用,以及浏览器和postman的响应编码格式REST_FRAMEWORK = {# 全局配置编码格式'DEFAULT_PARSER_CLASSES': ['rest_framework.parsers.JSONParser','rest_framework.parsers.FormParser','rest_framework.parsers.MultiPartParser'],# 全局配置响应编码格式'DEFAULT_RENDERER_CLASSES': ['rest_framework.renderers.JSONRenderer','rest_framework.renderers.BrowsableAPIRenderer',],}''' parser_classes = [ JSONParser, FormParser, MultiPartParser] renderer_classes = [ JSONRenderer, BrowsableAPIRenderer] def get ( self, request) : print ( self. request is request) print ( self. headers) '''def __init__(self, data=None, status=None, template_name=None, headers=None,exception=False, content_type=None):data=None # 字符串,列表,字典------> 放在了响应体中------>它是__init__()的第一个参数status=None # 这是http响应状态码,默认是200,不能使用status=100,这表示请求正在处理template_name=None # 模板名字默认是:rest_framework/api.html 可以定制自己返回的页面headers=None # http响应头,后期我们往响应头中放数据exception=False content_type=None # 响应编码格式 ''' res = Response( data= { } , status= 200 , headers= { 'xxx' : 'yyyy' } ) print ( res. data) print ( res. has_header( 'xxx' ) ) return resdef post ( self, request) : print ( request. data) return Response( '新增' )
2 drf之响应
2.1 drf之Response对象源码
data= None
status= None ,
headers= None , content_type= None
template_name= None
res= Response( data= { } , status= 500 , headers= { 'xxx' : 'yyy' } )
print ( res. data)
return res
res. headers 拿不到数据,可以通过下面的方式或得到
print ( res[ 'xxx' ] )
print ( res. has_header( 'zzz' ) )
2.2 drf之响应格式
class BookView ( APIView) : renderer_classes = [ BrowsableAPIRenderer]
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES' : [ 'rest_framework.renderers.JSONRenderer' , 'rest_framework.renderers.BrowsableAPIRenderer' , ] ,
}
class BookView ( APIView) : renderer_classes = [ BrowsableAPIRenderer] - 解析:三种编码都能解析- 响应:浏览器访问看到浏览器的样子,postman访问,看到json格式
3 两个视图基类
3.1 基于 APIView写接口
class BookView ( APIView) : def get ( self, request) : book_list = Book. objects. all ( ) ser = BookSerializer( instance= book_list, many= True ) return Response( ser. data) def post ( self, request) : ser = BookSerializer( data= request. data) if ser. is_valid( ) : ser. save( ) return Response( ser. data) else : return Response( ser. errors) class BookDetailView ( APIView) : def get ( self, request, pk) : book = Book. objects. filter ( pk= pk) . first( ) ser = BookSerializer( instance= book) return Response( ser. data) def put ( self, request, pk) : book = Book. objects. filter ( pk= pk) . first( ) ser = BookSerializer( instance= book, data= request. data) if ser. is_valid( ) : ser. save( ) return Response( ser. data) else : return Response( ser. errors) def delete ( self, request, pk) : Book. objects. filter ( pk= pk) . delete( ) return Response( '' )
3.2 基于GenericAPIView(只要跟数据库打交道)
自己写GenericAPIView
class GenericAPIView ( APIView) : queryset = None serializer_class = None def get_queryset ( self) : return self. queryset. all ( ) def get_serializer ( self, * args, ** kwargs) : return self. serializer_class( * args, ** kwargs) def get_object ( self, pk) : res = self. get_queryset( ) return res. filter ( pk= pk) . first( )
GenericAPIView 有类属性和方法
- queryset:以后放所有某个表查询出的数据- serializer_class:要序列化的类- get_queryset : 要序列化的所有数据,qs对象- get_serializer :序列化类- get_object :修改,查询的单条- lookup_field = 'pk' 路由使用转换器,转换出来的参数,查询单条要用到,如果改了,路由对应也要修改,一般不改- filter_backends:后面详细讲 过滤 功能- pagination_class :后面详细讲 分页- get_serializer_class 后期咱们可能会重写它,指定某些方法使用不同的序列化类- filter_queryset 后面跟过滤功能一起讲class PublishView ( GenericAPIView) : queryset = Publish. objects. all ( ) serializer_class = PublishSerializerdef get ( self, request) : obj_list = self. get_queryset( ) ser = self. get_serializer( instance= obj_list, many= True ) return Response( ser. data) def post ( self, request) : ser = self. get_serializer( data= request. data) if ser. is_valid( ) : ser. save( ) return Response( ser. data) else : return Response( ser. errors) class PublishDetailView ( GenericAPIView) : serializer_class = PublishSerializerqueryset = Publish. objects. all ( ) def get ( self, request, pk) : obj = self. get_object( ) ser = self. get_serializer( instance= obj) return Response( ser. data) def put ( self, request, pk) : obj = self. get_object( ) ser = self. get_serializer( instance= obj, data= request. data) if ser. is_valid( ) : ser. save( ) return Response( ser. data) else : return Response( ser. errors) def delete ( self, request, pk) : self. get_object( ) . delete( ) return Response( '' )
3.3 总结
def get_queryset ( self) : return self. queryset. all ( )
4 5个视图扩展类(不是视图类–》先继承GenericAPIView)
class PublishView ( GenericAPIView, ListModelMixin, CreateModelMixin) : queryset = Publish. objects. all ( ) serializer_class = PublishSerializerdef get ( self, request) : return self. list ( request) def post ( self, request) : return super ( ) . create( request) class PublishDetailView ( GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin) : serializer_class = PublishSerializerqueryset = Publish. objects. all ( ) def get ( self, request, pk) : return self. retrieve( request, pk) def put ( self, request, pk) : return self. update( request, pk) def delete ( self, request, pk) : return self. destroy( request, pk)
5 原生django,怎么写向响应头写入数据?
from django. http import HttpResponsedef custom_header_view ( request) : response = HttpResponse( "This is a custom header example" ) response[ 'X-Custom-Header' ] = 'Hello, World!' return response总结:首先创建了一个 HttpResponse 对象,并设置了响应的内容。然后,
通过 response[ 'Header-Name' ] 的方式向响应头添加自定义的响应头信息。
在这里,我们添加了一个名为 "X-Custom-Header" 的自定义头,其值为 "Hello, World!" 。
最后,将 HttpResponse 对象返回,以便将其发送给客户端。
这样,客户端将会接收到包含自定义响应头信息的响应。