1. 程式人生 > >python DRF獲取引數介紹

python DRF獲取引數介紹

DRF獲取引數的方式

例如url
url(r'^demo/(?P<word>.*)/$', DemoView.as_view())
在類檢視中獲取引數
url:http://127.0.0.1:8000/demo/aaa/?bbb=bbb&ccc=ccc&ccc=CCC
form:{"body":"body"}
JSON:{"body":"body"}
class DemoView(APIView):

    def post(self, request, aaa):
        aaa = aaa  # 獲取url路徑中的引數
        bbb_str = request.query_params.get('
bbb') # 獲取一個查詢字串的引數 ccc_list = request.query_params.getlist('ccc') # 獲取多個查詢字串引數 # 請求體中的引數 # 如果通過form表單傳遞,獲取出來是QueryDict,通過.dict()轉換成python的字典 form_body = request.data # 如果通過JSON傳遞,獲取出來就是字典,例如{'body':'body'} # json_body = request.data print
(aaa) print(bbb_str) print(ccc_list) print(form_body.dict()) # print(json_body) return Response({'message': 'OK'}) 結果 aaa bbb ['ccc', 'CCC'] {'body': 'body'} URL路徑引數/查詢字串不區分請求方式,GET/POST/PUT等都一樣 serializer中獲取引數 # view class DemoView(GenericAPIView): serializer_class
= DemoSerializer def post(self, request, aaa): serializer = self.get_serializer(data=request.query_params) serializer.is_valid(raise_exception=True) return Response({'message': 'OK'}) # serializer class DemoSerializer(serializers.Serializer): bbb = serializers.CharField() ccc = serializers.ListField() # List def validate(self, attrs): aaa = self.context['view'].kwargs.get('aaa') # 獲取路徑引數 bbb = attrs['bbb'] # 獲取查詢字串 ccc = attrs['ccc'] # 獲取以多個key相同的查詢字串 # 獲取當前登陸的物件,需要根據場景進行使用 # user = self.context['request'].user print(aaa) print(bbb) print(ccc) return attrs