Open source cms for mobile and desktop websites

nive_datastore.webapi

class nive_datastore.webapi.view.APIv1(context, request)
getItem()

Returns one or multiple items. This function either returns the current item if called without parameter or if id is passed as request form value one or multiple child items.

Request parameter:

  • id: the items’ id or a list of multiple items. leave empty to get the current

    item. Ignored if strict is true.

Returns json encoded data

Settings:

  • toJson: (list) fields included in json result. Can be type specific. The data fields included in the result are

    rendered based on customized view settings or the types’ default toJson value.

  • render: (list) list of fields to be rendered before being included in the result. The result depends on the

    individual fields. E.g. list fields would be returned as readable name not the raw data value.

  • strict: (bool) If True only the single item matching the current url is included in the result.

  • maxBatchItems: (number) the maximum number of returned in one call

  • deserialize: (callback) pluginpoint for a custom deserialization callback. The callback is once for the whole result.

    Takes two parameters items, view and should return the processed items.

You can also turn on strict the mode. If turned on getItem can only be called for the object to be retrieved itself, not for the container.

Customized getItem view

bookmark = ViewConf(
    name="read-bookmark",
    attr="getItem",
    # ...
    settings={
        "toJson": ("link", "share", "comment"),
        "render": ("pool_create",),
        "strict": True,
    }
)

To define the returned fields of multiple object types use a dict instead of a tuple and use the type id as key

bookmark = ViewConf(
    name="read-bookmark",
    attr="getItem",
    # ...
    settings = {
        "toJson": {"bookmark": ("link", "share", "comment")},
        "strict": False
    }
)

To mix defaults for multiple types and specific fields for other types use default__ as key.

bookmark = ViewConf(
    name="read-bookmark",
    attr="getItem",
    # ...
    settings = {
        "toJson": {
            "default__": ("id", "pool_type"),
            "bookmark": ("link", "share", "comment") },
        "strict": False
    }
)

The default value for toJson is loaded from the types’ ObjectConf.toJson settings

collection1 = ObjectConf(
    id = "bookmark",
    #...
    toJson = ("link", "share", "comment"),
)

In all cases each returned json bookmark item contains the values for link, share and comment.

newItem()

Creates a single item or a set of items as batch. Values are serialized and validated by ‘newItem’ form subset or the form setup configured for the customized view.

Request parameter:

  • type: the new type to be created. Must be set for each item.
  • <fields>: A single item can be passed directly as form values without wraping it as items.
  • items: One or multiple items to be stored. Multiple items have to be passed as array.

Returns json encoded result: {“result”: list of new item ids}

Settings:

  • type: (string/tuple) the type id created by the function. If set the type id passed in the request must match

    the settings. Use a tuple to allow multiple type ids.

  • form: (dict) form setup for validation settings. If not set the default form setup is loaded from the types’

    configuration.

  • values: (dict) a slot for default values not part of the form.

  • maxStoreItems: (number) the maximum number of items stored in one call.

  • serialize: (callback) pluginpoint for a custom serialization callback. The callback is invoked before each item is created.

    Takes three parameters data, typename, view and should return the processed data dict. If ValueError is raised the item is skipped and the next is processed.

Customized newItem view example

bookmark = ViewConf(
    name="add-bookmark",
    attr="newItem",
    # ...
    settings={"form": {"fields": ("link", "share", "comment")}
              "type": "bookmark",
              "maxStoreItems": 3,
              "values": {"source": "webapi"}
    }
)

The default forms setting is loaded from the types’ ObjectConf.forms settings for newItem

collection1 = ObjectConf(
    id = "bookmark",
    # ...
    forms = {
        "newItem": {"fields": ("link", "share", "comment"),
                    "defaults": {"share": True}},
    },
    # ...
)

In all examples newItem validates and stores 3 form fields: link, share, comment.

If you are using the default newItem view you have to pass the type id to be created by the function as form parameter type=bookmark. If you are using a customized view the type can be part of the views options slot settings={"type": "bookmark"}.

setItem()

