0

here is my python file

import sys
import requests

wrapper = "[Python Storage LogReader v2.b001] "
log = {}
log_lines = sys.argv
index = 0
for line in log_lines[1:]:
    error_log = wrapper + line
    log[index] = error_log
    index += 1

package = {}
package['test1'] = 'A'
package['test2'] = 'B'
package['log'] = log
success = requests.post('http://localhost:3000/post.php', package, False)

I call it like this:

python LogReader.py hello world sample

And the output received as the $_POST array is this:

Array (
    [test1] => A
    [test2] => B
    [log] => 2
)

Where "2" is the binary count of the arguments passed (I've verified by changing the argument count). What I want is this:

Array (
    [test1] => A
    [test2] => B
    [log] => Array (
        [0] => hello
        [1] => world
        [2] => sample
    )
)

I am new to Python but familiar with PHP and the way it parses a $_POST string. Essentially what I'm looking to send is this:

test1=A&test2=B&log[]=hello&log[]=world&log[]=sample

How do I do this in Python so as to get the equivalent? Obviously my goal is the simplest way possible. Thanks.

1 Answer 1

1

Two steps:

  1. Make log a list instead of a dict:
log = [wrapper + log_line for log_line in log_lines[1:]]

or to keep the loop for other purposes:

log = []
for log_line in log_lines[1:]:
    log.append(wrapper + log_line)
  1. In package, change the key for log to log[]:
package['log[]'] = log

By default, requests would serialize log (a list) to log=hello&log=world&log=sample as post data, so formatting it in the way PHP can understand it can be achieved by just adding the empty brackets to the key.

A similar Q&A: https://stackoverflow.com/a/23347265/8547331

Sign up to request clarification or add additional context in comments.

3 Comments

OK I guess I could best describe my reaction to that as "bizarrely elegant" :) As a PHP dev. Thank you!
interesting, does python send and receive log like that, i.e. log=entry1&log=entry2 etc. - that is, you could parse the raw expression so you get [entry1, entry2]. But I prefer PHP's logic ;)
In flask for example, the object that holds the POST data of a request is flask.request.form, which is an ImmutableMultiDict. Those have a method getlist, which is able to extract a list like that. Both flask.request.form.getlist("log") and flask.request.form.getlist("log[]") work, depending on which key you sent the data with, but it doesn't do it automatically like in PHP. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.