Sample Python code using DreamObjects OpenStack Swift-compatible API

This article lists several Python code examples to interact with DreamObjects.

Creating a Connection

Create a connection so you can interact with the server.

import cloudfiles
username = 'account_name:username'
api_key = 'your_api_key'

conn = cloudfiles.get_connection(
    username=username,
    api_key=api_key,
    authurl='https://objects-us-west-1.dream.io/auth',
    )

Listing Owned Containers

Get a list of containers you own while printing out the container name.

for container in conn.get_all_containers():
    print container.name

The output will look something like this:

mahbuckat1
mahbuckat2
mahbuckat3

Creating a Container

Create a new container called my-new-container.

container = conn.create_container('my-new-container')

Listing a Container’s Content

Get a list of objects in the container while printing out each object’s name, the file size, and last modified date.

for obj in container.get_objects():
    print "{0}\t{1}\t{2}".format(
        obj.name,
        obj.size,
        obj.last_modified,
        )

The output looks something like this:

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

Deleting a Container

The Container must be empty, otherwise this will not work.

conn.delete_container(container.name)

Creating an Object

Create a file hello.txt from the file named my_hello.txt.

obj = container.create_object('hello.txt')
obj.content_type = 'text/plain'
obj.load_from_filename('./my_hello.txt')

Download an Object (to a file)

Download the object hello.txt and saves it in ./my_hello.txt.

obj = container.get_object('hello.txt')
obj.save_to_filename('./my_hello.txt')

Delete an Object

Delete the object goodbye.txt.

container.delete_object('goodbye.txt')

Did this article answer your questions?

Article last updated .