Tethys Platform
Table Of Contents
Table Of Contents

App Base Class API

Last Updated: May 2017

Tethys apps are configured via the app class, which is contained in the app configuration file (app.py) of the app project. The app class must inherit from the TethysAppBase to be recognized by Tethys. The following article contains the API documentation for the TethysAppBase class.

Properties

class tethys_apps.base.TethysAppBase

Base class used to define the app class for Tethys apps.

name

Name of the app.

Type

string

index

Lookup term for the index URL of the app.

Type

string

icon

Location of the image to use for the app icon.

Type

string

package

Name of the app package.

Type

string

root_url

Root URL of the app.

Type

string

color

App theme color as RGB hexadecimal.

Type

string

description

Description of the app.

Type

string

tag

A string for filtering apps.

Type

string

enable_feedback

Shows feedback button on all app pages.

Type

boolean

feedback_emails

A list of emails corresponding to where submitted feedback forms are sent.

Type

list

Override Methods

TethysAppBase.url_maps()

Override this method to define the URL Maps for your app. Your UrlMap objects must be created from a UrlMap class that is bound to the root_url of your app. Use the url_map_maker() function to create the bound UrlMap class. If you generate your app project from the scaffold, this will be done automatically. Starting in Tethys 3.0, the WebSocket protocol is supported along with the HTTP protocol. To create a WebSocket UrlMap, follow the same pattern used for the HTTP protocol. In addition, provide a Consumer path in the controllers parameter as well as a WebSocket string value for the new protocol parameter for the WebSocket UrlMap. Alternatively, Bokeh Server can also be integrated into Tethys using Django Channels and Websockets. Tethys will automatically set these up for you if a handler and handler_type parameters are provided as part of the UrlMap.

Returns

A list or tuple of UrlMap objects.

Return type

iterable

Example:

from tethys_sdk.base import url_map_maker

class MyFirstApp(TethysAppBase):

    def url_maps(self):
        """
        Example url_maps method.
        """
        # Create UrlMap class that is bound to the root url.
        UrlMap = url_map_maker(self.root_url)

        url_maps = (
            UrlMap(name='home',
                url='my-first-app',
                controller='my_first_app.controllers.home',
            ),
            UrlMap(name='home_ws',
                url='my-first-ws',
                controller='my_first_app.controllers.HomeConsumer',
                protocol='websocket'
            ),
            UrlMap(name='bokeh_handler',
                url='my-first-app/bokeh-example',
                controller='my_first_app.controllers.bokeh_example',
                handler='my_first_app.controllers.bokeh_example_handler',
                handler_type='bokeh'
            ),
        )

        return url_maps
TethysAppBase.permissions()

Override this method to define permissions for your app.

Returns

A list or tuple of Permission or PermissionGroup objects.

Return type

iterable

Example:

from tethys_sdk.permissions import Permission, PermissionGroup

class MyFirstApp(TethysAppBase):

    def permissions(self):
        """
        Example permissions method.
        """
        # Viewer Permissions
        view_map = Permission(
            name='view_map',
            description='View map'
        )

        delete_projects = Permission(
            name='delete_projects',
            description='Delete projects'
        )

        create_projects = Permission(
            name='create_projects',
            description='Create projects'
        )

        admin = PermissionGroup(
            name='admin',
            permissions=(delete_projects, create_projects)
        )


        permissions = (admin, view_map)

        return permissions
TethysAppBase.custom_settings()

Override this method to define custom settings for use in your app.

Returns

A list or tuple of CustomSetting objects.

Return type

iterable

Example:

from tethys_sdk.app_settings import CustomSetting

class MyFirstApp(TethysAppBase):

    def custom_settings(self):
        """
        Example custom_settings method.
        """
        custom_settings = (
            CustomSetting(
                name='default_name',
                type=CustomSetting.TYPE_STRING
                description='Default model name.',
                required=True
            ),
            CustomSetting(
                name='max_count',
                type=CustomSetting.TYPE_INTEGER,
                description='Maximum allowed count in a method.',
                required=False
            ),
            CustomSetting(
                name='change_factor',
                type=CustomSetting.TYPE_FLOAT,
                description='Change factor that is applied to some process.',
                required=True
            ),
            CustomSetting(
                name='enable_feature',
                type=CustomSetting.TYPE_BOOLEAN,
                description='Enable this feature when True.',
                required=True
            )
        )

        return custom_settings
TethysAppBase.persistent_store_settings()

Override this method to define a persistent store service connections and databases for your app.

Returns

A list or tuple of PersistentStoreDatabaseSetting or PersistentStoreConnectionSetting objects.

Return type

iterable

Example:

from tethys_sdk.app_settings import PersistentStoreDatabaseSetting, PersistentStoreConnectionSetting

