def create_ps_database_setting(app_package, name, description='', required=False, initializer='', initialized=False, spatial=False, dynamic=False): from tethys_cli.cli_colors import pretty_output, FG_RED, FG_GREEN from tethys_apps.models import PersistentStoreDatabaseSetting from tethys_apps.models import TethysApp try: app = TethysApp.objects.get(package=app_package) except ObjectDoesNotExist: with pretty_output(FG_RED) as p: p.write('A Tethys App with the name "{}" does not exist. Aborted.'. format(app_package)) return False try: setting = PersistentStoreDatabaseSetting.objects.get(name=name) if setting: with pretty_output(FG_RED) as p: p.write( 'A PersistentStoreDatabaseSetting with name "{}" already exists. Aborted.' .format(name)) return False except ObjectDoesNotExist: pass try: ps_database_setting = PersistentStoreDatabaseSetting( tethys_app=app, name=name, description=description, required=required, initializer=initializer, initialized=initialized, spatial=spatial, dynamic=dynamic) ps_database_setting.save() with pretty_output(FG_GREEN) as p: p.write( 'PersistentStoreDatabaseSetting named "{}" for app "{}" created successfully!' .format(name, app_package)) return True except Exception as e: print(e) with pretty_output(FG_RED) as p: p.write('The above error was encountered. Aborted.'.format( app_package)) return False
def remove_ps_database_setting(app_package, name, force=False): from tethys_apps.models import TethysApp from tethys_cli.cli_colors import pretty_output, FG_RED, FG_GREEN from tethys_apps.models import PersistentStoreDatabaseSetting try: app = TethysApp.objects.get(package=app_package) except ObjectDoesNotExist: with pretty_output(FG_RED) as p: p.write('A Tethys App with the name "{}" does not exist. Aborted.'. format(app_package)) return False try: setting = PersistentStoreDatabaseSetting.objects.get(tethys_app=app, name=name) except ObjectDoesNotExist: with pretty_output(FG_RED) as p: p.write( 'An PersistentStoreDatabaseSetting with the name "{}" for app "{}" does not exist. Aborted.' .format(name, app_package)) return False if not force: proceed = input( 'Are you sure you want to delete the ' 'PersistentStoreDatabaseSetting named "{}"? [y/n]: '.format(name)) while proceed not in ['y', 'n', 'Y', 'N']: proceed = input('Please enter either "y" or "n": ') if proceed in ['y', 'Y']: setting.delete() with pretty_output(FG_GREEN) as p: p.write( 'Successfully removed PersistentStoreDatabaseSetting with name "{0}"!' .format(name)) return True else: with pretty_output(FG_RED) as p: p.write('Aborted. PersistentStoreDatabaseSetting not removed.') else: setting.delete() with pretty_output(FG_GREEN) as p: p.write( 'Successfully removed PersistentStoreDatabaseSetting with name "{0}"!' .format(name)) return True
def app_settings_list_command(args): load_apps() app_settings = get_app_settings(args.app) if app_settings is None: return unlinked_settings = app_settings['unlinked_settings'] linked_settings = app_settings['linked_settings'] with pretty_output(BOLD) as p: p.write("\nUnlinked Settings:") if len(unlinked_settings) == 0: with pretty_output() as p: p.write('None') else: is_first_row = True for setting in unlinked_settings: if is_first_row: with pretty_output(BOLD) as p: p.write('{0: <10}{1: <40}{2: <15}'.format( 'ID', 'Name', 'Type')) is_first_row = False with pretty_output() as p: p.write('{0: <10}{1: <40}{2: <15}'.format( setting.pk, setting.name, get_setting_type(setting))) with pretty_output(BOLD) as p: p.write("\nLinked Settings:") if len(linked_settings) == 0: with pretty_output() as p: p.write('None') else: is_first_row = True for setting in linked_settings: if is_first_row: with pretty_output(BOLD) as p: p.write('{0: <10}{1: <40}{2: <15}{3: <20}'.format( 'ID', 'Name', 'Type', 'Linked With')) is_first_row = False if hasattr(setting, 'persistent_store_service'): service_name = setting.persistent_store_service.name elif hasattr(setting, 'spatial_dataset_service'): service_name = setting.spatial_dataset_service.name elif hasattr(setting, 'dataset_service'): service_name = setting.dataset_service.name elif hasattr(setting, 'web_processing_service'): service_name = setting.web_processing_service.name elif hasattr(setting, 'value'): service_name = setting.value with pretty_output() as p: p.write( f'{setting.pk: <10}{setting.name: <40}{get_setting_type(setting): <15}{service_name: <20}' )
def link_command(args): """ Interact with Tethys Services (Spatial/Persistent Stores) to create them and/or link them to existing apps """ try: service = args.service setting = args.setting service_parts = service.split(':') setting_parts = setting.split(':') service_type = None service_uid = None setting_app_package = None setting_type = None setting_uid = None try: service_type = service_parts[0] service_uid = service_parts[1] setting_app_package = setting_parts[0] setting_type = setting_parts[1] setting_uid = setting_parts[2] except IndexError: with pretty_output(FG_RED) as p: p.write( 'Incorrect argument format. \nUsage: "tethys link <spatial|persistent>:<service_id|service_name> ' '<app_package>:<setting_type (ps_database|ps_connection|ds_spatial)><setting_id|setting_name>"' '\nCommand aborted.') exit(1) success = link_service_to_app_setting(service_type, service_uid, setting_app_package, setting_type, setting_uid) if not success: exit(1) exit(0) except Exception as e: with pretty_output(FG_RED) as p: p.write(e) p.write('An unexpected error occurred. Please try again.') exit(1)
def __init__(self, name, endpoint, username=None, password=None): """ Constructor """ self.name = name self.endpoint = endpoint self.username = username self.password = password with pretty_output(FG_WHITE) as p: p.write( 'DEPRECATION WARNING: Storing connection credentials for WPS Services in the app.py is a security ' 'leak. App configuration for WPS Services will be deprecated in version 1.2.' )
def __init__(self, name, type, endpoint, apikey=None, username=None, password=None): """ Constructor """ self.name = name # Validate the types if type in VALID_SPATIAL_ENGINES: self.type = type self.engine = VALID_SPATIAL_ENGINES[type] else: spatial_engine_key_list = list(VALID_SPATIAL_ENGINES) if len(VALID_SPATIAL_ENGINES) > 2: comma_separated_types = ', '.join( '"{0}"'.format(t) for t in spatial_engine_key_list[:-1]) last_type = '"{0}"'.format(spatial_engine_key_list[-1]) valid_types_string = '{0}, and {1}'.format( comma_separated_types, last_type) elif len(VALID_SPATIAL_ENGINES) == 2: valid_types_string = '"{0}" and "{1}"'.format( spatial_engine_key_list[0], spatial_engine_key_list[1]) else: valid_types_string = '"{0}"'.format(spatial_engine_key_list[0]) raise ValueError( 'The value "{0}" is not a valid for argument "type" of SpatialDatasetService.' ' Valid values for "type" argument include {1}.'.format( type, valid_types_string)) self.endpoint = endpoint self.apikey = apikey self.username = username self.password = password with pretty_output(FG_WHITE) as p: p.write( 'DEPRECATION WARNING: Storing connection credentials for Spatial Dataset Services ' 'in the app.py is a security leak. App configuration for Spatial Dataset Services ' 'will be deprecated in version 1.2.')
def get_manage_path(args): """ Validate user defined manage path, use default, or throw error """ # Determine path to manage.py file manage_path = os.path.join(get_tethys_src_dir(), 'tethys_portal', 'manage.py') # Check for path option if hasattr(args, 'manage'): manage_path = args.manage or manage_path # Throw error if path is not valid if not os.path.isfile(manage_path): with pretty_output(FG_RED) as p: p.write('ERROR: Can\'t open file "{0}", no such file.'.format( manage_path)) exit(1) return manage_path
def process_exception(self, request, exception): if hasattr(social_exceptions, exception.__class__.__name__): if isinstance(exception, social_exceptions.AuthCanceled): if request.user.is_anonymous: return redirect('accounts:login') else: return redirect('user:settings', username=request.user.username) elif isinstance(exception, social_exceptions.AuthAlreadyAssociated): blurb = 'The {0} account you tried to connect to has already been associated with another account.' with pretty_output(FG_WHITE) as p: p.write(exception.backend.name) if 'google' in exception.backend.name: blurb = blurb.format('Google') elif 'linkedin' in exception.backend.name: blurb = blurb.format('LinkedIn') elif 'hydroshare' in exception.backend.name: blurb = blurb.format('HydroShare') elif 'facebook' in exception.backend.name: blurb = blurb.format('Facebook') else: blurb = blurb.format('social') messages.success(request, blurb) if request.user.is_anonymous: return redirect('accounts:login') else: return redirect('user:settings', username=request.user.username) elif isinstance(exception, social_exceptions.NotAllowedToDisconnect): blurb = 'Unable to disconnect from this social account.' messages.success(request, blurb) if request.user.is_anonymous: return redirect('accounts:login') else: return redirect('user:settings', username=request.user.username)
def link_service_to_app_setting(service_type, service_uid, app_package, setting_type, setting_uid): """ Links a Tethys Service to a TethysAppSetting. :param service_type: The type of service being linked to an app. Must be either 'spatial' or 'persistent' or 'dataset' or 'wps'. :param service_uid: The name or id of the service being linked to an app. :param app_package: The package name of the app whose setting is being linked to a service. :param setting_type: The type of setting being linked to a service. Must be one of the following: 'ps_database', 'ps_connection', or 'ds_spatial'. :param setting_uid: The name or id of the setting being linked to a service. :return: True if successful, False otherwise. """ import django django.setup() from tethys_cli.cli_colors import pretty_output, FG_GREEN, FG_RED from tethys_sdk.app_settings import (SpatialDatasetServiceSetting, PersistentStoreConnectionSetting, PersistentStoreDatabaseSetting, WebProcessingServiceSetting) from tethys_services.models import ( SpatialDatasetService, DatasetService, PersistentStoreService, WebProcessingService) from tethys_apps.models import TethysApp service_type_to_model_dict = { "spatial": SpatialDatasetService, "dataset": DatasetService, "persistent": PersistentStoreService, 'wps': WebProcessingService } setting_type_to_link_model_dict = { 'ps_database': { 'setting_model': PersistentStoreDatabaseSetting, 'service_field': 'persistent_store_service' }, 'ps_connection': { 'setting_model': PersistentStoreConnectionSetting, 'service_field': 'persistent_store_service' }, 'ds_spatial': { 'setting_model': SpatialDatasetServiceSetting, 'service_field': 'spatial_dataset_service' }, 'ds_dataset': { 'setting_model': SpatialDatasetServiceSetting, 'service_field': 'dataset_service' }, 'wps': { 'setting_model': WebProcessingServiceSetting, 'service_field': 'web_processing_service' } } service_model = service_type_to_model_dict[service_type] try: try: service_uid = int(service_uid) service = service_model.objects.get(pk=service_uid) except ValueError: service = service_model.objects.get(name=service_uid) except ObjectDoesNotExist: with pretty_output(FG_RED) as p: p.write('A {0} with ID/Name "{1}" does not exist.'.format(str(service_model), service_uid)) return False try: app = TethysApp.objects.get(package=app_package) except ObjectDoesNotExist: with pretty_output(FG_RED) as p: p.write('A Tethys App with the name "{}" does not exist. Aborted.'.format(app_package)) return False try: linked_setting_model_dict = setting_type_to_link_model_dict[setting_type] except KeyError: with pretty_output(FG_RED) as p: p.write('The setting_type you specified ("{0}") does not exist.' '\nChoose from: "ps_database|ps_connection|ds_spatial"'.format(setting_type)) return False linked_setting_model = linked_setting_model_dict['setting_model'] linked_service_field = linked_setting_model_dict['service_field'] try: try: setting_uid = int(setting_uid) setting = linked_setting_model.objects.get( tethys_app=app, pk=setting_uid) except ValueError: setting = linked_setting_model.objects.get( tethys_app=app, name=setting_uid) setattr(setting, linked_service_field, service) setting.save() with pretty_output(FG_GREEN) as p: p.write('{}:"{}" was successfully linked to {}:"{}" of the "{}" Tethys App' .format(service.__class__.__name__, service.name, setting.__class__.__name__, setting.name, app_package)) return True except ObjectDoesNotExist: with pretty_output(FG_RED) as p: p.write( 'A {0} with ID/Name "{1}" does not exist.'.format(str(linked_setting_model), setting_uid)) return False