portal_web package

Subpackages

Submodules

portal_web.config module

Helper functions for the creation of the pyramid app.

class portal_web.config.Environment(val, config)[source]

Bases: object

View predicate factory for restricting views to environments.

Parameters:
  • val (str) – value for comparison.

  • config (pyramid.config.Configurator) – App config.

Classattributes:

phash (str): hash for view predicate.

val

value for comparison.

Type:

str

phash()
text()[source]
portal_web.config.add_helpers(event)[source]

Adds helper functions as top-level name in temlating system.

Parameters:

event (pyramid.events.BeforeRender) – BeforeRender event.

Returns:

None.

portal_web.config.add_locale(event)[source]

Sets the language of the app.

Considers several sources in the following, descending order:

  1. request: manual choice of language using GET parameter _LOCALE_

  2. cookie: formerly chosen or detected language using cookie _LOCALE_

  3. browser: browser language using HTTP header Accept-Language

  4. default: en

The chosen or detected language will be saved in a cookie _LOCALE_.

Parameters:

event (pyramid.events.NewRequest) – NewRequest event.

Returns:

None.

portal_web.config.add_templates(event)[source]

Adds base templates and macros as top-level name in temlating system.

Parameters:

event (pyramid.events.BeforeRender) – BeforeRender event.

Returns:

None.

portal_web.config.context_found(event)[source]

Trigger _context_found() on context, after it has been found

portal_web.config.debug_context(event)[source]

Prints context to debug log.

Parameters:

event (pyramid.events.ContextFound) – ContextFound event.

Returns:

None.

portal_web.config.debug_request(event)[source]

Prints request to debug log.

Parameters:

event (pyramid.events.NewRequest) – NewRequest event.

Returns:

None.

portal_web.config.debug_response(event)[source]

Prints response to debug log.

Parameters:

event (pyramid.events.NewRequest) – NewRequest event.

Returns:

None.

portal_web.config.get_plugins(settings=None, environment=None)[source]

Fetches plugin settings based on module name pattern matching.

The module name pattern needs to be configured in the portal app settings as key plugins.pattern. All modules starting with this pattern will be treated as portal plugins.

Note

Dots in module names get substituted by an underscore.

Parameters:

settings (dict) – Parsed [app:main] section of .ini file.

Returns:

plugin settings.

Return type:

dict

Examples

>>> settings = { 'plugins.pattern': '_web' }
>>> print(get_plugins(settings))
{
    200: {
        'path': '/ado/src/someplugin_web',
        'name': 'someplugin_web',
        'settings': {}
    },
    100: {
        'path': '/ado/src/anotherplugin_web',
        'name': 'anotherplugin_web',
        'settings': {}
    }
}
portal_web.config.notfound(request)[source]

Not Found view (404 Error).

Parameters:

request (pyramid.request) – Current request.

Returns:

404 Response.

Return type:

pyramid.httpexceptions.HTTPNotFound

portal_web.config.party(request)[source]
portal_web.config.replace_environment_vars(settings)[source]

Substitues placeholders in app settings with environment variables.

Values in the app settings with the syntax ${ENVIRONMENT_VARIABLE} are substituted with the respective value of the key ENVIRONMENT_VARIABLE in the environment variables.

Parameters:

settings (dict) – Parsed [app:main] section of .ini file.

Returns:

substituted settings.

Return type:

dict

Examples

>>> import os
>>> os.environ['SERVICE'] = 'webgui'
>>> settings = { 'service': '${SERVICE}' }
>>> print(replace_environment_vars(settings))
{ 'service' = 'webgui' }
Raises:

AssertionError – on unsubstituted setting.

portal_web.config.roles(request)[source]
portal_web.config.start_db_transaction(event)[source]

Starts a transaction on a pool db connection. If needed, open database.

portal_web.config.stop_db_transaction(event)[source]

Stops a transaction so the db connection can be freed back to the db connection pool

portal_web.config.user(request)[source]
portal_web.config.web_user(request)[source]

portal_web.helpers module

Helper functions included as top-level names in temlating system.

portal_web.helpers.b64encode(s, altchars=None)[source]

Encode the bytes-like object s using Base64 and return a bytes object.

Optional altchars should be a byte string of length 2 which specifies an alternative alphabet for the ‘+’ and ‘/’ characters. This allows an application to e.g. generate url or filesystem safe Base64 strings.