Store a single item or a set of items as batch. Values are serialized and validated by ‘setItem’ form subset or the form setup configured for the customized view.

Request parameter:

  • <fields>: A single item can be passed as form values.
  • items: One or multiple items to be stored. Multiple items have to be passed as array.

Returns json encoded result: {“result”: list of stored item ids}

Settings:

  • strict: (bool) If True only the single item matching the current url will be updated.

  • form: (dict) form setup for validation settings. If not set the default form setup is loaded from the types’

    configuration.

  • values: (dict) a slot for default values not part of the form

  • maxStoreItems: (number) the maximum number of items store in one call

  • serialize: (callable) pluginpoint for a custom serialization callback. The callback is invoked before each item is created.

    Takes three parameters data, typename, view and should return the processed data dict.

You can also turn on strict the mode. If turned on setItem can only be called for the object to be updated itself, not for the container.

Customized setItem view

bookmark = ViewConf(
    name="update-bookmark",
    attr="setItem",
    ...
    settings = {
        "form": {"fields": ("link", "share", "comment"),
                 "defaults": {"share": True}},
        "strict": True
    }
)

The default forms setting is loaded from the types’ ObjectConf.forms settings for setItem

collection1 = ObjectConf(
    id = "bookmark",
    # ...
    forms = {
        "setItem": {"fields": ("link", "share", "comment")},
    },
    # ...
)

In all examples setItem validates and stores 3 form fields: link, share, comment.

deleteItem()

Delete one or more items.

For customized views you change the behaviour whether contained objects are removed recursively or not. By default recursive is True.

You can also turn on strict the mode. If turned on deleteItem can only be called for the object to be deleted itself, not for the container.

Another supported option is a confirmation id. If used the item will only be deleted if the confirmation is present in the request. In combination with template renderers you can easily build a confirmation dialog box to get input from the user. By default confirm is None.

Request parameter:

  • id: (number,list) the items’ id or a list of ids if strict is set to False
  • confirmation: the confirmation token if enabled.

Returns json encoded result: {“result”: list of deleted item ids}

Settings:

  • strict: (bool) If True only the single item matching the current url will be updated.

  • recursive: (bool) If False deleteItem will not remove container items havng children.

  • confirmation: (string) a confirmation token required to be passed in the request.

  • maxDeleteItems: (number) the maximum number of items deleted in one call. Recursively deleted

    items are not counted.

You can also turn on strict the mode. If turned on setItem can only be called for the object to be updated itself, not for the container.

  1. Customized deleteItem view

    bookmark = ViewConf(
        name="delete-bookmark",
        attr="deleteItem",
        ...
        settings = {
            "strict": True,
            "recursive": False,
            "confirm": "g3d4ea8b1",
            "maxDeleteItems": 3
        }
    )
    
listItems()

Returns a list of batched items for a single or all types stored in the current container. Fast and efficient listing function. listItems uses the access permissions of the container and does not check access permissions for items included in the result. The result can only inlcude meta layer fields and type fields for a single type.

For an advanced listing function use subtree or search.

Request parameter:

  • sort: sort field. a meta field or if type is not empty, one of the types fields.
  • order: ‘<’,’>’. order the result list based on values ascending ‘<’ or descending ‘>’
  • size: number of batched items. maximum is 100.
  • start: start number of batched result sets.

Returns json encoded result set: {“items”:[[item values], [item values]], “start”:number}

Settings:

  • type: (string) the type id to load data fields from. Can be empty if only meta fields are included

    in the result.

  • fields: (list) fields included in json result. Either meta layer field ids or type specific fields

    for a single type.

  • maxBatchItems: (number) the maximum number of returned in one call

  • deserialize: (callback) pluginpoint for a custom deserialization callback. The callback is invoked once for

    the whole result. Takes two parameters items, view and should return the processed items.

Customized listItems view

bookmark = ViewConf(
    name="list-bookmark",
    attr="listItems",
    ...
    settings = {
        "fields": ("link", "share", "comment", "pool_create"),
        "type": "bookmark"
    }
)
search()

