karbor.api.openstack package

Submodules

karbor.api.openstack.wsgi module

class karbor.api.openstack.wsgi.ActionDispatcher

Bases: object

Maps method name to local methods through action name.

default(data)
dispatch(*args, **kwargs)

Find and call local method.

class karbor.api.openstack.wsgi.Controller(view_builder=None)

Bases: object

Default controller.

static assert_valid_body(body, entity_name)
static is_valid_body(body, entity_name)
static validate_name_and_description(body)
static validate_string_length(value, entity_name, min_length=0, max_length=None, remove_whitespaces=False)

Check the length of specified string.

Parameters
  • value – the value of the string

  • entity_name – the name of the string

  • min_length – the min_length of the string

  • max_length – the max_length of the string

  • remove_whitespaces – True if trimming whitespaces is needed else False

wsgi_actions = {}
wsgi_extensions = []
class karbor.api.openstack.wsgi.ControllerMetaclass(name, bases, cls_dict)

Bases: type

Controller metaclass.

This metaclass automates the task of assembling a dictionary mapping action keys to method names.

class karbor.api.openstack.wsgi.DictSerializer

Bases: karbor.api.openstack.wsgi.ActionDispatcher

Default request body serialization.

default(data)
serialize(data, action='default')
exception karbor.api.openstack.wsgi.Fault(exception)

Bases: webob.exc.HTTPException

Wrap webob.exc.HTTPException to provide API friendly response.

class karbor.api.openstack.wsgi.JSONDeserializer

Bases: karbor.api.openstack.wsgi.TextDeserializer

default(datastring)
class karbor.api.openstack.wsgi.JSONDictSerializer

Bases: karbor.api.openstack.wsgi.DictSerializer

Default JSON request body serialization.

default(data)
exception karbor.api.openstack.wsgi.OverLimitFault(message, details, retry_time)

Bases: webob.exc.HTTPException

Rate-limited request response.

class karbor.api.openstack.wsgi.Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)

Bases: karbor.wsgi.common.Request

best_match_content_type()

Determine the most acceptable content-type.

Based on:
  1. URI extension (.json)

  2. Content-type header

  3. Accept* headers

best_match_language()

Determines best available locale from the Accept-Language header.

Returns

the best language match or None if the ‘Accept-Language’ header was not available in the request.

get_content_type()
class karbor.api.openstack.wsgi.Resource(controller, action_peek=None, **deserializers)

Bases: karbor.wsgi.common.Application

WSGI app that handles (de)serialization and controller dispatch.

WSGI app that reads routing information supplied by RoutesMiddleware and calls the requested action method upon its controller. All controller action methods must accept a ‘req’ argument, which is the incoming wsgi.Request. If the operation is a PUT or POST, the controller method must also accept a ‘body’ argument (the deserialized request body). They may raise a webob.exc exception or return a dict, which will be serialized by requested content type.

Exceptions derived from webob.exc.HTTPException will be automatically wrapped in Fault() to provide API friendly error responses.

deserialize(meth, content_type, body)
dispatch(method, request, action_args)

Dispatch a call to the action-specific method.

get_action_args(request_environment)

Parse dictionary created by routes library.

get_body(request)
get_method(request, action, content_type, body)

Look up the action-specific method and its extensions.

post_process_extensions(extensions, resp_obj, request, action_args)
pre_process_extensions(extensions, request, action_args)
register_actions(controller)

Registers controller actions with this resource.

register_extensions(controller)

Registers controller extensions with this resource.

class karbor.api.openstack.wsgi.ResourceExceptionHandler

Bases: object

Context manager to handle Resource exceptions.

Used when processing exceptions generated by API implementation methods (or their extensions). Converts most exceptions to Fault exceptions, with the appropriate logging.

class karbor.api.openstack.wsgi.ResponseObject(obj, code=None, **serializers)

Bases: object

Bundles a response object with appropriate serializers.

Object that app methods may return in order to bind alternate serializers with a response object to be serialized. Its use is optional.

attach(**kwargs)

Attach slave templates to serializers.

property code

Retrieve the response status.

get_serializer(content_type, default_serializers=None)

Returns the serializer for the wrapped object.

Returns the serializer for the wrapped object subject to the indicated content type. If no serializer matching the content type is attached, an appropriate serializer drawn from the default serializers will be used. If no appropriate serializer is available, raises InvalidContentType.

property headers

Retrieve the headers.

preserialize(content_type, default_serializers=None)

Prepares the serializer that will be used to serialize.

Determines the serializer that will be used and prepares an instance of it for later call. This allows the serializer to be accessed by extensions for, e.g., template extension.

serialize(request, content_type, default_serializers=None)

Serializes the wrapped object.

Utility method for serializing the wrapped object. Returns a webob.Response object.

class karbor.api.openstack.wsgi.TextDeserializer

Bases: karbor.api.openstack.wsgi.ActionDispatcher

Default request body deserialization.

default(datastring)
deserialize(datastring, action='default')
karbor.api.openstack.wsgi.action(name)

Mark a function as an action.

The given name will be taken as the action key in the body.

This is also overloaded to allow extensions to provide non-extending definitions of create and delete operations.

karbor.api.openstack.wsgi.action_peek_json(body)

Determine action to invoke.

karbor.api.openstack.wsgi.deserializers(**deserializers)

Attaches deserializers to a method.

This decorator associates a dictionary of deserializers with a method. Note that the function attributes are directly manipulated; the method is not wrapped.

karbor.api.openstack.wsgi.extends(*args, **kwargs)

Indicate a function extends an operation.