portal_web.helpers.format_currency(value, places=None, curr=None, sep=None, dp=None, pos=None, neg=None, trailneg=None)[source]

Convert Decimal to a money formatted string.

Defaults to currency of tryton company.

Parameters:
  • places – required number of places after the decimal point

  • curr – optional currency symbol before the sign (may be blank)

  • sep – optional grouping separator (comma, period, space, or blank)

  • dp – decimal point indicator (comma or period) only specify as blank when places is zero

  • pos – optional sign for positive numbers: ‘+’, space or blank

  • neg – optional sign for negative numbers: ‘-’, ‘(’, space or blank

  • trailneg – optional trailing minus indicator: ‘-’, ‘)’, space or blank

Returns:

Formatted money value.

Return type:

str

Examples

>>> d = Decimal('-1234567.8901')
>>> format_currency(d, curr='$')
'-$1,234,567.89'
>>> format_currency(d, places=0, sep='.', dp='', neg='', trailneg='-')
'1.234.568-'
>>> format_currency(d, curr='$', neg='(', trailneg=')')
'($1,234,567.89)'
>>> format_currency(Decimal(123456789), sep=' ')
'123 456 789.00'
>>> format_currency(Decimal('-0.02'), neg='<', trailneg='>')
'<0.02>'

portal_web.includes module

Functions to include resources/views and register content by the plugin system.

The following functions are called by convention on app creation:

  • web_resources

  • web_registry

  • web_views

  • api_views

portal_web.includes.api_views(config)[source]

Adds the views for the api service.

Note

The function is called by the plugin system, when the app is created.

Parameters:

config (pyramid.config.Configurator) – App config.

Returns:

None.

portal_web.includes.web_registry(config)[source]

Extends the registry for content elements for the web service.

Note

The function is called by the plugin system, when the app is created.

Parameters:

config (pyramid.config.Configurator) – App config.

Returns:

None.

portal_web.includes.web_resources(config)[source]

Extends the resource tree for the web service.

Note

The function is called by the plugin system, when the app is created.

Parameters:

config (pyramid.config.Configurator) – App config.

Returns:

None.

portal_web.includes.web_views(config)[source]

Adds the views for the web service.

Note

The function is called by the plugin system, when the app is created.

Parameters:

config (pyramid.config.Configurator) – App config.

Returns:

None.

portal_web.resources module

Base resources including base, web-/apirootfactory, back-/frontend, debug

class portal_web.resources.ApiRootFactory(request, context=None)[source]

Bases: ResourceBase

Root resource factory for api service.

Parameters:

request (pyramid.request.Request) – Current request.

Access:

No permissions (not needed for api views)

class portal_web.resources.ArticleResource(request, id)[source]

Bases: ResourceBase

Example for an article resource for news content provided by the registry.

Parameters:
  • request (pyramid.request.Request) – Current request.

  • id (int) – Article id.

Access:

No permissions

class portal_web.resources.BackendResource(request, context=None)[source]

Bases: ResourceBase

Root resource for users logged in (“backend”).

Parameters:

request (pyramid.request.Request) – Current request.

Access:

Authenticated: read

class portal_web.resources.DebugResource(request, context=None)[source]

Bases: ResourceBase

Root resource for debug views.

Note

To be included in the resource tree in development environment only.

Parameters:

request (pyramid.request.Request) – Current request.

Access:

No permissions (not needed for debug views)

class portal_web.resources.FrontendResource(request, context=None)[source]

Bases: ResourceBase

Root resource for users not logged in (“frontend”).

Parameters:

request (pyramid.request.Request) – Current request.

Access:

No permissions (not needed for page views)

class portal_web.resources.ModelResource(request, code)[source]

Bases: ResourceBase

class portal_web.resources.NewsResource(request, context=None)[source]

Bases: ResourceBase

Example for a news resource for news content provided by the registry.

Parameters:

request (pyramid.request.Request) – Current request.

Access:

No permissions

class portal_web.resources.PrettyDefaultdict[source]

Bases: defaultdict

class portal_web.resources.ProfileResource(request, context=None)[source]

Bases: ResourceBase

Profile resource for managing the user profile.

Parameters:

request (pyramid.request.Request) – Current request.

Access:

Authenticated: read

class portal_web.resources.ResourceBase(request, context=None)[source]

