当内容类型为application / x-www-form-urlencoded时,请求正文为何为空白?

时间:2018-08-16 21:38:40

标签: cherrypy

我收到内容类型为application/x-www-form-urlencoded的请求。当我尝试使用cherrypy.request.body.read()读取请求的正文时,结果为b''

我似乎可以使用以下任意一种来访问请求表单参数:

cherrypy.request.params

cherrypy.request.body.params

cherrypy.request.body.request_params

但是这对于我的用例来说很不方便,我希望无论内容类型如何都能够获取原始请求正文。另外,上面的3给我提供了一个字典,它不是请求在其主体中的确切格式。有办法做到这一点吗?还是隐藏了此功能?

1 个答案:

答案 0 :(得分:1)

不确定是否要通过不使用与定义的Content-Type对应的已解析主体来完成什么工作,但是您可以自己配置cherrypy.request.process_request_body = False来处理请求的主体并读取像这样的身体:

cherrypy.request.rfile.read(cherrypy.request.headers['Content-Length'])

有关更多信息,请参见:https://github.com/cherrypy/cherrypy/blob/master/cherrypy/_cprequest.py#L292-L315

该网址相关部分的片段:

rfile = None
"""
If the request included an entity (body), it will be available
as a stream in this attribute. However, the rfile will normally
be read for you between the 'before_request_body' hook and the
'before_handler' hook, and the resulting string is placed into
either request.params or the request.body attribute.
You may disable the automatic consumption of the rfile by setting
request.process_request_body to False, either in config for the desired
path, or in an 'on_start_resource' or 'before_request_body' hook.
WARNING: In almost every case, you should not attempt to read from the
rfile stream after CherryPy's automatic mechanism has read it. If you
turn off the automatic parsing of rfile, you should read exactly the
number of bytes specified in request.headers['Content-Length'].
Ignoring either of these warnings may result in a hung request thread
or in corruption of the next (pipelined) request.
"""

process_request_body = True
"""
If True, the rfile (if any) is automatically read and parsed,
and the result placed into request.params or request.body.
"""

body = None
"""
If the request Content-Type is 'application/x-www-form-urlencoded'
or multipart, this will be None. Otherwise, this will be an instance
of :class:`RequestBody<cherrypy._cpreqbody.RequestBody>` (which you
can .read()); this value is set between the 'before_request_body' and
'before_handler' hooks (assuming that process_request_body is True."""