ptah

URI

ptah.resolve(uri)

Resolve uri, return resolved object.

Uri contains two parts, schema and uuid. schema is used for resolver selection. uuid is resolver specific data. By default uuid is a uuid.uuid4 string.

class ptah.resolver(schema, _resolver__depth=1)

Register resolver for given schema. resolver is decorator style registration.

param schema:uri schema

Resolver interface ptah.interfaces.resolver

import ptah

@ptah.resolver('custom-schema')
def my_resolver(uri):
   ....

# now its possible to resolver 'custom-schema:xxx' uri's
ptah.resolve('custom-schema:xxx')
classmethod register(schema, resolver)

Register resolver for given schema

Parameters:
  • schema – uri schema
  • resolver – Callable object that accept one parameter.

Example:

import ptah

def my_resolver(uri):
   ....

ptah.resolver.register('custom-schema', my_resolver)

# now its possible to resolver 'custom-schema:xxx' uri's
ptah.resolve('custom-schema:xxx')
classmethod pyramid(cfg, schema, resolver)

pyramid configurator directive ptah_uri_resolver.

config = Configurator()
config.include('ptah')

def my_resolver(uri):
    ....

config.ptah_uri_resolver('custom-schema', my_resolver)
ptah.extract_uri_schema(uri)

Extract schema of given uri

class ptah.UriFactory(schema)

Uri Generator

uri = UriFactory('cms-content')

uri()
'cms-content:f73f3266fa15438e94cca3621a3f2dbc'
__call__()

Generate new uri using supplied schema

Snippet

Snippet is very similar to pyramid view. It doesnt availble with pyramid traversing. It doesnt have security.

class ptah.snippet

Register snippet.

Parameters:
  • name – Snippet name
  • context – Snippet context
  • renderer – Pyramid renderer

Example:

import ptah

@ptah.snippet('test', Context, renderer='...:test.pt')
def snippet(request):
    ...

ptah.render_snippet('test', Context(), request)

To render snippet use ptah.render_snippet() or ptah.View.snippet.

classmethod register(name, context=None, view=None, renderer=None)

Register snippet.

Parameters:
  • name – Snippet name
  • context – Snippet context
  • view – View implementation
  • renderer – Pyramid renderer
def snippet(request):
    ...

ptah.snippet.register('test', Context, view=snippet):
    ...
ptah.render_snippet(name, context, request)

Render snippet

Parameters:
  • name – Name of snippet
  • context – Context for snippet
  • request – Current request
Return type:

string with rendered html

Layout

class ptah.layout

Registers a layout.

Parameters:
  • name – Layout name
  • context – Specific context for this layout.
  • root – Root object
  • parent – A parent layout. None means no parent layout.
  • renderer – A pyramid renderer
  • route_name – A pyramid route_name. Apply layout only for specific route
  • use_global_views – Apply layout to all routes. even is route doesnt use use_global_views.

Simple example with one default layout and ‘page’ layout.

import ptah

@ptah.layout('page', parent='page', renderer='ptah:template/page.pt')
class PageLayout(ptah.View):
     ...

@ptah.layout('', parent='page', renderer='ptah:template/template.pt')
class DefaultLayout(object):
     ...

To use layout with pyramid view use wrapper=ptah.wrap_layout()

Example:

config.add_view('
    index.html',
    wrapper=ptah.wrap_layout(),
    renderer = '...')

in this example ‘’ layout is beeing used. You can specify specific layout name for pyramid view ptah.wrap_layout('page')

classmethod register(name='', context=None, root=None, parent='', renderer=None, route_name=None, use_global_views=False, view=<class 'ptah.view.View'>)

Imperative layout registration.

Parameters:
  • name – Layout name
  • context – Specific context for this layout.
  • root – Root object
  • parent – A parent layout. None means no parent layout.
  • renderer – A pyramid renderer
  • route_name – A pyramid route_name. Apply layout only for specific route
  • use_global_views – Apply layout to all routes. even is route doesnt use use_global_views.
  • view – Layout implementation (same as for pyramid view)
ptah.layout.register('page', renderer='...', view=MyLayout)
classmethod pyramid(cfg, name='', context=None, root=None, parent='', renderer=None, route_name=None, use_global_views=False, view=<class 'ptah.view.View'>)