Can be used as either:

@extends
def index(...):
    pass

or as:

@extends(action='resize')
def _action_resize(...):
    pass
karbor.api.openstack.wsgi.response(code)

Attaches response code to a method.

This decorator associates a response code with a method. Note that the function attributes are directly manipulated; the method is not wrapped.

karbor.api.openstack.wsgi.serializers(**serializers)

Attaches serializers to a method.

This decorator associates a dictionary of serializers with a method. Note that the function attributes are directly manipulated; the method is not wrapped.

Module contents

WSGI middleware for OpenStack API controllers.

class karbor.api.openstack.APIMapper(controller_scan=<function controller_scan>, directory=None, always_scan=False, register=True, explicit=True)

Bases: routes.mapper.Mapper

connect(*args, **kwargs)

Create and connect a new Route to the Mapper.

Usage:

m = Mapper()
m.connect(':controller/:action/:id')
m.connect('date/:year/:month/:day', controller="blog",
          action="view")
m.connect('archives/:page', controller="blog", action="by_page",
requirements = { 'page':'\d{1,2}' })
m.connect('category_list', 'archives/category/:section',
          controller='blog', action='category',
          section='home', type='list')
m.connect('home', '', controller='blog', action='view',
          section='home')
routematch(url=None, environ=None)

Match a URL against against one of the routes contained.

Will return None if no valid match is found, otherwise a result dict and a route object is returned.

resultdict, route_obj = m.match('/joe/sixpack')
class karbor.api.openstack.ProjectMapper(controller_scan=<function controller_scan>, directory=None, always_scan=False, register=True, explicit=True)

Bases: karbor.api.openstack.APIMapper

resource(member_name, collection_name, **kwargs)

Generate routes for a controller resource

The member_name name should be the appropriate singular version of the resource given your locale and used with members of the collection. The collection_name name will be used to refer to the resource collection methods and should be a plural version of the member_name argument. By default, the member_name name will also be assumed to map to a controller you create.

The concept of a web resource maps somewhat directly to ‘CRUD’ operations. The overlying things to keep in mind is that mapping a resource is about handling creating, viewing, and editing that resource.

All keyword arguments are optional.

controller

If specified in the keyword args, the controller will be the actual controller used, but the rest of the naming conventions used for the route names and URL paths are unchanged.

collection

Additional action mappings used to manipulate/view the entire set of resources provided by the controller.

Example:

map.resource('message', 'messages', collection={'rss':'GET'})
# GET /message/rss (maps to the rss action)
# also adds named route "rss_message"
member

Additional action mappings used to access an individual ‘member’ of this controllers resources.

Example:

map.resource('message', 'messages', member={'mark':'POST'})
# POST /message/1/mark (maps to the mark action)
# also adds named route "mark_message"
new

Action mappings that involve dealing with a new member in the controller resources.

Example:

map.resource('message', 'messages', new={'preview':'POST'})
# POST /message/new/preview (maps to the preview action)
# also adds a url named "preview_new_message"
path_prefix

Prepends the URL path for the Route with the path_prefix given. This is most useful for cases where you want to mix resources or relations between resources.

name_prefix

Perpends the route names that are generated with the name_prefix given. Combined with the path_prefix option, it’s easy to generate route names and paths that represent resources that are in relations.

Example:

map.resource('message', 'messages', controller='categories',
    path_prefix='/category/:category_id',
    name_prefix="category_")
# GET /category/7/message/1
# has named route "category_message"

requirements

A dictionary that restricts the matching of a variable. Can be used when matching variables with path_prefix.

Example:

map.resource('message', 'messages',
     path_prefix='{project_id}/',
     requirements={"project_id": R"\d+"})
# POST /01234/message
#    success, project_id is set to "01234"
# POST /foo/message
#    404 not found, won't be matched by this route
parent_resource

A dict containing information about the parent resource, for creating a nested resource. It should contain the member_name and collection_name of the parent resource. This dict will be available via the associated Route object which can be accessed during a request via request.environ['routes.route']

If parent_resource is supplied and path_prefix isn’t, path_prefix will be generated from parent_resource as “<parent collection name>/:<parent member name>_id”.

If parent_resource is supplied and name_prefix isn’t, name_prefix will be generated from parent_resource as “<parent member name>_”.

Example:

>>> from routes.util import url_for
>>> m = Mapper()
>>> m.resource('location', 'locations',
...            parent_resource=dict(member_name='region',
...                                 collection_name='regions'))
>>> # path_prefix is "regions/:region_id"
>>> # name prefix is "region_"
>>> url_for('region_locations', region_id=13)
'/regions/13/locations'
>>> url_for('region_new_location', region_id=13)
'/regions/13/locations/new'
>>> url_for('region_location', region_id=13, id=60)
'/regions/13/locations/60'
>>> url_for('region_edit_location', region_id=13, id=60)
'/regions/13/locations/60/edit'

Overriding generated path_prefix:

>>> m = Mapper()
>>> m.resource('location', 'locations',
...            parent_resource=dict(member_name='region',
...                                 collection_name='regions'),
...            path_prefix='areas/:area_id')
>>> # name prefix is "region_"
>>> url_for('region_locations', area_id=51)
'/areas/51/locations'

Overriding generated name_prefix:

>>> m = Mapper()
>>> m.resource('location', 'locations',
...            parent_resource=dict(member_name='region',
...                                 collection_name='regions'),
...            name_prefix='')
>>> # path_prefix is "regions/:region_id"
>>> url_for('locations', region_id=51)
'/regions/51/locations'