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.

Amin Guermazi
  • 1,632
  • 9
  • 19
Oliver Williams
  • 5,966
  • 7
  • 36
  • 78

1 Answers1

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

Oliver Williams
  • 5,966
  • 7
  • 36
  • 78
Jeronimo
  • 2,268
  • 2
  • 13
  • 28
  • OK I guess I could best describe my reaction to that as "bizarrely elegant" :) As a PHP dev. Thank you! – Oliver Williams Apr 06 '20 at 20:15
  • 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 ;) – Oliver Williams Apr 07 '20 at 00:10
  • In [flask](https://flask.palletsprojects.com/en/1.1.x/) for example, the object that holds the POST data of a request is `flask.request.form`, which is an [ImmutableMultiDict](https://tedboy.github.io/flask/generated/generated/werkzeug.ImmutableMultiDict.html). 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. :) – Jeronimo Apr 07 '20 at 07:31