class MyFirstApp(TethysAppBase):

    def persistent_store_settings(self):
        """
        Example persistent_store_settings method.
        """

        ps_settings = (
            # Connection only, no database
            PersistentStoreConnectionSetting(
                name='primary',
                description='Connection with superuser role needed.',
                required=True
            ),
            # Connection only, no database
            PersistentStoreConnectionSetting(
                name='creator',
                description='Create database role only.',
                required=False
            ),
            # Spatial database
            PersistentStoreDatabaseSetting(
                name='spatial_db',
                description='for storing important spatial stuff',
                required=True,
                initializer='appsettings.model.init_spatial_db',
                spatial=True,
            ),
            # Non-spatial database
            PersistentStoreDatabaseSetting(
                name='temp_db',
                description='for storing temporary stuff',
                required=False,
                initializer='appsettings.model.init_temp_db',
                spatial=False,
            )
        )

        return ps_settings
TethysAppBase.dataset_service_settings()

Override this method to define dataset service connections for use in your app.

Returns

A list or tuple of DatasetServiceSetting objects.

Return type

iterable

Example:

from tethys_sdk.app_settings import DatasetServiceSetting

class MyFirstApp(TethysAppBase):

    def dataset_service_settings(self):
        """
        Example dataset_service_settings method.
        """
        ds_settings = (
            DatasetServiceSetting(
                name='primary_ckan',
                description='Primary CKAN service for app to use.',
                engine=DatasetServiceSetting.CKAN,
                required=True,
            ),
            DatasetServiceSetting(
                name='hydroshare',
                description='HydroShare service for app to use.',
                engine=DatasetServiceSetting.HYDROSHARE,
                required=False
            )
        )

        return ds_settings
TethysAppBase.spatial_dataset_service_settings()

Override this method to define spatial dataset service connections for use in your app.

Returns

A list or tuple of SpatialDatasetServiceSetting objects.

Return type

iterable

Example:

from tethys_sdk.app_settings import SpatialDatasetServiceSetting

class MyFirstApp(TethysAppBase):

    def spatial_dataset_service_settings(self):
        """
        Example spatial_dataset_service_settings method.
        """
        sds_settings = (
            SpatialDatasetServiceSetting(
                name='primary_geoserver',
                description='spatial dataset service for app to use',
                engine=SpatialDatasetServiceSetting.GEOSERVER,
                required=True,
            ),
        )

        return sds_settings
TethysAppBase.web_processing_service_settings()

Override this method to define web processing service connections for use in your app.

Returns

A list or tuple of WebProcessingServiceSetting objects.

Return type

iterable

Example:

from tethys_sdk.app_settings import WebProcessingServiceSetting

class MyFirstApp(TethysAppBase):

    def web_processing_service_settings(self):
        """
        Example wps_services method.
        """
        wps_services = (
            WebProcessingServiceSetting(
                name='primary_52n',
                description='WPS service for app to use',
                required=True,
            ),
        )

        return wps_services
TethysAppBase.handoff_handlers()

Override this method to define handoff handlers for use in your app.

Returns

A list or tuple of HandoffHandler objects.

Return type

iterable

Example:

from tethys_sdk.handoff import HandoffHandler

class MyFirstApp(TethysAppBase):

    def handoff_handlers(self):
        """
        Example handoff_handlers method.
        """
        handoff_handlers = (
            HandoffHandlers(
                name='example',
                handler='my_first_app.controllers.my_handler'
            ),
        )

        return handoff_handlers
TethysAppBase.job_templates()

Override this method to define job templates to easily create and submit jobs in your app.

Returns

A list or tuple of JobTemplate objects.

Return type

iterable

Example:

from tethys_sdk.jobs import CondorJobTemplate
from tethys_sdk.compute import list_schedulers

class MyFirstApp(TethysAppBase):

    def job_templates(cls):
        """
        Example job_templates method.
        """
        my_scheduler = list_schedulers()[0]

        job_templates = (CondorJobTemplate(name='example',
                                           parameters={'executable': '$(APP_WORKSPACE)/example_exe.py',
                                                       'condorpy_template_name': 'vanilla_transfer_files',
                                                       'attributes': {'transfer_input_files': ('../input_1.in', '../input_2.in'),
                                                                      'transfer_output_files': ('example_output1.out', 'example_output2.out'),
                                                                     },
                                                       'scheduler': my_scheduler,
                                                       'remote_input_files': ('$(APP_WORKSPACE)/example_exe.py', '$(APP_WORKSPACE)/input_1.in', '$(USER_WORKSPACE)/input_2.in'),
                                                      }
                                          ),
                        )

        return job_templates
classmethod TethysAppBase.pre_delete_app_workspace()

Override this method to pre-process the app workspace before it is emptied

classmethod TethysAppBase.post_delete_app_workspace()

Override this method to post-process the app workspace after it is emptied

