penitent_tangent
penitent_tangent

Reputation: 772

POSTing a file to PHP from Python

I have a GAE PHP script that accepts a POSTed message consisting of $_POST['version_name'], $_POST['version_comments'] and $_FILES['userfile']['tmp_name'][0].

It runs a file_get_contents against $_FILES['userfile']['tmp_name'][0] and stores the binary away in a CloudSQL DB.

This is the end point for a PHP-driven form, so users can upload new versions (with names / comments) through a friendly GUI from their browser. It works fine.

Now I want to be able to use the same handler as the end point for a Python script. I've written this:

r = requests.post('http://handler_url_here/', 
data={'version_name': "foo", 'version_comments': "bar"}, 
files={'userfile': open('version_archive.tar.gz', 'rb')})

version_archive.tar.gz is a non-empty file, but file_get_contents($_FILES['userfile']['tmp_name'][0]) is returning null. Uploading files is a bit tricky with GAE, so I'd prefer to not change the listener - is there some way I can make Python send its payload in the same format the listener is expecting?

$_POST['version_name'] and $_POST['version_comments'] are working as expected.

Upvotes: 0

Views: 125

Answers (1)

Topher Hunt
Topher Hunt

Reputation: 4803

I'd start by looking at the middle-man, which in this case is the HTTP request. Keep in mind, your Python script isn't posting directly to PHP; it's making an HTTP POST request, which is then getting interpreted by PHP into the $_POST variables and whatnot.

Figure out a way to "capture" or "dump" the HTTP request that Python is sending so you can inspect its contents. (You can find a number of free tools that help you do this in various ways. Reading the HTTP request should be pretty self-explanatory if you're familiar with working with $_GET and $_POST variables in PHP.) Then send a supposedly identical request from PHP, capture the HTTP request, and determine how and why they're different.

Good luck!

Upvotes: 1

Related Questions