Bases: object

Base class for traversal based resources providing a content registry.

Resources are used to form flexible, hierarchical parent-child structures to reflect the url. In the first step of traversal, the URL is mapped to a resource and in the second step the resource is mapped to a pyramid view.

Children may be added to resources via the add_child() function.

The content registry may be used to assign different types of content to a resource, which is provided to pyramid views and the template engine as context. Different types might be:

  • meta (e.g. browser title, keywords, desciption, etc.)

  • content (e.g. page content, news articles, etc.)

  • static (e.g. css files, logo images, etc.)

  • menues (e.g. top navigation, sidebar navigation, etc.)

  • widgets (dynamic content elements used in different locations)

The registry of a parent class is inherited to and may be extended by its children. This allows for content elements to be present on a whole branch of resources, like logos or menues.

The registry may be extended by the extend_registry decorator function.

Note

In later versions the content of the registry might be stored in and retrieved from a database to provide CMS features.

Parameters:

request (pyramid.request.Request) – Current request.

Classattributes:

__name__ (str): URL path segment. __parent__ (obj): Instance of parent resource. __children__ (dict): Children resources. __registry__ (dict): Content registry

(dictionary or property function returning a dictionary).

__acl__ (list): Access control list

(list of tupels or property function returning a list of tupels).

_registry_cache

Cached content registry.

Type:

dict

request

Current request.

Type:

pyramid.request.Request

classmethod add_child(val)[source]

Adds a child resource to this resource.

Parameters:

val (class) – Class of child resource.

Returns:

None.

Examples

>>> ParentResource.add_child(ChildResource)
context_found()[source]
dict()[source]

Returns an autovivid dictionary for easy extension of the registry.

Returns:

Autovivid dictionary

Return type:

dict

Examples

>>> reg = self.dict()
>>> print(reg['create']['key']['path'] = 'onthefly')
{
    'create': {
        'key': {
            path': 'onthefly'
        }
    }
}
classmethod extend_registry(func)[source]

Decorator function to extend the registry.

The __registry__ class attribute might contain a dictionary or a property function returning a dictionary. By extending the registry, the original class attribute is replaced by a property function, which merges the original registry with a new registry returned by func. Registries might be extended several times.

Parameters:

func (function) – Function extending the registry.

Returns:

None

classmethod merge_registry(orig_dict, new_dict)[source]

Recursively merges dict-like objects.

Note

If a value in new_dict is {}, the key is removed in orig_dict

Parameters:
  • orig_dict (dict) – Original dictionary to be merged with.

  • new_dict (dict) – New dictionary to be merged.

Returns:

Merged dict.

Return type:

dict

Examples

>>> orig_dict = {
...     'A': {
...         'A1': 'A1',
...         'A2': 'A2'
...     },
...     'B': 'B'
... }
>>> new_dict = {
...     'A': {
...         'A2': 'XX'
...     },
...     'B': {},
...     'C': 'C'
... }
>>> print(cls.merge_registry(orig_dict, new_dict))
{
    'A': {
        'A1': 'A1',
        'A2': 'XX'
    },
    'C': 'C'
}
property registry

Gets the current registry of the resource.

The registry is retrieved by merging the (possibly extended) registry with all (possibly extended) registries of the current resource branch back to the root parent once and is cached. Additional calls will return the cached registry.

Returns:

Current registry

Return type:

dict

class portal_web.resources.WebRootFactory(request)[source]

Bases: object

Root resource factory for web service.

Parameters:

request (pyramid.request.Request) – Current request.

Returns:

If user is logged in FrontendResource: If user is not logged in

Return type:

BackendResource

Module contents

Main module for the pyramid app.

portal_web.main(global_config, **settings)[source]

Configures and creates the app.

Handles configuration of

  • debugpy debugging

  • app config

  • tryton database

  • session

  • policies

  • subscribers

  • route predicates

  • view predicates

  • request methods

  • translation directories

  • logging

  • root factories

  • resources

  • registry

  • views

Contains the main logic of the plugin system by including settings, translation directories, logging configuration, views, ressources and registry information of the plugins in a well defined order.

Parameters:
  • global_config (dict) – Parsed [DEFAULT] section of .ini file.

  • **settings (dict) – Parsed [app:main] section of .ini file.

Returns:

a Pyramid WSGI application.

Return type:

obj