Pyramid ptah_layout directive:

config = Configurator()
config.include('ptah')

config.ptah_layout('page', renderer='..')
ptah.wrap_layout(layout='')

Generate view name for pyramid view declaration.

config = Configurator()
config.include('ptah')

config.ptah_layout('page')

config.add_view(
    'index.html',
    wrapper=ptah.wrap_layout())

Library

ptah.library(name, path='', type='', require='', prefix='', postfix='', extra=None)

Registers a library with one or more assets. Used to logically group JS and CSS collections. Provides ability to declarare dependency/requirements between library collections.

Parameters:
  • name – Library collection name
  • path – The path argument points at a file or directory on disk.
  • type – A string, either css or js
  • require – A library name to be considered dependency (Optional)
  • prefix – A string which will be generated before the library HTML
  • postfix – A string which will be generated after the library HTML An example of prefix/postfix is <!– JS/CSS –>
  • extra – Additional attributes for computed library tag An example of extra is {‘type’:’text/pythonscript’}
ptah.include(request, *args)

Given a library name; the library will be attached to the request. See render_includes function to compute the HTML from attached libraries.

Parameters:
  • request – Pyramid request
  • name – Name of library to include
ptah.render_includes(request)

Renders HTML for all included libraries for this request.

Parameters:request – Pyramid request

Settings

ptah.get_settings(grp, registry=None)

Get settings group by group id. Also there is ptah_get_settins pyramid configurator directive.

config = Configurator()
config.include('ptah')
config.commit()

# get settings with pyramid directive
ptah_settings = config.ptah_get_settings('ptah')

# get settings with `get_settings`
ptah_settings = ptah.get_settings(ptah.CFG_ID_PTAH, config.registry)
ptah.settings.init_settings(pconfig, cfg=None, section='DEFAULT')

Initialize settings management system. This function available as pyramid configurator directive. You should call it during application configuration process.

config = Configurator()
config.include('ptah')

# initialize ptah setting management system
config.ptah_init_settings()
ptah.register_settings(name, *fields, **kw)

Register settings group.

Parameters:
  • name – Name of settings group
  • fields – List of ptah.form.Field objects

ACL

ptah.ACLs

ACLs dictionary contains all registered acl maps in the system.

class ptah.ACL(id, title, description='')

Named ACL map

ACL contains list of permit rules, for example:

>> acl = ACL('test', 'Test ACL')
>> acl.allow('system.Everyone', 'View')
>> acl.deny('system.Everyone', 'Edit')

>> list(acl)
[(Allow, 'system.Everyone', ('View',)),
 (Deny, 'system.Everyone', ('Edit',))]
allow(role, *permissions)

Give permissions to role

deny(role, *permissions)

Deny permissions for role

unset(role, *permissions)

Unset any previously defined permissions

class ptah.ACLsProperty

This property merges __acls__ list of ACLs and generate one __acl__

For example:

>> class Content(object):
...
...   __acls__ = ['map1', 'map2']
...
...   __acl__ = ACLsProperty()

In this case it is possible to manipulate permissions by just changing __acls__ list.

ptah.get_acls()

return list of registered ACLS

class ptah.IACLsAware(name, bases=(), attrs=None, __doc__=None, __module__=None)

acl maps aware context

Roles

class ptah.Role(name, title, description='')

Register new security role in the system

ptah.get_local_roles(userid, request=None, context=None, get_cfg_storage=<function get_cfg_storage at 0x2ae8410>)

calculates local roles for userid

ptah.get_roles()

return list of registered roles

class ptah.IOwnersAware(name, bases=(), attrs=None, __doc__=None, __module__=None)

Owners aware context

__owner__

Owner principal uri

class ptah.ILocalRolesAware(name, bases=(), attrs=None, __doc__=None, __module__=None)

Local roles aware context

__local_roles__
ptah.Everyone
ptah.Authenticated
ptah.Owner

Permissions

ptah.Permission(name, title, description='')

Register new permission.

ptah.get_permissions()

return list of registered permissions

ptah.check_permission(permission, context, request=None, throw=False)

Check permission withing context.

Parameters:
  • permission ((Permission or sting)) – Permission
  • context – Context object
  • throw – Throw HTTPForbidden exception.
