Videos
I know the question may sound very basic to many of you, but to someone like me, it's not.
So basically, I started out by making a folder named 'server' in my local E: drive. I put some random files in it, and then using Command Prompt, I launched the localhost server with 'server' folder as the main directory by the following command: "python -m http.server".
Now that my localhost server is running, I created a Python file, and a PowerPoint file named 'demo.pptx'. This file 'demo.pptx' is meant to be uploaded on the localhost server when I run my program.
So, coming to the Python code, I wrote the following:
import requests
url = 'http://127.0.0.1:8000/'
files = {'file': open('demo.pptx', 'rb')}
requests.post(url, files=files)
As expected, when you run the Python program, 'demo.pptx' doesn't get uploaded on the server. Moreover, I get the following message on Command Prompt: 'code 501, message Unsupported method ('POST')'. In the very next line, cmd also says: '"POST / HTTP/1.1" 501 - '
Why is that? Could anybody help me out please?
If upload_file is meant to be the file, use:
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.
The filename will be included in the mime header for the specific field:
>>> import requests
>>> open('file.txt', 'wb') # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"
--c226ce13d09842658ffbd31e0563c6bd--
Note the filename="file.txt" parameter.
You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:
files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}
This sets an alternative filename and content type, leaving out the optional headers.
If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.
The new Python requests library has simplified this process, we can use the 'files' variable to signal that we want to upload a multipart-encoded file:
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text