Aas*_*lli 6 django request django-rest-framework axios
如何在 django rest 框架中访问 GET 请求数据。在文档中,他们提到“为了清楚起见,我们建议使用 request.query_params 而不是 Django 的标准 request.GET”
https://www.django-rest-framework.org/api-guide/requests/
但是当我使用 request.query_params.get('some_vaue') 时,即使我在请求正文中传递数据,它也不会给我任何信息。
示例代码示例:
class TestView(APIView):
def get(self, request):
test = request.query_params.get('test')
print('data',test)
...
...
...
Run Code Online (Sandbox Code Playgroud)
当我在邮递员的请求正文中传递一些值并打印该值时,它实际上打印了 None。
更新
下面是我的 axios 代码
axios.get(API_URL, {
headers: {
'Content-Type': 'application/json'
},
params: {
page_num: 1,
test: 'test data'
}
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err.response.data);
});
Run Code Online (Sandbox Code Playgroud)
重新更新:
出于测试目的,我打印了请求对象,如
print(request.__dict__)
Run Code Online (Sandbox Code Playgroud)
所以它打印出来
{'_request': <WSGIRequest: GET '/api/my api url/?page_num=1&test=test+data'>, 'parsers': [<rest_framework.parsers.JSONParser object at 0x0000016742098128>, <rest_framework.parsers.FormParser object at 0x00000167420980B8>, <rest_framework.parsers.MultiPartParser object at 0x00000167420980F0>], 'authenticators': (), 'negotiator': <rest_framework.negotiation.DefaultContentNegotiation object at 0x0000016742098080>, 'parser_context': {'view': <app_name.views.APIClassName object at 0x0000016742280400>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request object at 0x0000016742107080>, 'encoding': 'utf-8'}, '_data': {}, '_files': <MultiValueDict: {}>, '_full_data': {}, '_content_type': <class 'rest_framework.request.Empty'>, '_stream': None, 'accepted_renderer': <rest_framework.renderers.JSONRenderer object at 0x00000167421070B8>, 'accepted_media_type': 'application/json', 'version': None, 'versioning_scheme': None, '_authenticator': None, '_user': <django.contrib.auth.models.AnonymousUser object at 0x0000016741FFAC88>, '_auth': None}
Run Code Online (Sandbox Code Playgroud)
我可以看到它正在传递数据,但不确定为什么如果我执行 request.data['page_num'] 或任何其他值,它不会获取数据。
Nav*_*ain 12
如果您使用基于类的视图:
POST 在 request.data 中提供数据,在 request.query_params 中提供 GET
如果您使用基于函数的视图:
request.data 将为这两种方法完成工作。
axios 不支持使用 get 方法将参数作为正文发送,它将在 url 中附加参数。所以如果你使用 axios 你将不得不使用 query_params
axios 示例代码:
axios.get(API_URL, {
params: {
testData: 'test data',
pageNum: 1
}
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err.response.data);
});
Run Code Online (Sandbox Code Playgroud)
DRF 示例代码:
Class TestView(APIView):
def get(self, request):
test_data_var = request.query_params['testData']
page_num_var = request.query_params['pageNum']
Run Code Online (Sandbox Code Playgroud)
注意: 如果您在邮递员中测试它,则将获取请求查询参数放在参数选项卡中。
| 归档时间: |
|
| 查看次数: |
12903 次 |
| 最近记录: |