Learning Python Network Programming

(Sean Pound) #1

APIs in Action


Now run the client, and if everything works as expected, then we will get a
confirmation message. Make sure that you have picked a bucket that hasn't
already been created:


$ python3.4 s3_client.py create_bucket mybucket.example.com


Created bucket mybucket.example.com OK


When we refresh the S3 Console in our browser, we will see that our bucket has
been created.


Uploading a file


Now that we've created a bucket, we can upload some files. Writing a function for
uploading a file is similar to creating a bucket. We check the documentation to see
how to construct our HTTP request, figure out what information should be collected
at the command line, and then write the function.


We need to use an HTTP PUT again. We need the name of the bucket that we want to
store the file in and the name that we want the file to be stored under in S3. The body
of the request will contain the file data. At the command line, we'll collect the bucket
name, the name we want the file to have in the S3 service and the name of the local
file to upload.


Add the following function to your s3_client.py file after the create_bucket()
function:


def upload_file(bucket, s3_name, local_path):
data = open(local_path, 'rb').read()
url = 'http://{}.{}/{}'.format(bucket, endpoint, s3_name)
r = requests.put(url, data=data, auth=auth)
if r.ok:
print('Uploaded {} OK'.format(local_path))
else:
xml_pprint(r.text)

In creating this function, we follow a pattern similar to that for creating a bucket:



  1. Prepare the data that will go in the request body.

  2. Construct our URL.

  3. Make the request.

  4. Check the outcome.

Free download pdf