Resource

NOTE: This module is being phased out in favor of openstack.resource2. Once all services have been moved over to use resource2, that module will take this `resource` name.

Resource

The Resource class is a base class that represent a remote resource. Attributes of the resource are defined by the responses from the server rather than in code so that we don’t have to try and keep up with all possible attributes and extensions. This may be changed in the future.

The prop class is a helper for definiting properties in a resource.

For update management, Resource maintains a dirty list so when updating an object only the attributes that have actually been changed are sent to the server.

There is also some support here for lazy loading that needs improvement.

There are plenty of examples of use of this class in the SDK code.

The prop class

class openstack.resource.prop(name, alias=None, type=None, default=None)

A helper for defining properties in a resource.

A prop defines some known attributes within a resource’s values. For example we know a User resource will have a name:

>>> class User(Resource):
...     name = prop('name')
...
>>> u = User()
>>> u.name = 'John Doe'
>>> print u['name']
John Doe

User objects can now be accessed via the User().name attribute. The ‘name’ value we pass as an attribute is the name of the attribute in the message. This means that you don’t need to use the same name for your attribute as will be set within the object. For example:

>>> class User(Resource):
...     name = prop('userName')
...
>>> u = User()
>>> u.name = 'John Doe'
>>> print u['userName']
John Doe

There is limited validation ability in props.

You can validate the type of values that are set:

>>> class User(Resource):
...     name = prop('userName')
...     age = prop('age', type=int)
...
>>> u = User()
>>> u.age = 'thirty'
TypeError: Invalid type for attr age

By specifying an alias attribute name, that alias will be read when the primary attribute name does not appear within the resource:

>>> class User(Resource):
...     name = prop('address', alias='location')
...
>>> u = User(location='Far Away')
>>> print u['address']
Far Away

The Resource class

class openstack.resource.Resource(attrs=None, loaded=False)

Construct a Resource to interact with a service’s REST API.

The Resource class offers two class methods to construct resource objects, which are preferrable to entering through this initializer. See Resource.new() and Resource.existing().

Parameters:
  • attrs (dict) – The attributes to set when constructing this Resource.
  • loaded (bool) – True if this Resource exists on the server, False if it does not.
resource_key = None

Singular form of key for resource.

resource_name = None

Common name for resource.

resources_key = None

Plural form of key for resource.

id_attribute = 'id'

Attribute key associated with the id for this resource.

name_attribute = 'name'

Attribute key associated with the name for this resource.

location = None

Attribute key associated with ‘location’ from response headers

base_path = ''

The base part of the url for this resource.

service = None

The service associated with this resource to find the service URL.

allow_create = False

Allow create operation for this resource.

allow_retrieve = False

Allow retrieve/get operation for this resource.

allow_update = False

Allow update operation for this resource.

allow_delete = False

Allow delete operation for this resource.

allow_list = False

Allow list operation for this resource.

allow_head = False

Allow head operation for this resource.

classmethod new(**kwargs)

Create a new instance of this resource.

Internally set flags such that it is marked as not present on the server.

Parameters:kwargs (dict) – Each of the named arguments will be set as attributes on the resulting Resource object.
classmethod existing(**kwargs)

Create an instance of an existing remote resource.

It is marked as an exact replication of a resource present on a server.

Parameters:kwargs (dict) – Each of the named arguments will be set as attributes on the resulting Resource object.
classmethod from_id(value)

Create an instance from an ID or return an existing instance.

New instances are created with new()

Parameters:value – If value is an instance of this Resource type, it is returned. If value is an ID which an instance of this Resource type can be created with, one is created and returned.
Return type:Resource or the appropriate subclass.
Raises:ValueError if value is not an instance of this Resource type or a valid id.
classmethod from_name(value)

Create an instance from a name or return an existing instance.

New instances are created with new()

Parameters:value – If value is an instance of this Resource type, it is returned. If value is a name which an instance of this Resource type can be created with, one is created and returned.
Return type:Resource or the appropriate subclass.
Raises:ValueError if value is not an instance of this Resource type or a valid name.
id

The identifier associated with this resource.

The true value of the id property comes from the attribute set as id_attribute. For example, a container’s name may be the appropirate identifier, so id_attribute = "name" would be set on the Resource, and Resource.name would be conveniently accessible through id.

name

The name associated with this resource.

The true value of the name property comes from the attribute set as name_attribute.

is_dirty

True if the resource needs to be updated to the remote.

update_attrs(*args, **kwargs)

Update the attributes on this resource

Note that this is implemented because Resource.update overrides the update method we would get from the MutableMapping base class.

Params args:A dictionary of attributes to be updated.
Params kwargs:Named arguments to be set on this instance. When a key corresponds to a resource.prop, it will be set via resource.prop.__set__.
Return type:None
static get_id(value)

If a value is a Resource, return the canonical ID.

static convert_ids(attrs)

Return an attribute dictionary suitable for create/update

As some attributes may be Resource types, their id attribute needs to be put in the Resource instance’s place in order to be properly serialized and understood by the server.

classmethod create_by_id(session, attrs, resource_id=None, path_args=None)

Create a remote resource from its attributes.

Parameters:
  • session (Session) – The session to use for making this request.
  • attrs (dict) – The attributes to be sent in the body of the request.
  • resource_id – This resource’s identifier, if needed by the request. The default is None.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
Returns:

A dict representing the response body.

Raises:

MethodNotSupported if Resource.allow_create is not set to True.

create(session)

Create a remote resource from this instance.

