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?
            Asked
            
        
        
            Active
            
        
            Viewed 6.1k times
        
    68
            
            
         
    
    
        G S
        
- 35,511
- 22
- 84
- 118
1 Answers
119
            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)
 
    
    
        Brown Bear
        
- 19,655
- 10
- 58
- 76
 
    
    
        Roman Bodnarchuk
        
- 29,461
- 12
- 59
- 75
- 
                    any way to get them external from the do_POST() method? – KevinDTimm Jun 01 '11 at 16:10
- 
                    @KevinDTimm what is the reason to do this? – Roman Bodnarchuk Jun 01 '11 at 16:46
- 
                    8Note 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))` – Michael Osl Apr 11 '14 at 12:35
- 
                    18in python3: `self.headers.get(...)` – vlk Mar 11 '15 at 03:49
- 
                    5Any 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? – sevko Jun 19 '16 at 19:53
- 
                    3@sevko because otherwise you will start reading the next pipelined request sent by the client. – Marcus Nov 09 '17 at 21:43
- 
                    6This 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? – OLL Dec 24 '21 at 12:32