目錄
1.drf 響應(yīng)格式和請求格式配置(了解)
2.封裝自己的Response對象
3.drf自動生成路由
4.action裝飾器
5 認(rèn)證介紹和源碼分析
1.drf 響應(yīng)格式和請求格式配置(了解)
1.1 配置響應(yīng)格式
1 在配置文件中配置
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': ( # 默認(rèn)響應(yīng)渲染類
'rest_framework.renderers.JSONRenderer', # json渲染器
'rest_framework.renderers.BrowsableAPIRenderer', # 瀏覽API渲染器
)
}
2 在瀏覽器訪問就是瀏覽器方式伴澄,用postman訪問就是json格式,ajax請求就是json格式
3 原來沒有配置羔挡,為什么顯示瀏覽器方式和json的樣子
4 drf也有一套默認(rèn)配置文件来庭,默認(rèn)就配了兩個響應(yīng)類
5 局部配置某個視圖類的響應(yīng)格式愕秫,在視圖類中配置
from rest_framework.renderers import renderer
renderer_classes = [JSONRenderer]
1.2 配置能夠解析的格式(urlencoded,formdata燃箭,json)
1 在setting中配置
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
]
}
2 它就只能解析三種請求編碼格式(urlencoded,formdata舍败,json)
3 局部使用招狸,在視圖類中配置
from rest_framework.parsers import FormParser
parser_classes = [FormParser,JSONParser]
2.封裝自己的Response對象
class APIResponse(Response):
def __init__(self, code=200, msg=None, data=None, status=None,
template_name=None, headers=None,
exception=False, content_type=None, **kwargs):
dic = {'status': code, 'msg': msg}
if data:
dic['data'] = data
if kwargs:
dic.update(kwargs)
super().__init__(data=dic, status=status,
template_name=template_name, headers=headers,
exception=exception, content_type=content_type)
### 使用邻薯,在視圖類中
return APIResponse(msg='成功了',data=ser.data)
3.drf自動生成路由
1 三種路由寫法
- path('test/', views.Test.as_view()),
- path('test/', views.Test.as_view({'get':'send_email'})),
- 自動生成路由
# 1 導(dǎo)入路由類
from rest_framework.routers import SimpleRouter, DefaultRouter
# DefaultRouter生成的路由更多一點(diǎn)裙戏,多了一個根的路由(沒有用)
# 2 實(shí)例化得到對象
router = SimpleRouter()
# 3 注冊路由
router.register('books', views.BookView)
router.register('publish', views.PublishView)
# print(router.urls) # 自動生成的路由
urlpatterns = [
# 把自動生成的路徑加入到urlpatterns
path('api/v1/', include(router.urls)),
]
# 4 把自動生成的路徑加入到urlpatterns
urlpatterns+=router.urls
總結(jié):ViewSetMixin+9個視圖子類才能用自動生成路由
4.action裝飾器
1 作用:給自動生成路由的視圖類再定制一些路由
2 用法一:
# api/v1/publish/sen_email/
@action(methods=['GET'], detail=False)
def sen_email(self, request, *args, **kwargs):
print(args)
print(kwargs)
return APIResponse(msg='發(fā)送成功')
3 方法二:
# api/v1/publish/10/sen_email/
@action(methods=['GET'], detail=True)
def sen_email(self, request, *args, **kwargs):
# pk=10
print(args)
print(kwargs)
return APIResponse(msg='發(fā)送成功')
5 認(rèn)證介紹和源碼分析
1 只有認(rèn)證通過的用戶才能訪問指定的url地址,比如:查詢課程信息厕诡,需要登錄之后才能查看累榜,沒有登錄,就不能查看灵嫌,這時候需要用到認(rèn)證組件
2 APIVIew--->dispatche--->self.initial--->寫的
self.perform_authentication(request)# 認(rèn)證
self.check_permissions(request) # 權(quán)限
self.check_throttles(request) # 頻率
3 APIView的perform_authentication
-request.user # 新的request對象壹罚,drf的Request類
4 Request類的user
-被包裝成了數(shù)據(jù)屬性,內(nèi)部有 self._authenticate()
-Request類的_authenticate()方法
5 Request類的_authenticate()方法
def _authenticate(self):
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()
6 drf的Request對象實(shí)例化是再什么時候寿羞?
-再APIVIew的dispatch最上面完成的
- return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(), # 看它
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
7 APIView的get_authenticators
def get_authenticators(self):
return [auth() for auth in self.authentication_classes]
-如果我再視圖類中寫:authentication_classes=[類名猖凛,類名1]
-返回[對象,對象1]