0

I know the library requests, but I don't want to use it for different reasons.

So what I am trying is to make a Post request with formdata with curl from Python.

The command looks something like this:

command = "curl --insecure POST --form file1='@path_to_file' --form file2='@path_to_file2' --form config='{"key1": {"key11": "value11", "key12": "value12"}, "key2": {"key21": "value21", "key22": "value22"}' <REST API Adress>"

So if I copy this code manually into the linux terminal it works perfectly fine, but when I am trying to automate that with python subprocess there are backslashs added everywhere in the command. I think that is the reason why it always fails. The code looks like this:

p = Popen([command], cwd=<some path>, stdout=PIPE, stderr=PIPE)
process_output, process_error = p.communicate()

It just fails and prints me a command that looks like this:

command = "curl --insecure POST --form file1=\'@path_to_file\' --form file2=\'@path_to_file2\' --form config=\'{"key1": {"key11": "value11", "key12": "value12"}, "key2": {"key21": "value21", "key22": "value22"}\' <REST API Adress>"

I mean I get it. It is because of the single quotes, but how can I avoid this? Like how can I actually execute the correct command without backslashs?

2
  • You can add three quotation marks (""") before and after the string. Like this: """curl --insecure POST --form file1='@path_to_file' --form file2='@path_to_file2' --form config='{"key1": {"key11": "value11", "key12": "value12"}, "key2": {"key21": "value21", "key22": "value22"}' <REST API Adress>""" Commented Mar 22, 2022 at 19:06
  • It still does not work. Commented Mar 23, 2022 at 10:22

2 Answers 2

1

Split the command into words like the shell would.

rest_api_address = ...
commmand = ["curl",
            "--insecure", "POST",
            "--form", "file1=@path_to_file",
            "--form", "file2=@path_to_file2",
            "--form", "config={...}",
            rest_api_address]

p = Popen(command, ...)

The single quotes were for the benefit of the shell; they are not necessary when bypassing the shell as we do here.

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

1 Comment

Still doesn't work
0

I'm on windows, so i can't test, but i have better experience using the quotation marks the other way around, maybe this helps you too. So in your example:

command = 'curl --insecure POST --form file1="@path_to_file" --form file2="@path_to_file2" --form config="{"key1": {"key11": "value11", "key12": "value12"}, "key2": {"key21": "value21", "key22": "value22"}" <REST API Adress>'

Comments

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.