Python horizon.messages.error() Examples
The following are 30
code examples of horizon.messages.error().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
horizon.messages
, or try the search function
.
Example #1
Source File: views.py From trove-dashboard with Apache License 2.0 | 6 votes |
def download_log(request, instance_id, filename): try: publish_value = request.GET.get('publish') if publish_value: publish = True else: publish = False data = get_contents(request, instance_id, filename, publish, FULL_LOG_VALUE) response = http.HttpResponse() response.write(data) response['Content-Disposition'] = ('attachment; ' 'filename="%s.log"' % filename) response['Content-Length'] = str(len(response.content)) return response except Exception as e: messages.error(request, _('Error downloading log file: %s') % e) return shortcuts.redirect(request.build_absolute_uri())
Example #2
Source File: views.py From avos with Apache License 2.0 | 6 votes |
def _set_external_network(self, router, ext_net_dict): gateway_info = router.external_gateway_info if gateway_info: ext_net_id = gateway_info['network_id'] if ext_net_id in ext_net_dict: gateway_info['network'] = ext_net_dict[ext_net_id] else: msg_params = {'ext_net_id': ext_net_id, 'router_id': router.id} msg = _('External network "%(ext_net_id)s" expected but not ' 'found for router "%(router_id)s".') % msg_params messages.error(self.request, msg) # gateway_info['network'] is just the network name, so putting # in a smallish error message in the table is reasonable. gateway_info['network'] = pgettext_lazy( 'External network not found', # Translators: The usage is "<UUID of ext_net> (Not Found)" u'%s (Not Found)') % ext_net_id
Example #3
Source File: forms.py From avos with Apache License 2.0 | 6 votes |
def populate_network_id_choices(self, request): search_opts = {'router:external': True} try: networks = api.neutron.network_list(request, **search_opts) except Exception as e: msg = _('Failed to get network list %s') % e LOG.info(msg) messages.error(request, msg) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) return choices = [(network.id, network.name or network.id) for network in networks] if choices: choices.insert(0, ("", _("Select network"))) else: choices.insert(0, ("", _("No networks available"))) return choices
Example #4
Source File: tabs.py From avos with Apache License 2.0 | 6 votes |
def get_context_data(self, request): stack = self.tab_group.kwargs['stack'] try: stack_identifier = '%s/%s' % (stack.stack_name, stack.id) resources = api.heat.resources_list(self.request, stack_identifier) LOG.debug('got resources %s' % resources) # The stack id is needed to generate the resource URL. for r in resources: r.stack_id = stack.id except Exception: resources = [] messages.error(request, _( 'Unable to get resources for stack "%s".') % stack.stack_name) return {"stack": stack, "table": project_tables.ResourcesTable( request, data=resources, stack=stack), }
Example #5
Source File: tables.py From avos with Apache License 2.0 | 6 votes |
def delete(self, request, obj_id): try: # detach all interfaces before attempting to delete the router search_opts = {'device_owner': 'network:router_interface', 'device_id': obj_id} ports = api.neutron.port_list(request, **search_opts) for port in ports: api.neutron.router_remove_interface(request, obj_id, port_id=port.id) api.neutron.router_delete(request, obj_id) except q_ext.NeutronClientException as e: msg = _('Unable to delete router "%s"') % e LOG.info(msg) messages.error(request, msg) redirect = reverse(self.redirect_url) raise exceptions.Http302(redirect, message=msg) except Exception: obj = self.table.get_object_by_id(obj_id) name = self.table.get_object_display(obj) msg = _('Unable to delete router "%s"') % name LOG.info(msg) exceptions.handle(request, msg)
Example #6
Source File: views.py From avos with Apache License 2.0 | 6 votes |
def download_rc_file(request): template = 'project/access_and_security/api_access/openrc.sh.template' try: context = _get_openrc_credentials(request) response = shortcuts.render(request, template, context, content_type="text/plain") response['Content-Disposition'] = ('attachment; ' 'filename="%s-openrc.sh"' % context['tenant_name']) response['Content-Length'] = str(len(response.content)) return response except Exception as e: LOG.exception("Exception in DownloadOpenRCForm.") messages.error(request, _('Error Downloading RC File: %s') % e) return shortcuts.redirect(request.build_absolute_uri())
Example #7
Source File: forms.py From avos with Apache License 2.0 | 6 votes |
def handle(self, request, data): user_is_editable = api.keystone.keystone_can_edit_user() if user_is_editable: try: api.keystone.user_update_own_password(request, data['current_password'], data['new_password']) response = http.HttpResponseRedirect(settings.LOGOUT_URL) msg = _("Password changed. Please log in again to continue.") utils.add_logout_reason(request, response, msg) return response except Exception: exceptions.handle(request, _('Unable to change password.')) return False else: messages.error(request, _('Changing password is not supported.')) return False
Example #8
Source File: tables.py From tacker-horizon with Apache License 2.0 | 6 votes |
def get_data(self, request, stack_id): try: stack = api.heat.stack_get(request, stack_id) if stack.stack_status == 'DELETE_COMPLETE': # returning 404 to the ajax call removes the # row from the table on the ui raise Http404 item = VNFManagerItemList.get_obj_given_stack_id(stack_id) item.status = stack.status item.stack_status = stack.stack_status return item except Http404: raise except Exception as e: messages.error(request, e) raise
Example #9
Source File: views.py From don with Apache License 2.0 | 6 votes |
def collect(request): macro = {'collect_status': 'Collection failed'} status = 0 BASE_DIR = settings.ROOT_PATH # CUR_DIR = os.getcwd() os.chdir(BASE_DIR + '/don/ovs') cmd = 'sudo python collector.py' for line in run_command(cmd): if line.startswith('STATUS:') and line.find('Writing collected info') != -1: status = 1 macro['collect_status'] = \ "Collecton successful. Click visualize to display" # res = collector.main() os.chdir(BASE_DIR) if status: messages.success(request, macro['collect_status']) else: messages.error(request, macro['collect_status']) resp = HttpResponse(json.dumps(macro), content_type="application/json") return resp
Example #10
Source File: views.py From don with Apache License 2.0 | 6 votes |
def analyze(request): # pwd = settings.BASE_DIR pwd = settings.ROOT_PATH JSON_FILE = pwd + '/don/ovs/don.json' params = { 'error_file': pwd + '/don/templates/don/don.error.txt', 'test:all': True, 'test:ping': False, 'test:ping_count': 1, 'test:ovs': True, 'test:report_file': pwd + '/don/templates/don/don.report.html', } print "params ====> ", params analyzer.analyze(JSON_FILE, params) # output = analyzer.analyze(JSON_FILE, params) # html = '<html><body>Output: %s</body></html>' % output # return HttpResponse(html) # return HttpResponseRedirect('/static/don.report.html') return render(request, "don/ovs/analyze.html") # return render_to_response('don/ovs/analyze.html')
Example #11
Source File: tables.py From avos with Apache License 2.0 | 5 votes |
def get_data(self, request, instance_id): instance = api.nova.server_get(request, instance_id) try: instance.full_flavor = api.nova.flavor_get(request, instance.flavor["id"]) except Exception: exceptions.handle(request, _('Unable to retrieve flavor information ' 'for instance "%s".') % instance_id, ignore=True) error = get_instance_error(instance) if error: messages.error(request, error) return instance
Example #12
Source File: tables.py From trove-dashboard with Apache License 2.0 | 5 votes |
def handle(self, table, request, obj_ids): try: username, password = api.trove.root_enable(request, obj_ids) table.data[0].enabled = True table.data[0].password = password except Exception: messages.error(request, _('There was a problem enabling root.'))
Example #13
Source File: forms.py From avos with Apache License 2.0 | 5 votes |
def _add_interface_by_subnet(self, request, data): router_id = data['router_id'] try: router_inf = api.neutron.router_add_interface( request, router_id, subnet_id=data['subnet_id']) except Exception as e: self._handle_error(request, router_id, e) try: port = api.neutron.port_get(request, router_inf['port_id']) except Exception: # Ignore an error when port_get() since it is just # to get an IP address for the interface. port = None return port
Example #14
Source File: messages.py From avos with Apache License 2.0 | 5 votes |
def test_safe_message(self): req = self.request string = mark_safe("We are now safe from ants! Go <a>here</a>!") expected = ["error", force_text(string), " safe"] self.assertTrue("async_messages" in req.horizon) self.assertItemsEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' messages.error(req, string) self.assertItemsEqual(req.horizon['async_messages'], [expected]) res = http.HttpResponse() res = middleware.HorizonMiddleware().process_response(req, res) self.assertEqual(json.dumps([expected]), res['X-Horizon-Messages'])
Example #15
Source File: messages.py From avos with Apache License 2.0 | 5 votes |
def test_middleware_header(self): req = self.request string = "Giant ants are attacking San Francisco!" expected = ["error", force_text(string), ""] self.assertTrue("async_messages" in req.horizon) self.assertItemsEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' messages.error(req, string) self.assertItemsEqual(req.horizon['async_messages'], [expected]) res = http.HttpResponse() res = middleware.HorizonMiddleware().process_response(req, res) self.assertEqual(json.dumps([expected]), res['X-Horizon-Messages'])
Example #16
Source File: exceptions.py From avos with Apache License 2.0 | 5 votes |
def handle_recoverable(request, message, redirect, ignore, escalate, handled, force_silence, force_log, log_method, log_entry, log_level): if not force_silence and not handled and (not ignore or force_log): # Default recoverable error to WARN log level log_method = getattr(LOG, log_level or "warning") log_method(error_color("Recoverable error: %s" % log_entry)) if not ignore and not handled: messages.error(request, message or log_entry) if redirect: raise Http302(redirect) if not escalate: return RecoverableError # return to normal code flow
Example #17
Source File: forms.py From avos with Apache License 2.0 | 5 votes |
def handle(self, request, data, **kwargs): try: if 'rule_to_delete' in request.POST: rulemanager.remove_rules(request, [request.POST['rule_to_delete']], router_id=data['router_id']) except Exception: exceptions.handle(request, _('Unable to delete router rule.')) try: if 'nexthops' not in data: data['nexthops'] = '' if data['source'] == '0.0.0.0/0': data['source'] = 'any' if data['destination'] == '0.0.0.0/0': data['destination'] = 'any' rule = {'action': data['action'], 'source': data['source'], 'destination': data['destination'], 'nexthops': data['nexthops'].split(',')} rulemanager.add_rule(request, router_id=data['router_id'], newrule=rule) msg = _('Router rule added') LOG.debug(msg) messages.success(request, msg) return True except Exception as e: msg = _('Failed to add router rule %s') % e LOG.info(msg) messages.error(request, msg) redirect = reverse(self.failure_url, args=[data['router_id']]) exceptions.handle(request, msg, redirect=redirect)
Example #18
Source File: forms.py From avos with Apache License 2.0 | 5 votes |
def handle(self, request, data): index = "horizon:project:containers:index" orig_container = data['orig_container_name'] orig_object = data['orig_object_name'] new_container = data['new_container_name'] new_object = data['new_object_name'] path = data['path'] if path and not path.endswith("/"): path = path + "/" new_path = "%s%s" % (path, new_object) # Now copy the object itself. try: api.swift.swift_copy_object(request, orig_container, orig_object, new_container, new_path) dest = "%s/%s" % (new_container, path) vals = {"dest": dest.rstrip("/"), "orig": orig_object.split("/")[-1], "new": new_object} messages.success(request, _('Copied "%(orig)s" to "%(dest)s" as "%(new)s".') % vals) return True except exceptions.HorizonException as exc: messages.error(request, exc) raise exceptions.Http302( reverse(index, args=[tables.wrap_delimiter(orig_container)])) except Exception: redirect = reverse(index, args=[tables.wrap_delimiter(orig_container)]) exceptions.handle(request, _("Unable to copy object."), redirect=redirect)
Example #19
Source File: tables.py From avos with Apache License 2.0 | 5 votes |
def get_data(self, request, job_execution_id): try: return saharaclient.job_execution_get(request, job_execution_id) except api_base.APIException as e: if e.error_code == 404: raise Http404 else: messages.error(request, _("Unable to update row"))
Example #20
Source File: tables.py From avos with Apache License 2.0 | 5 votes |
def get_instance_error(instance): if instance.status.lower() != 'error': return None message = instance_fault_to_friendly_message(instance) preamble = _('Failed to launch instance "%s"' ) % instance.name or instance.id message = string_concat(preamble, ': ', message) return message
Example #21
Source File: exceptions.py From avos with Apache License 2.0 | 5 votes |
def handle_unauthorized(request, message, redirect, ignore, escalate, handled, force_silence, force_log, log_method, log_entry, log_level): if ignore: return NotAuthorized if not force_silence and not handled: log_method(error_color("Unauthorized: %s" % log_entry)) if not handled: if message: message = _("Unauthorized: %s") % message # We get some pretty useless error messages back from # some clients, so let's define our own fallback. fallback = _("Unauthorized. Please try logging in again.") messages.error(request, message or fallback) # Escalation means logging the user out and raising NotAuthorized # so the middleware will redirect them appropriately. if escalate: # Prevents creation of circular import. django.contrib.auth # requires openstack_dashboard.settings to be loaded (by trying to # access settings.CACHES in in django.core.caches) while # openstack_dashboard.settings requires django.contrib.auth to be # loaded while importing openstack_auth.utils from django.contrib.auth import logout # noqa logout(request) raise NotAuthorized # Otherwise continue and present our "unauthorized" error message. return NotAuthorized
Example #22
Source File: exceptions.py From avos with Apache License 2.0 | 5 votes |
def handle_notfound(request, message, redirect, ignore, escalate, handled, force_silence, force_log, log_method, log_entry, log_level): if not force_silence and not handled and (not ignore or force_log): log_method(error_color("Not Found: %s" % log_entry)) if not ignore and not handled: messages.error(request, message or log_entry) if redirect: raise Http302(redirect) if not escalate: return NotFound # return to normal code flow
Example #23
Source File: forms.py From avos with Apache License 2.0 | 5 votes |
def handle(self, request, data): user = data.pop('id') # Throw away the password confirmation, we're done with it. data.pop('confirm_password', None) data.pop('domain_id') data.pop('domain_name') try: if "email" in data: data['email'] = data['email'] or None response = api.keystone.user_update(request, user, **data) messages.success(request, _('User has been updated successfully.')) except exceptions.Conflict: msg = _('User name "%s" is already used.') % data['name'] messages.error(request, msg) return False except Exception: response = exceptions.handle(request, ignore=True) messages.error(request, _('Unable to update the user.')) if isinstance(response, http.HttpResponse): return response else: return True
Example #24
Source File: tables.py From avos with Apache License 2.0 | 5 votes |
def delete(self, request, obj_id): domain = self.table.get_object_by_id(obj_id) if domain.enabled: msg = _('Domain "%s" must be disabled before it can be deleted.') \ % domain.name messages.error(request, msg) raise exceptions.ClientException(409, msg) else: LOG.info('Deleting domain "%s".' % obj_id) api.keystone.domain_delete(request, obj_id)
Example #25
Source File: tables.py From avos with Apache License 2.0 | 5 votes |
def single(self, table, request, obj_id): if ('domain_context' not in request.session or request.session['domain_context'] != obj_id): try: domain = api.keystone.domain_get(request, obj_id) request.session['domain_context'] = obj_id request.session['domain_context_name'] = domain.name messages.success(request, _('Domain Context updated to Domain %s.') % domain.name) except Exception: messages.error(request, _('Unable to set Domain Context.'))
Example #26
Source File: neutron.py From avos with Apache License 2.0 | 5 votes |
def _server_get_addresses(request, server, ports, floating_ips, network_names): def _format_address(mac, ip, type): try: version = netaddr.IPAddress(ip).version except Exception as e: error_message = _('Unable to parse IP address %s.') % ip LOG.error(error_message) messages.error(request, error_message) raise e return {u'OS-EXT-IPS-MAC:mac_addr': mac, u'version': version, u'addr': ip, u'OS-EXT-IPS:type': type} addresses = collections.defaultdict(list) instance_ports = ports.get(server.id, []) for port in instance_ports: network_name = network_names.get(port.network_id) if network_name is not None: for fixed_ip in port.fixed_ips: addresses[network_name].append( _format_address(port.mac_address, fixed_ip['ip_address'], u'fixed')) port_fips = floating_ips.get(port.id, []) for fip in port_fips: addresses[network_name].append( _format_address(port.mac_address, fip.floating_ip_address, u'floating')) return dict(addresses)
Example #27
Source File: base.py From avos with Apache License 2.0 | 5 votes |
def summarize(self, start, end): if not api.nova.extension_supported('SimpleTenantUsage', self.request): return if start <= end and start <= self.today: # The API can't handle timezone aware datetime, so convert back # to naive UTC just for this last step. start = timezone.make_naive(start, timezone.utc) end = timezone.make_naive(end, timezone.utc) try: self.usage_list = self.get_usage_list(start, end) except Exception: exceptions.handle(self.request, _('Unable to retrieve usage information.')) elif end < start: messages.error(self.request, _("Invalid time period. The end date should be " "more recent than the start date.")) elif start > self.today: messages.error(self.request, _("Invalid time period. You are requesting " "data from the future which may not exist.")) for project_usage in self.usage_list: project_summary = project_usage.get_summary() for key, value in project_summary.items(): self.summary.setdefault(key, 0) self.summary[key] += value
Example #28
Source File: exceptions.py From avos with Apache License 2.0 | 5 votes |
def check_message(keywords, message): """Checks an exception for given keywords and raises a new ``ActionError`` with the desired message if the keywords are found. This allows selective control over API error messages. """ exc_type, exc_value, exc_traceback = sys.exc_info() if set(str(exc_value).split(" ")).issuperset(set(keywords)): exc_value._safe_message = message raise
Example #29
Source File: tables.py From avos with Apache License 2.0 | 5 votes |
def get_data(self, request, stack_id): try: stack = api.heat.stack_get(request, stack_id) if stack.stack_status == 'DELETE_COMPLETE': # returning 404 to the ajax call removes the # row from the table on the ui raise Http404 return stack except Http404: raise except Exception as e: messages.error(request, e) raise
Example #30
Source File: tables.py From trove-dashboard with Apache License 2.0 | 5 votes |
def handle(self, table, request, obj_ids): datum_display_objs = [] for datum_id in obj_ids: datum = table.get_object_by_id(datum_id) datum_display = table.get_object_display(datum) or datum_id datum_display_objs.append(datum_display) display_str = functions.lazy_join(", ", datum_display_objs) try: cluster_id = table.kwargs['cluster_id'] data = [{'id': instance_id} for instance_id in obj_ids] api.trove.cluster_shrink(request, cluster_id, data) LOG.info('%s: "%s"' % (self._get_action_name(past=True), display_str)) msg = _('Removed instances from cluster.') messages.info(request, msg) except Exception as ex: LOG.error('Action %(action)s failed with %(ex)s for %(data)s' % {'action': self._get_action_name(past=True).lower(), 'ex': ex, 'data': display_str}) msg = _('Unable to remove instances from cluster: %s') messages.error(request, msg % ex) return shortcuts.redirect(self.get_success_url(request))