Advanced search functions with many optionsand support for preconfigured search profiles. The functions returns a set of batched items encoded as json.

Search profiles can be preconfigured and stored in the datastore application configuration or for each customized view.

Request parameter

  • profile: (string) the search profile name if not set in the configuration.

All other values extracted from the request and used in the search as parameter or batching, sort, order have to be defined in the configuration as settings[“dynamic”] = {} values.

Return value

  • items: list of items
  • start: if batched the current start number
  • size: maximum batch size
  • total: number of items in total

The return value is based on the linked renderer. By default the result is returned as json encoded result set:

{"items":[items], "start":number, "size":number, "total":number}

Settings:

  • sort: (string) is a field name and used to sort the result.

  • order: (string) either ‘<’,’>’ or empty. Orders the result list based on values ascending ‘<’ or descending ‘>’

  • size: (number) number of batched items.

  • start: (number) start number of batched result sets.

  • type: (string) type id. If type is not empty this function uses nive.search.SearchType, if empty nive.search.Search.

    The data fields to be included in the result have to be assigned respectively. In other words if type is given the types data fields can be included in the result, otherwise not.

  • container: (bool) determines whether to search in the current container or search all items in the tree.

  • fields: (list) a list of data fields to be included in the result set. See nive.search.

  • parameter: (dict/callback) is a dictionary or callable of fixed query parameters used in the select statement. These values cannot

    be changed through request form values. The callback takes two parameters context and request and should return a dictionary. E.g.

    def makeParam(context, request):
        return {"id": context.id}
    
    settings = {
        # ...
        # adds the contexts file as parameter
        "parameter": makeParam,
        # ...
    }
    

    or as inline function definition

    settings = {
        # ...
        # adds the contexts file as parameter
        "parameter": lambda context, request, view: {"id": context.id},
        # ...
    }
    
  • dynamic: (dict) these values values are extracted from the request. The values listed here are the defaults

    if not found in the request. The dynamic values are mixed with the fixed parameters and passed to the query.

  • operators: (dict) fieldname:operator entries used for search conditions. See nive.search.

  • ignoreEmpty: (bool) automatically removes empty dynamic values and so these are not included in select statements.

  • advanced: (dict) search options like group restraints. See nive.search for details and all supported options.

  • groups: (string/list) use the groups defintion to restrict the execution to users assigned to one of the groups.

    For customized views it is recommended to use the view permissions directly.

Here is a simple example how to search for all bookmarks

settings = {
    "type": "bookmark",
    "container": False,
    "fields": ["id", "link", "comment"],
    "parameter": {"share": True},
    "dynamic": {"start": 0},
    "sort": "pool_change",
    "order": "<",
    "size": 30,
}

The same example extended with text search in comment. This one allows you to pass in a text matched against the comment field of each bookmark

settings = {
    "type": "bookmark",
    "container": False,
    "fields": ["id", "link", "comment"],
    "parameter": {"share": True},
    "dynamic": {"start": 0, "text": ""},
    "operators": {"text": "LIKE"},
    "sort": "pool_change",
    "order": "<",
    "size": 30,
}

The system provides two options to configure search profiles. The first one uses the application configuration

datastore = AppConf(
    search = {
        # the default profile if no name is given
        "default": {
            # profile values go here
        },
        "extended": {
            # profile values go here
        },
    }
)

To use the extended profile pass the profiles name as query parameter e.g. http://myapp.com/storage/search?profile=extended. This way search will always return json.

The second option is to add a custom view based on search. This way you can add a custom renderer, view name and permissions

search = ViewConf(
    name="list",
    attr="search",
    context="nive_datastore.root.root",
    permission="view",
    renderer="myapp:templates/list.pt",
    settings = {
        # search profile values go here
    }
)
subtree()

Returns complex results like parts of a subtree including multiple levels. Contained items can be accessed through items in the result. subtree uses the items configuration render option to determine the result values rendered in a json document. If render is None the item will not be rendered at all.

Request parameter

  • profile: (string) the subtree profile name if not set in the configuration.

