1

I am developing with apis however I faced with a problem that I have never met.

curl -F "media=@IMAGE_NAME" 'xxxx url'

How do I convert it into python code with requests?

2

4 Answers 4

2

There's a great example of a POST request in the manual. I think yours specifically would be:

r = requests.post("xxx url", data={"media": "@IMAGE_NAME"})
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I've known this usage. Actually I am not understanding what @IMAGE_NAME means. In a web app, Does it mean the file itself or the file name I got from the form?
Sorry, I have ready known that files = { 'media': open(image_name, 'rb') }
1

I solved this problem.

files = { 'media': open(image_name, 'rb') }

Then

requests.post(url, files=files)

see http://www.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file

Comments

0

If you have multiple -F parameters you can either use a tuple:

requests.post("https://www.example.com", data=[("foo", "bar"), ("baz", "off")])

or a dict:

requests.post("https://www.example.com", data={"key1": "bar", "baz": "off"})

https://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests show some examples.

Comments

-1

As per your case :

def command_string_generator(method, token, port, account,container=None, obj=None, headers_in=None, curlhead=None):
    url = 'xxxx url'
    image = "media=@IMAGE_NAME"
    command_string = 'curl -F %s %s ' % (image ,url)
    print command_string
    return command_string

you can use a function like this as per your needs with -F and change accordingly. Hope this might be helpful.Additional parameters are just for convienience.

2 Comments

Thanks for your answering but I want to use the requests :p
Hahaaaa. Sure your choice. :)

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.