使用Djang在不使用表单(restapi)的情况下访问POST字段数据

2024-06-16 10:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

django documentation中,它说:

HttpRequest.POST

A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.

但是,服务器不响应浏览器(例如使用JS框架或表单),而是响应Anroid/iOS应用程序发送的restapi。在

如果客户机直接在POST请求中发送字段,我如何读取数据?例如,这个(Java+Unirest):

Unirest.post("/path/to/server")
       .field("field1", "value2")
       .field("field2", "value2");

编辑:我可以简单地使用response.POST["field1"]读取数据,还是必须使用request.body进行操作?在

编辑2:这样我就可以简单地使用request.body作为类似于request.POST的类似字典的对象?在


Tags: thetoformfielddataaccessrequestdocumentation
3条回答

据我所知,Unirest的field方法只使用普通的application/x-www-form-urlencoded数据,就像HTML表单一样。所以您应该能够像您建议的那样使用response.POST["field1"]。在

docs

request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:

  • It includes all parsed content, including file and non-file inputs.
  • It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH
    requests.
  • It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.

Can I simply read the data using response.POST["field1"], or will I have to do something with request.body?

So I can simply use request.body as a dictionary-like object similar to request.POST?

示例-来自create方法(viewsets):

user = dict(
                full_name=request.DATA['full_name'],
                password=request.DATA['password'],
                email=request.DATA['email'],
                personal_number=request.DATA['personal_number'],
                user_type=request.DATA['user_type'],
                profile_id=request.DATA['profile_id'],
                account_id=request.DATA['account_id']
            )

编辑1:在版本3(最新)中,request.DATA已替换为request.data

^{pr2}$

如果与之交互的api是基于sipmle Django类的视图,则可以通过request.body访问数据,如下所示:

class MyView(View):
    def post(self, request):
        field1 = request.body.get('field1')
        field2 = request.body.get('field2')
        ... # processing here

如果您使用的是Django rest framework api,则可以通过request.data访问数据:

^{pr2}$

NB:如果您发现request.DATA在互联网上的某个地方使用也是正确的,但它只对旧版本的DRF有效,并且它被弃用,取而代之的是新版本中的request.data。在

相关问题 更多 >