classmethod TethysAppBase.pre_delete_user_workspace(user)

Override this method to pre-process a user's workspace before it is emptied

Parameters

user (User, required) -- User that requested to clear their workspace

classmethod TethysAppBase.post_delete_user_workspace(user)

Override this method to post-process a user's workspace after it is emptied

Parameters

user (User, required) -- User that requested to clear their workspace

Class Methods

classmethod TethysAppBase.get_custom_setting(name)

Retrieves the value of a CustomSetting for the app.

Parameters

name (str) -- The name of the CustomSetting as defined in the app.py.

Returns

Value of the CustomSetting or None if no value assigned.

Return type

variable

Example:

from my_first_app.app import MyFirstApp as app

max_count = app.get_custom_setting('max_count')
classmethod TethysAppBase.get_persistent_store_connection(name, as_url=False, as_sessionmaker=False)

Gets an SQLAlchemy Engine or URL object for the named persistent store connection.

Parameters
  • name (string) -- Name of the PersistentStoreConnectionSetting as defined in app.py.

  • as_url (bool) -- Return SQLAlchemy URL object instead of engine object if True. Defaults to False.

  • as_sessionmaker (bool) -- Returns SessionMaker class bound to the engine if True. Defaults to False.

Returns

An SQLAlchemy Engine or URL object for the persistent store requested.

Return type

sqlalchemy.Engine or sqlalchemy.URL

Example:

from my_first_app.app import MyFirstApp as app

conn_engine = app.get_persistent_store_connection('primary')
conn_url = app.get_persistent_store_connection('primary', as_url=True)
SessionMaker = app.get_persistent_store_database('primary', as_sessionmaker=True)
session = SessionMaker()
classmethod TethysAppBase.get_persistent_store_database(name, as_url=False, as_sessionmaker=False)

Gets an SQLAlchemy Engine or URL object for the named persistent store database given.

Parameters
  • name (string) -- Name of the PersistentStoreConnectionSetting as defined in app.py.

  • as_url (bool) -- Return SQLAlchemy URL object instead of engine object if True. Defaults to False.

  • as_sessionmaker (bool) -- Returns SessionMaker class bound to the engine if True. Defaults to False.

Returns

An SQLAlchemy Engine or URL object for the persistent store requested.

Return type

sqlalchemy.Engine or sqlalchemy.URL

Example:

from my_first_app.app import MyFirstApp as app

db_engine = app.get_persistent_store_database('example_db')
db_url = app.get_persistent_store_database('example_db', as_url=True)
SessionMaker = app.get_persistent_store_database('example_db', as_sessionmaker=True)
session = SessionMaker()
classmethod TethysAppBase.get_dataset_service(name, as_public_endpoint=False, as_endpoint=False, as_engine=False)

Retrieves dataset service engine assigned to named DatasetServiceSetting for the app.

Parameters
  • name (str) -- name fo the DatasetServiceSetting as defined in the app.py.

  • as_endpoint (bool) -- Returns endpoint url string if True, Defaults to False.

  • as_public_endpoint (bool) -- Returns public endpoint url string if True. Defaults to False.

  • as_engine (bool) -- Returns tethys_dataset_services.engine of appropriate type if True. Defaults to False.

Returns

DatasetService assigned to setting if no other options are specified.

Return type

DatasetService

Example:

from my_first_app.app import MyFirstApp as app

ckan_engine = app.get_dataset_service('primary_ckan', as_engine=True)
classmethod TethysAppBase.get_spatial_dataset_service(name, as_public_endpoint=False, as_endpoint=False, as_wms=False, as_wfs=False, as_engine=False)

Retrieves spatial dataset service engine assigned to named SpatialDatasetServiceSetting for the app.

Parameters
  • name (str) -- name fo the SpatialDatasetServiceSetting as defined in the app.py.

  • as_endpoint (bool) -- Returns endpoint url string if True, Defaults to False.

  • as_public_endpoint (bool) -- Returns public endpoint url string if True. Defaults to False.

  • as_wfs (bool) -- Returns OGC-WFS enpdoint url for spatial dataset service if True. Defaults to False.

  • as_wms (bool) -- Returns OGC-WMS enpdoint url for spatial dataset service if True. Defaults to False.

  • as_engine (bool) -- Returns tethys_dataset_services.engine of appropriate type if True. Defaults to False.

Returns

SpatialDatasetService assigned to setting if no other options are specified.

Return type

SpatialDatasetService

Example:

from my_first_app.app import MyFirstApp as app

geoserver_engine = app.get_spatial_dataset_service('primary_geoserver', as_engine=True)
classmethod TethysAppBase.get_web_processing_service(name, as_public_endpoint=False, as_endpoint=False, as_engine=False)

Retrieves web processing service engine assigned to named WebProcessingServiceSetting for the app.