Parameters:session (Session) – The session to use for making this request.
Returns:This Resource instance.
Raises:MethodNotSupported if Resource.allow_create is not set to True.
classmethod get_data_by_id(session, resource_id, path_args=None, args=None, include_headers=False)

Get the attributes of a remote resource from an id.

Parameters:
  • session (Session) – The session to use for making this request.
  • resource_id – This resource’s identifier, if needed by the request.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
  • args (dict) – A dictionary of query parameters to be appended to the compound URL.
  • include_headers (bool) – True if header data should be included in the response body, False if not.
Returns:

A dict representing the response body.

Raises:

MethodNotSupported if Resource.allow_retrieve is not set to True.

classmethod get_by_id(session, resource_id, path_args=None, include_headers=False)

Get an object representing a remote resource from an id.

Parameters:
  • session (Session) – The session to use for making this request.
  • resource_id – This resource’s identifier, if needed by the request.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
  • include_headers (bool) – True if header data should be included in the response body, False if not.
Returns:

A Resource object representing the response body.

Raises:

MethodNotSupported if Resource.allow_retrieve is not set to True.

get(session, include_headers=False, args=None)

Get the remote resource associated with this instance.

Parameters:
  • session (Session) – The session to use for making this request.
  • include_headers (bool) – True if header data should be included in the response body, False if not.
  • args (dict) – A dictionary of query parameters to be appended to the compound URL.
Returns:

This Resource instance.

Raises:

MethodNotSupported if Resource.allow_retrieve is not set to True.

classmethod head_data_by_id(session, resource_id, path_args=None)

Get a dictionary representing the headers of a remote resource.

Parameters:
  • session (Session) – The session to use for making this request.
  • resource_id – This resource’s identifier, if needed by the request.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
Returns:

A dict containing the headers.

Raises:

MethodNotSupported if Resource.allow_head is not set to True.

classmethod head_by_id(session, resource_id, path_args=None)

Get an object representing the headers of a remote resource.

Parameters:
  • session (Session) – The session to use for making this request.
  • resource_id – This resource’s identifier, if needed by the request.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
Returns:

A Resource representing the headers.

Raises:

MethodNotSupported if Resource.allow_head is not set to True.

head(session)

Get the remote resource headers associated with this instance.

Parameters:session (Session) – The session to use for making this request.
Returns:This Resource instance.
Raises:MethodNotSupported if Resource.allow_head is not set to True.
classmethod update_by_id(session, resource_id, attrs, path_args=None)

Update a remote resource with the given attributes.

Parameters:
  • session (Session) – The session to use for making this request.
  • resource_id – This resource’s identifier, if needed by the request.
  • attrs (dict) – The attributes to be sent in the body of the request.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
Returns:

A dict representing the response body.

Raises:

MethodNotSupported if Resource.allow_update is not set to True.

update(session)

Update the remote resource associated with this instance.

Parameters:session (Session) – The session to use for making this request.
Returns:This Resource instance.
Raises:MethodNotSupported if Resource.allow_update is not set to True.
classmethod delete_by_id(session, resource_id, path_args=None)

Delete a remote resource with the given id.

Parameters:
  • session (Session) – The session to use for making this request.
  • resource_id – This resource’s identifier, if needed by the request.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
Returns:

None

Raises:

MethodNotSupported if Resource.allow_delete is not set to True.

delete(session)

Delete the remote resource associated with this instance.

Parameters:session (Session) – The session to use for making this request.
Returns:None
Raises:MethodNotSupported if Resource.allow_update is not set to True.
classmethod list(session, path_args=None, paginated=False, params=None)

This method is a generator which yields resource objects.

This resource object list generator handles pagination and takes query params for response filtering.

Parameters:
  • session (Session) – The session to use for making this request.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
  • paginated (bool) – True if a GET to this resource returns a paginated series of responses, or False if a GET returns only one page of data. When paginated is False only one page of data will be returned regardless of the API’s support of pagination.
  • params (dict) – Query parameters to be passed into the underlying get() method. Values that the server may support include limit and marker.
Returns:

A generator of Resource objects.

Raises:

MethodNotSupported if Resource.allow_list is not set to True.

classmethod find(session, name_or_id, path_args=None, ignore_missing=True)

Find a resource by its name or id.

Parameters:
  • session (Session) – The session to use for making this request.
  • name_or_id – This resource’s identifier, if needed by the request. The default is None.
  • path_args (dict) – A dictionary of arguments to construct a compound URL. See How path_args are used for details.
  • ignore_missing (bool) – When set to False ResourceNotFound will be raised when the resource does not exist. When set to True, None will be returned when attempting to find a nonexistent resource.
Returns:

The Resource object matching the given name or id or None if nothing matches.

Raises:

openstack.exceptions.DuplicateResource if more than one resource is found for this request.

Raises:

openstack.exceptions.ResourceNotFound if nothing is found and ignore_missing is False.

How path_args are used

As Resources often contain compound Resource.base_paths, meaning the path is constructed from more than just that string, the various request methods need a way to fill in the missing parts. That’s where path_args come in.

For example:

class ServerIP(resource.Resource):
    base_path = "/servers/%(server_id)s/ips"

Making a GET request to obtain server IPs requires the ID of the server to check. This is handled by passing {"server_id": "12345"} as the path_args argument when calling Resource.get_by_id(). From there, the method uses Python’s string interpolation to fill in the server_id piece of the URL, and then makes the request.

Creative Commons Attribution 3.0 License

Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.