Return values

The return value is based on the linked renderer. By default the result is returned as json encoded result set:

{"items": {"items": {<values>}, <values>}, <values>}

Settings

  • levels: (number) the number of levels to include, 0=include all (default)
  • secure: (bool) if true the api-subtree permission is checked for each item
  • descent: (item type, interface) item types or interfaces to descent into subtree e.g. (IContainer,)
  • toJson: (dict or tuple) result values. If empty uses the types toJson defaults
  • parameter: (dict) query parameter for result selection e.g. {“pool_state”: 1}
  • addContext: (bool) adds the item object as context to the result

A simple configuration looks as follows

settings = {
    "levels": 0,
    "descent": (IContainer,),
    "toJson": {"bookmark": ("comment", share")},
    "parameter": {"pool_state": 1}
}

The system provides two options to configure subtree profiles. The first one uses the application configuration

datastore = AppConf(
    subtree = {
        # the default profile if no name is given
        "default": {
            # profile values go here
        },
        "extended": {
            # profile values go here
        },
    }
)

To use the extended profile pass the profiles name as query parameter e.g. http://myapp.com/storage/subtree?profile=extended. In this case subtree() will always return json.

The second option is to add a custom view based on subtree. This way you can add a custom renderer, view name and permissions:

subtree = ViewConf(
    name="tree",
    attr="subtree",
    context="nive_datastore.root.root",
    permission="view",
    renderer="myapp:templates/tree.pt",
    settings={
        # subtree profile values go here
    }
)
newItemForm()

Renders and executes a web form based on the configured form setup. All form validation and processing is handled automatically and if the processing succeeds the new item will be stored with the values submitted.

The form setup requires the items type either passed in the request or configured as part of the settings.

Request parameter

  • assets: You can call newItemForm?assets=only to get the required css, js assets only. The form

    iteself will not be processed. Use this in combination with settings[“includeAssets”] = False for single page applications or to load assets only once.

Return values

  • body: This function returns rendered html code as body.
  • X-Result header: http header indicating whether the new item has been created or not.

Settings

  • type: (string) type id of new item to be created. if empty type is extracted from request.

  • form: (dict/string) the form setup as form definition including form fields and options or the subset

    to be loaded from the types configuration settings. This slot supports all nive.HTMLForm options

  • values: (dict) additional values used for the new item. These values are independent from fields or

    form defaults.

  • includeAssets: (bool) include js/css assets required by the form in the html markup. default true.

For example the configuration for a new item form might loook like

settings = {
    "form": {"fields": ("link", "share", "comment"),
             "use_ajax": True}
    "type": "bookmark",
    "includeAssets": False,
    "values": {"source": "webform"}
}

Configuration lookup order :

  1. Customized newItemForm view

    bookmark = ViewConf(
        name="add-bookmark",
        attr="newItemForm",
        # ...
        settings={"form": {"fields": ("link", "share", "comment"),
                           "use_ajax": True}
                  "type": "bookmark",
                  "values": {"source": "webform"}
        }
    )
    
  2. The types’ ObjectConf.forms settings for newItem

    collection1 = ObjectConf(
        id = "bookmark",
        # ...
        forms = {
            "newItem": {"fields": ("link", "share", "comment"),
                        "use_ajax": True},
            "setItem": {"fields": ("link", "share", "comment"),
                        "use_ajax": True}
        },
        # ...
    )
    

defines the newItem form in both cases with 3 form fields and to use ajax submissions

{"fields": ("link", "share", "comment"), "use_ajax": True}

If you are using the default newItemForm view you have to pass the type id to be created by the function as form parameter type=bookmark. If you are using a customized view the type can be part of the views options slot settings={"type": "bookmark"}.

To get required assets in a seperate call use ?assets=only as query parameter. This will return the required css and js assets for the specific form only.

setItemForm()

Renders and executes a web form based on the configured form setup. All form validation and processing is handled automatically and if the processing succeeds the item will be updated with the values submitted.

Request parameter

  • assets: You can call setItemForm?assets=only to get the required css, js assets only. The form

    iteself will not be processed. Use this in combination with settings[“includeAssets”] = False for single page applications or to load assets only once.

Return values

  • body: This function returns rendered html code as body.
  • X-Result header: http header indicating whether the new item has been created or not.

Settings

  • form: (dict/string) the form setup as form definition including form fields and options or the subset

    to be loaded from the types configuration settings. This slot supports all nive.HTMLForm options

  • values: (dict) additional values used for the new item. These values are independent from fields or

    form defaults.

  • includeAssets: (bool) include js/css assets required by the form in the html markup. default true.

For example the configuration for a new item form might loook like

settings = {
    "form": {"fields": ("link", "share", "comment"),
             "use_ajax": True}
    "values": {"source": "webform"}
}

Configuration lookup order :

  1. Customized setItemForm view

    bookmark = ViewConf(
        name="update-bookmark",
        attr="setItemForm",
        # ...
        settings={"form": {"fields": ("link", "share", "comment"),
                           "use_ajax": True}
                  "values": {"source": "webform"}
        }
    )
    
  2. The types’ ObjectConf.forms settings for setItem

    collection1 = ObjectConf(
        id = "bookmark",
        # ...
        forms = {
            "newItem": {"fields": ("link", "share", "comment"),
                        "use_ajax": True},
            "setItem": {"fields": ("link", "share", "comment"),
                        "use_ajax": True}
        },
        # ...
    )
    

defines the setItem form in both cases with 3 form fields and to use ajax submissions

{"fields": ("link", "share", "comment"), "use_ajax": True}

If you are using the default setItemForm view you have to pass the type id to be created by the function as form parameter type=bookmark. If you are using a customized view the type can be part of the views options slot settings={"type": "bookmark"}.

To get required assets in a seperate call use ?assets=only as query parameter. This will return the required css and js assets for the specific form only.

action()

Trigger a workflow action based on the contexts current state.

Parameters: - action: action name to be triggered - transition (optional): transition if multiple match action - test (optional): if ‘true’ the action is not triggered but only

tested if the current user is allowed to run the action in the current context.

returns the action result and new state information

{“result”:true/false, “messages”: [], “state”: {}}

state()

Get the current contexts’ workflow state.

returns state information

  • id: the state id
  • name: the state name
  • process: id and name of active workflow process
  • transistions: list of possible transitions for the current state

each transition includes

  • id: the id
  • name: the name
  • fromstate: the current state
  • tostate: new state after axcecution
  • actions: list of triggering actions for the transition
renderTmpl(template=None)

Renders the items template defined in the configuration (ObjectConf.template). The template will be called with a dictionary containing the item, request and view.

See pyramid.renderers for possible template engines.

Link the template in the objects type configuration

collection1 = ObjectConf(
    id = "bookmark",
    template="bookmark.pt",
    # ...
)

You can now add a custom view and use the objects template without linking it in the view definition.

bookmark = ViewConf(
name=”render-me”, attr=”renderTmpl”, # ...

)

tmpl()

For view based template rendering. An instance of the view class is automatically passed to the template as view. The current context can be accessed as context.

See pyramid.renderers for possible template engines.

Configuration example

bookmark = ViewConf(
    name="render-me",
    attr="tmpl",
    renderer="myapp:templates/bookmark.pt",
    #  ...
)
renderListItem(values, typename=None, template=None, **kw)

This function renders data records (non object) returned by Select or Search functions with the object configuration defined listing renderer.

Unlike the object renderer this function does not require full object loads like renderTmpl but works with simple dictionary lists.

Make sure all values required to render the template are passed to renderListItems i.e. included as result in the select functions.

E.g.

Configuration

ObjectConf(id="article", listing="article-list.pt", ...)

Template

<h2>${name}</h2>
<p>${text}</p>
<a href="${pool_filename}">read all</a>

Usage

<div tal:content="structure view.renderListItem(values, 'article')"
     class="col-lg-12"></div>
Values:
Typename:
Template:
© 2013 Nive GmbH