Parameters
  • name (str) -- name fo the WebProcessingServiceSetting as defined in the app.py.

  • as_endpoint (bool) -- Returns endpoint url string if True, Defaults to False.

  • as_public_endpoint (bool) -- Returns public endpoint url string if True. Defaults to False.

  • as_engine (bool) -- Returns owslib.wps.WebProcessingService engine if True. Defaults to False.

Returns

WpsService assigned to setting if no other options are specified.

Return type

WpsService

Example:

from my_first_app.app import MyFirstApp as app

wps_engine = app.get_web_processing_service('primary_52n')
classmethod TethysAppBase.get_handoff_manager()

Get the HandoffManager for the app.

classmethod TethysAppBase.get_job_manager()

Get the JobManager for the app.

Deprecated since version 2.1.

classmethod TethysAppBase.get_app_workspace()

Get the file workspace (directory) for the app.

Returns

An object representing the workspace.

Return type

tethys_apps.base.TethysWorkspace

Example:

import os
from my_first_app.app import MyFirstApp as app

def a_controller(request):
    """
    Example controller that uses get_app_workspace() method.
    """
    # Retrieve the workspace
    app_workspace = app.get_app_workspace()
    new_file_path = os.path.join(app_workspace.path, 'new_file.txt')

    with open(new_file_path, 'w') as a_file:
        a_file.write('...')

    context = {}

    return render(request, 'my_first_app/template.html', context)

Deprecated since version 2.1.

classmethod TethysAppBase.get_user_workspace(user)

Get the file workspace (directory) for the given User.

Parameters

user (User or HttpRequest) -- User or request object.

Returns

An object representing the workspace.

Return type

tethys_apps.base.TethysWorkspace

Example:

import os
from my_first_app.app import MyFirstApp as app

def a_controller(request):
    """
    Example controller that uses get_user_workspace() method.
    """
    # Retrieve the workspace
    user_workspace = app.get_user_workspace(request.user)
    new_file_path = os.path.join(user_workspace.path, 'new_file.txt')

    with open(new_file_path, 'w') as a_file:
        a_file.write('...')

    context = {}

    return render(request, 'my_first_app/template.html', context)
classmethod TethysAppBase.list_persistent_store_connections()

Returns a list of existing persistent store connections for this app.

Returns

A list of persistent store connection names.

Return type

list

Example:

from my_first_app.app import MyFirstApp as app

ps_connections = app.list_persistent_store_connections()
classmethod TethysAppBase.list_persistent_store_databases(dynamic_only=False, static_only=False)

Returns a list of existing persistent store databases for the app.

Parameters
  • dynamic_only (bool) -- only persistent store created dynamically if True. Defaults to False.

  • static_only (bool) -- only static persistent stores if True. Defaults to False.

Returns

A list of all persistent store database names for the app.

Return type

list

Example:

from my_first_app.app import MyFirstApp as app

ps_databases = app.list_persistent_store_databases()
classmethod TethysAppBase.persistent_store_exists(name)

Returns True if a persistent store with the given name exists for the app.

Parameters

name (string) -- Name of the persistent store database to check.

Returns

True if persistent store exists.

Return type

bool

Example:

from my_first_app.app import MyFirstApp as app

result = app.persistent_store_exists('example_db')

if result:
    engine = app.get_persistent_store_engine('example_db')
classmethod TethysAppBase.create_persistent_store(db_name, connection_name, spatial=False, initializer='', refresh=False, force_first_time=False)

Creates a new persistent store database for the app. This method is idempotent.

Parameters
  • db_name (string) -- Name of the persistent store that will be created.

  • connection_name (string|None) -- Name of persistent store connection or None if creating a test copy of an existing persistent store (only while in the testing environment)

  • spatial (bool) -- Enable spatial extension on the database being created when True. Connection must have superuser role. Defaults to False.

  • initializer (string) -- Dot-notation path to initializer function (e.g.: 'my_first_app.models.init_db').

  • refresh (bool) -- Drop database if it exists and create again when True. Defaults to False.

  • force_first_time (bool) -- Call initializer function with "first_time" parameter forced to True, even if this is not the first time intializing the persistent store database. Defaults to False.

Returns

True if successful.

Return type

bool

Example:

from my_first_app.app import MyFirstApp as app

result = app.create_persistent_store('example_db', 'primary')

if result:
    engine = app.get_persistent_store_engine('example_db')
classmethod TethysAppBase.drop_persistent_store(name)

Drop a persistent store database for the app. This method is idempotent.

Parameters

name (string) -- Name of the persistent store to be dropped.

Returns

True if successful.

Return type

bool

Example:

from my_first_app.app import MyFirstApp as app

result = app.drop_persistent_store('example_db')

if result:
    # App database 'example_db' was successfully destroyed and no longer exists
    pass