def __init__(self, json=None, data_id=None, message_type=None, timestamp=0, fields=None, metadata=None): """ If a json string is passed, it is parsed into a dictionary and its values for timestamp, fields and metadata are copied in. Otherwise, the DASRecord object is initialized with the passed-in values for instrument, timestamp, fields (a dictionary of fieldname-value pairs) and metadata. If timestamp is not specified, the instance will use the current time. """ if json: parsed = parse(json) self.data_id = parsed.get('data_id', None) self.message_type = parsed.get('message_type', None) self.timestamp = parsed.get('timestamp', None) self.fields = parsed.get('fields', {}) self.metadata = parsed.get('metadata', {}) else: #self.source = self.data_id = data_id self.message_type = message_type self.timestamp = timestamp or timestamp_method() if fields is None: self.fields = {} else: self.fields = fields if metadata is None: self.metadata = {} else: self.metadata = metadata
def index(request): """Home page - render logger states and cruise information. """ global api if api is None: api = DjangoServerAPI() ############################ # If we've gotten a POST request cruise_id = '' errors = [] if request.method == 'POST': logging.debug('POST: %s', request.POST) # First things first: log the request log_request(request, 'index') # Are they deleting a cruise?(!) if 'delete_cruise' in request.POST: logging.info('deleting cruise') api.delete_cruise() # Did we get a mode selection? elif 'select_mode' in request.POST: new_mode_name = request.POST['select_mode'] logging.info('switching to mode "%s"', new_mode_name) try: api.set_active_mode(new_mode_name) except ValueError as e: logging.warning('Error trying to set mode to "%s": %s', new_mode_name, str(e)) # Did we get a cruise definition file? Load it. If there aren't # any errors, switch to the configuration it defines. elif 'load_config' in request.POST and 'config_file' in request.FILES: config_file = request.FILES['config_file'] config_contents = config_file.read() logging.warning('Uploading file "%s"...', config_file.name) try: configuration = parse(config_contents.decode('utf-8')) api.load_configuration(configuration) except JSONDecodeError as e: errors.append('Error loading "%s": %s' % (config_file.name, str(e))) except ValueError as e: errors.append(str(e)) if errors: logging.warning('Errors! %s', errors) # If they canceled the upload elif 'cancel' in request.POST: logging.warning('User canceled upload') # Else unknown post else: logging.warning('Unknown POST request: %s', request.POST) # Assemble information to draw page template_vars = { 'websocket_server': WEBSOCKET_DATA_SERVER, 'errors': { 'django': errors }, } try: template_vars['cruise_id'] = api.get_configuration().id template_vars['loggers'] = api.get_loggers() template_vars['modes'] = api.get_modes() template_vars['active_mode'] = api.get_active_mode() template_vars['errors'] = errors except ValueError: logging.info('No configuration loaded') return render(request, 'django_gui/index.html', template_vars)
def choose_file(request, selection=None): """Render a chooser to pick and load a configuration file from the server side. Files can be navigated/selected starting at a base defined by the list in django_gui.settings.FILECHOOSER_DIRS. """ global api if api is None: api = DjangoServerAPI() ################## # Internal function to create listing from dirname def get_dir_contents(dir_name): # If at root, set empty selection, otherwise, allow to pop back up a level contents = { '..': '' if abspath(dir_name) in FILECHOOSER_DIRS else abspath(dir_name + '/..') } for filename in listdir(dir_name): path = dir_name + '/' + filename if isdir(path): filename += '/' contents[filename] = abspath(path) return contents ################## # Start of choose_file() code target_file = None # file we're going to load load_errors = [] # where we store any errors # If post, figure out what user selected if request.method == 'POST': dir_name = request.POST.get('dir_name', None) selection = [request.POST.get('select_file', '')] # Was this a request to load the target file? target_file = request.POST.get('target_file', None) if target_file: try: with open(target_file, 'r') as config_file: configuration = parse(config_file.read()) api.load_configuration(configuration) except (JSONDecodeError, ScannerError) as e: load_errors.append('Error loading "%s": %s' % (target_file, str(e))) except ValueError as e: load_errors.append(str(e)) # If no errors, go home; otherwise reset back to previous page if not load_errors: return HttpResponse('<script>window.close()</script>') else: logging.warning('Errors loading cruise definition: %s', load_errors) target_file = None # Okay, it wasn't a request to load a target file. Do we have a # selection? If no target and no selection, it means they canceled # the choice. elif selection is None or selection[0] is None: return HttpResponse('<script>window.close()</script>') # If we don't have a selection, use the complete listing from our settings. if not selection or selection == ['']: logging.debug('No selection, so setting up with: %s', FILECHOOSER_DIRS) dir_name = '' selection = FILECHOOSER_DIRS # Here, we should have a selection of *some* sort. Figure out how to # display it: if a single element and a directory, expand the # directory. If single element and a file, it's our target file. If # multiple elements, just display list of elements. if len(selection) == 1: # If it's a file, designate it as the target_file; we won't bother # with a listing. if isfile(selection[0]): target_file = selection[0] listing = [] # If it's a directory, fetch/expand its contents into the listing else: dir_name = selection[0] listing = get_dir_contents(dir_name) # If here, 'selection' is a list of files/dirs; use them as our listing else: # If selection includes one of our top dirs, use the complete # listing from our settings. if set(selection).intersection(FILECHOOSER_DIRS): dir_name = '' selection = FILECHOOSER_DIRS listing = {f.split('/')[-1]: f for f in selection} # Render the page return render( request, 'django_gui/choose_file.html', { 'target_file': target_file, 'dir_name': dir_name, 'listing': listing, 'load_errors': load_errors })
def __init__(self, config_str, log_level=None): """Create a Listener from a JSON config string.""" config = read_config.parse(config_str) logging.info('Received config string: %s', pprint.pformat(config)) super().__init__(config=config)
def test_parse_config(self): result = read_config.parse(SAMPLE_JSON) self.assertEqual(result['gyr1']['port'], '/tmp/tty_gyr1') self.assertEqual(len(result), 4)