Python 3 script to upload a file to a REST URL (multi-page request)

I am new to Python and use Python 3.2. I am trying to write a python script that will select a file from a user machine (like an image file) and send it to the server using a REST based call. The Python script must call the REST URL and send the file when the script is called.

This is similar to the multi-page POST that the browser executes when a file is downloaded; but here I want to do it through a Python script.

If possible, you do not want to add any external libraries in Python and want to keep it a fairly simple python script using a basic Python installation.

Can anyone visit me? or share some script examples that achieve what I want?

+4
source share
3 answers

A query library is what you need. You can install using pip install requests .

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

 >>> url = 'http://httpbin.org/post' >>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files) 
+6
source

A RESTful way to upload an image would be to use a PUT request if you know the image URL is:

 #!/usr/bin/env python3 import http.client h = http.client.HTTPConnection('example.com') h.request('PUT', '/file/pic.jpg', open('pic.jpg', 'rb')) print(h.getresponse().read()) 

upload_docs.py contains an example of uploading a file as multipart/form-data using basic HTTP authentication. It supports both Python 2.x and Python 3.

You can also use requests to send files as multipart/form-data :

 #!/usr/bin/env python3 import requests response = requests.post('http://httpbin.org/post', files={'file': open('filename','rb')}) print(response.content) 
+3
source

You can also use unirest. Code example

 import unirest # consume async post request def consumePOSTRequestSync(): params = {'test1':'param1','test2':'param2'} # we need to pass a dummy variable which is open method # actually unirest does not provide variable to shift between # application-x-www-form-urlencoded and # multipart/form-data params['dummy'] = open('dummy.txt', 'r') url = 'http://httpbin.org/post' headers = {"Accept": "application/json"} # call get service with headers and params response = unirest.post(url, headers = headers,params = params) print "code:"+ str(response.code) print "******************" print "headers:"+ str(response.headers) print "******************" print "body:"+ str(response.body) print "******************" print "raw_body:"+ str(response.raw_body) # post sync request multipart/form-data consumePOSTRequestSync() 

You can check this post http://stackandqueue.com/?p=57 for more details.

0
source

Source: https://habr.com/ru/post/1380349/


All Articles