ptah.DEFAULT_ACL
ptah.NOT_ALLOWED
ptah.NO_PERMISSION_REQUIRED

Security

ptah.auth_service

Instance of ptah.authentication.Authentication class.

ptah.SUPERUSER_URI

System user uri. Permission check always passes for user user. It is possible to use it as effective user:

ptah.auth_service.set_effective_user(ptah.SUPERUSER_URI)

This allow to pass security checks for any user.

ptah.auth_checker(checker, __cfg=None, __depth=1)

Register authentication checker. Checker function accepts ptah.authentication.AuthInfo object.

Parameters:checker – Checker function.

Checker function interface ptah.interfaces.auth_checker()

@ptah.auth_checker
def my_checker(info):
    ...
class ptah.auth_provider(name, _auth_provider__depth=1)

Register authentication provider. Auth provider interface ptah.interfaces.AuthProvider

Parameters:name – provider name
@ptah.auth_provider('my-provider')
class AuthProvider(object):
     ...
classmethod register(name, provider)

authentication provider registration:

.. code-block:: python
class AuthProvider(object):
...

ptah.auth_provider.register(‘my-provider’, AuthProvider)

ptah.search_principals(term)

Search principals by term, it uses principal_searcher functions

class ptah.principal_searcher(name, _principal_searcher__depth=1)

Register principal searcher function.

Searcher function interface ptah.interfaces.principal_searcher()

@ptah.principal_searcher('test')
def searcher(term):
     ...

searcher function receives text as term variable, and should return iterator to principal objects.

classmethod register(name, searcher)

register principal searcher:

def searcher(term):
    ...

ptah.principal_searcher.register('test', searcher)

Password utils

ptah.pwd_tool

Instance of ptah.password.PasswordTool class

class ptah.password.PasswordTool

Password management utility.

can_change_password(principal)

Can principal password be changed. ptah.password_changer is beeing used.

change_password(passcode, password)

Encode and change password. ptah.password_changer is beeing used.

Parameters:
  • passcode – Previously generated passcode
  • passsword – Plain password.
Return type:

True if password has been changed, False otherwise.

check(encoded, password)

Compare encoded password with plain password.

Parameters:
  • encoded – Encoded password
  • password – Plain password
encode(password, salt=None)

Encode password with current password manager

generate_passcode(principal)

Generate passcode for principal.

Parameters:principal – Principal object
get_principal(passcode)

Return principal by previously generated passcode.

remove_passcode(passcode)

Remove passcode

validate(password)

Validate password

class ptah.password_changer(schema, _password_changer__depth=1)

Register password changer function.

Parameters:schema – Principal uri schema.
@ptah.password_change('myuser')
def change_password(principal, password):
    principal.password = password
classmethod pyramid(cfg, schema, changer)

pyramid password changer registration directive.

Parameters:
  • schema – Principal uri schema.
  • changer – Function
config = Configurator()
config.include('ptah')

config.ptah_password_changer('custom-schema', custom_changer)

Utilities

ptah.get_base()

Return the central SQLAlchemy declarative base.

ptah.get_session()

Return the central SQLAlchemy contextual session.

To customize the kinds of sessions this contextual session creates, call its configure method:

ptah.get_session().configure(...)

But if you do this, be careful about the ‘ext’ arg. If you pass it, the ZopeTransactionExtension will be disabled and you won’t be able to use this contextual session with transaction managers. To keep the extension active you’ll have to re-add it as an argument. The extension is accessible under the semi-private variable _zte. Here’s an example of adding your own extensions without disabling the ZTE:

ptah.get_session().configure(ext=[ptah._zte, ...])
ptah.reset_session()

Reset sqla session

class ptah.Pagination(page_size, left_neighbours=3, right_neighbours=3)

simple pagination

ptah.tldata
class ptah.JsonDictType

function which returns a SQLA Column Type suitable to store a Json dict.

Returns:ptah.sqla.MutationDict
class ptah.JsonListType

function which returns a SQLA Column Type suitable to store a Json array.

