Python Swift Examples

Create a Connection

This creates a connection so that you can interact with the server:

  1. import swiftclient
  2. user = 'account_name:username'
  3. key = 'your_api_key'
  4. conn = swiftclient.Connection(
  5. user=user,
  6. key=key,
  7. authurl='https://objects.dreamhost.com/auth',
  8. )

Create a Container

This creates a new container called my-new-container:

  1. container_name = 'my-new-container'
  2. conn.put_container(container_name)

Create an Object

This creates a file hello.txt from the file named my_hello.txt:

  1. with open('hello.txt', 'r') as hello_file:
  2. conn.put_object(container_name, 'hello.txt',
  3. contents= hello_file.read(),
  4. content_type='text/plain')

List Owned Containers

This gets a list of containers that you own, and prints out the container name:

  1. for container in conn.get_account()[1]:
  2. print container['name']

The output will look something like this:

  1. mahbuckat1
  2. mahbuckat2
  3. mahbuckat3

List a Container’s Content

This gets a list of objects in the container, and prints out each object’s name, the file size, and last modified date:

  1. for data in conn.get_container(container_name)[1]:
  2. print '{0}\t{1}\t{2}'.format(data['name'], data['bytes'], data['last_modified'])

The output will look something like this:

  1. myphoto1.jpg 251262 2011-08-08T21:35:48.000Z
  2. myphoto2.jpg 262518 2011-08-08T21:38:01.000Z

Retrieve an Object

This downloads the object hello.txt and saves it in ./my_hello.txt:

  1. obj_tuple = conn.get_object(container_name, 'hello.txt')
  2. with open('my_hello.txt', 'w') as my_hello:
  3. my_hello.write(obj_tuple[1])

Delete an Object

This deletes the object hello.txt:

  1. conn.delete_object(container_name, 'hello.txt')

Delete a Container

Note

The container must be empty! Otherwise the request won’t work!

  1. conn.delete_container(container_name)