How to extract HTTP message body in BaseHTTPRequestHandler.do_POST()?
Asked Answered
J

1

73

In the do_POST() method of BaseHTTPRequestHandler I can access the headers of the POST request simply via the property self.headers. But I can't find a similar property for accessing the body of the message. How do I then go about doing that?

Jettiejettison answered 12/5, 2011 at 9:27 Comment(0)
L
127

You can access POST body in do_POST method like this:

for python 2

content_len = int(self.headers.getheader('content-length', 0))

for python 3

content_len = int(self.headers.get('Content-Length'))

and then read the data

post_body = self.rfile.read(content_len)
Laughable answered 12/5, 2011 at 10:52 Comment(7)
any way to get them external from the do_POST() method?Apogamy
@Apogamy what is the reason to do this?Laughable
Note that this leads to a TypeError if the content-length header is not set (e.g. by calling curl -X POST http://your-endpoint). So either make sure to catch it or set a default value for the content-length header: content_len = int(self.headers.getheader('content-length', 0))Pose
in python3: self.headers.get(...)Kaoliang
Any reason why self.rfile.read() doesn't just read the entire input on its own? Why do we need to specify the number of bytes to read?Pentapody
@Pentapody because otherwise you will start reading the next pipelined request sent by the client.Evangelize
This doesn't feel safe. What happens if a malicious client sends a very large 'Content-Length' value? Won't that cause the server to read more data than it should?Quaky

© 2022 - 2024 — McMap. All rights reserved.