Returns:ptah.sqla.MutationList
ptah.generate_fieldset(model, fieldNames=None, namesFilter=None, skipPrimaryKey=True)
Parameters:
  • model – subclass of sqlalchemy.ext.declarative.declarative_base
  • fieldNamesoptional sequence of strings to use
  • namesFilteroptional callable which takes a key and list of fieldNames to compute if fieldName should filtered out of Fieldset generation.
  • skipPrimaryKeydefault: True Should PrimaryKey be omitted from fieldset generation.
Returns:

a instance of ptah.form.Fieldset

ptah.build_sqla_fieldset(columns, skipPrimaryKey=False)

Given a list of SQLAlchemy columns generate a ptah.form.Fieldset.

Parameters:
  • columns – sequence of sqlachemy.schema.Column instances
  • skipPrimaryKeydefault: False boolean whether to include PK Columns in Fieldset generation.
Returns:

a instance of ptah.form.Fieldset

ptah.rst_to_html(text)

Status messages

ptah.add_message(request, msg, type='info')

Add status message

Predefined message types

  • info
  • success
  • warning
  • error
ptah.render_messages(request)

Render previously added messages

UI Actions

ptah.uiaction(context, id, title, description='', action='', condition=None, permission=None, category='', sort_weight=1.0, **kw)

Register ui action

ptah.list_uiactions(content, request, category='')

List ui actions for specific content

Data population

ptah.POPULATE_DB_SCHEMA

Id for database schema creation step. Use it as requires dependency to make sure that db schema is cerated before execute any other steps.

class ptah.populate

Registers a data populate step. Populate steps are used by Data population command line tool and by ptah_populate() pyramid directive for populate system data.

Parameters:
  • name – Unique step name
  • title – Human readable title
  • active – Should this step automaticly executed or not
  • requires – List of steps that should be executed before this step

Populate step interface ptah.interfaces.populate_step. Steps are executed after configuration is completed.

import ptah

@ptah.populate('custom-user',
               title='Create custom user',
               requires=(ptah.POPULATE_DB_SCHEMA,))
def create_custom_user(registry):
    # create user

create_custom_user executes only after ptah.POPULATE_DB_SCHEMA step.

Perpose of inactive steps is for example entering testing data or executing custom step.

Data migration

ptah.register_migration(pkg, path, title='', force=False)

Registers a migration for package. Check Data migration chapter for detailed description.

Parameters:
  • pkg – Package name
  • path – String implying a path or asset specification (e.g. ptah:migrations). Path to directory with migration scripts.
  • title – Optional human readable title.
  • force – Force execute migration during bootstrap process
import ptah

ptah.register_migration(
    'ptah', 'ptah:migrations', 'Ptah database migration')

Events

Settings events

ptah.events.SettingsInitializing(config, registry)

Settings initializing event

ptah.events.SettingsInitialized(config, registry)

ptah sends this event when settings initialization is completed.

ptah.events.SettingsGroupModified(group)

ptah sends this event when settings group is modified.

Content events

ptah.events.ContentCreatedEvent(object)

ptah.TypeInformation will send event during create().

ptah.events.ContentAddedEvent(object)

ptahcms.Container will send event when content has been created through containers __setitem__ method.

ptah.events.ContentMovedEvent(object)

ptahcms.Container will send event when content has moved.

ptah.events.ContentModifiedEvent(object)

ptahcms.Content will send event during update().

ptah.events.ContentDeletingEvent(object)

ptahcms.Container will send event before content has been deleted through containers __delitem__ method.

Principal events

ptah.events.LoggedInEvent(principal)

User logged in to system.

ptah.events.LoginFailedEvent(principal, message='')

User login failed.

ptah.events.LoggedOutEvent(principal)

User logged out.

ptah.events.ResetPasswordInitiatedEvent(principal)

User has initiated password changeing.

ptah.events.PrincipalPasswordChangedEvent(principal)

User password has been changed.

ptah.events.PrincipalValidatedEvent(principal)

Principal account has been validated.

ptah.events.PrincipalAddedEvent(principal)

Principal added event

ptah.events.PrincipalRegisteredEvent(principal)

Principal registered event

Populate db schema

ptah.events.BeforeCreateDbSchema(registry)

ptah.POPULATE_DB_SCHEMA populate step sends event before tables have been created.

registry: Pyramid registry object

Project Versions

Table Of Contents

Previous topic

API

Next topic

ptah.cms

This Page