Learning Python Network Programming

(Sean Pound) #1
Chapter 3
r = requests.put(url, data=data, headers=headers, auth=auth)
if r.ok:
print('Uploaded {} OK'.format(local_path))
else:
xml_pprint(r.text)

Here, we have used the mimetypes module to guess a suitable Content-Type
by looking at the file extension of local_path. If mimetypes can't determine a
Content-Type from local_path, then we don't include the Content-Type
header, and let S3 apply the default binary/octet-stream type.


Unfortunately, in S3 we won't be able to overwrite the metadata for an existing object
by using a simple PUT request. It's possible to do it by using a PUT copy request, but
that's beyond the scope of this chapter. For now, it's better to just delete the file from
S3 by using the AWS Console before uploading it again. We only need to do this
once. Now, our code will automatically add the Content-Type for any new file that
we upload.


Once you've deleted the file, re-run the client just as shown in the last section, that is,
upload the file with the new Content-Type and try to download the file in a browser
again. If all goes well, then the image will be displayed.


Downloading a file with the API


Downloading a file through the S3 API is similar to uploading it. We simply take the
bucket name, the S3 object name and the local filename again but issue a GET request
instead of a PUT request, and then write the data received to disk.


Add the following function to your program, underneath the upload_file() function:


def download_file(bucket, s3_name, local_path):
url = 'http://{}.{}/{}'.format(bucket, endpoint, s3_name)
r = requests.get(url, auth=auth)
if r.ok:
open(local_path, 'wb').write(r.content)
print('Downloaded {} OK'.format(s3_name))
else:
xml_pprint(r.text)

Now, run the client and download a file, which you have uploaded previously,
by using the following command:


$ python3.4 s3_client.py download_file mybucket.example.com test.jpg
~/test_downloaded.jpg


Downloaded test.jpg OK

Free download pdf