Reputation: 51
Why does the following print None?
import requests
r = requests.request('http://cnn.com', data={"foo":"bar"})
print r.request.body
# None
If you change cnn.com to www.cnn.com, it prints the proper body. I noticed a redirect (there is a 301 in r.history). What's going on?
Upvotes: 3
Views: 5029
Reputation: 366073
Your code as it stands doesn't actually work—it'll raise a TypeError
right off the bat. But I think I can guess at what you're trying to do.
If you change that request
to a post
, it will indeed successfully return None
.
Why? Because you're asking for the body of the redirect, not the body of the original request. For that, you want r.history[0].request.body
.
Read Redirection and History for more info. Note that auto-redirecting isn't actually documented to work for POST requests, even though it often does anyway. Also note that in earlier versions of requests
, history
entries didn't have complete Request
objects. (You'll have to look at the version history if you need to know when that changed. But it seems to be there in 1.2.0, and not in 0.14.2—and a lot of things that were added or changes in 1.0.0 aren't really documented, because it was a major rewrite.)
As a side note… why do you need this? If you really need to know what body you sent, why not do the two-step process of creating a request and sending it, so you can see the body beforehand? (Or, for that matter, just encode the data explicitly?)
Upvotes: 2