当前位置: 首页>>代码示例>>Python>>正文


Python common.set_error_message函数代码示例

本文整理汇总了Python中tvb.interfaces.web.controllers.common.set_error_message函数的典型用法代码示例。如果您正苦于以下问题:Python set_error_message函数的具体用法?Python set_error_message怎么用?Python set_error_message使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了set_error_message函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_new

 def create_new(self, cancel=False, **data):
     """
     Create new user with data submitted from UI.
     """
     if cancel:
         raise cherrypy.HTTPRedirect('/user/usermanagement')
     template_specification = dict(mainContent="create_new", title="Create New", data=data)
     redirect = False
     if cherrypy.request.method == 'POST':
         try:
             data[KEY_COMMENT] = "Created by administrator."
             # User is created by administrator, should be validated automatically, and credentials
             # should be sent to user by email.
             email_msg = """A TVB account was just created for you by an administrator. 
             \n Your credentials are username=%s, password=%s. 
             \n You can log in here: %s.
             """ % (data[KEY_USERNAME], data[KEY_PASSWORD], TvbProfile.current.web.BASE_URL)
             self._create_user(email_msg=email_msg, validated=True, **data)
             common.set_info_message("New user created successfully.")
             redirect = True
         except formencode.Invalid as excep:
             template_specification[common.KEY_ERRORS] = excep.unpack_errors()
         except Exception as excep:
             self.logger.exception(excep)
             common.set_error_message("We are very sorry, but we could not create your user. Most probably is "
                                      "because it was impossible to sent emails. Please try again later...")
     if redirect:
         raise cherrypy.HTTPRedirect('/user/usermanagement')
     else:
         return self.fill_default_attributes(template_specification)
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:30,代码来源:users_controller.py

示例2: load_burst_from_json

    def load_burst_from_json(self, **data):
        """Upload Burst from previously exported JSON file"""
        self.logger.debug("Uploading ..." + str(data))

        try:
            upload_param = "uploadedfile"
            if upload_param in data and data[upload_param]:

                upload_param = data[upload_param]
                if isinstance(upload_param, FieldStorage) or isinstance(upload_param, Part):
                    if not upload_param.file:
                        raise BurstServiceException("Please select a valid JSON file.")
                    upload_param = upload_param.file.read()

                upload_param = json.loads(upload_param)
                prj_id = common.get_current_project().id
                importer = ImportService()
                burst_entity = importer.load_burst_entity(upload_param, prj_id)
                common.add2session(common.KEY_BURST_CONFIG, burst_entity)

        except Exception as excep:
            self.logger.warning(excep.message)
            common.set_error_message(excep.message)

        raise cherrypy.HTTPRedirect('/burst/')
开发者ID:maedoc,项目名称:tvb-framework,代码行数:25,代码来源:burst_controller.py

示例3: profile

    def profile(self, logout=False, save=False, **data):
        """
        Display current user's profile page.
        On POST: logout, or save password/email.
        """
        if cherrypy.request.method == "POST" and logout:
            raise cherrypy.HTTPRedirect("/user/logout")
        template_specification = dict(mainContent="profile", title="User Profile")
        user = common.get_logged_user()

        if cherrypy.request.method == "POST" and save:
            try:
                form = EditUserForm()
                data = form.to_python(data)
                if data.get(KEY_PASSWORD):
                    user.password = md5(data[KEY_PASSWORD]).hexdigest()
                if data.get(KEY_EMAIL):
                    user.email = data[KEY_EMAIL]
                old_password = None
                if data.get("old_password"):
                    old_password = md5(data["old_password"]).hexdigest()
                self.user_service.edit_user(user, old_password)
                if old_password:
                    common.set_info_message("Changes Submitted!")
                else:
                    common.set_info_message("Submitted!  No password changed.")
            except formencode.Invalid, excep:
                template_specification[common.KEY_ERRORS] = excep.unpack_errors()
            except UsernameException, excep:
                self.logger.exception(excep)
                user = common.get_logged_user()
                common.add2session(common.KEY_USER, self.user_service.get_user_by_id(user.id))
                common.set_error_message("Could not save changes. Probably wrong old password!!")
开发者ID:sdiazpier,项目名称:tvb-framework,代码行数:33,代码来源:users_controller.py

示例4: recoverpassword

 def recoverpassword(self, cancel=False, **data):
     """
     This form should reset a password for a given userName/email and send a 
     notification message to that email.
     """
     template_specification = dict(mainContent="recover_password", title="Recover password", data=data)
     redirect = False
     if cherrypy.request.method == 'POST':
         if cancel:
             raise cherrypy.HTTPRedirect('/user')
         form = RecoveryForm()
         try:
             data = form.to_python(data)
             okmessage = self.user_service.reset_password(**data)
             common.set_info_message(okmessage)
             redirect = True
         except formencode.Invalid as excep:
             template_specification[common.KEY_ERRORS] = excep.unpack_errors()
             redirect = False
         except UsernameException as excep1:
             self.logger.exception("Could not reset password!")
             common.set_error_message(excep1.message)
             redirect = False
     if redirect:
         #Redirect to login page, with some success message to display
         raise cherrypy.HTTPRedirect('/user')
     else:
         #Stay on the same page
         return self.fill_default_attributes(template_specification)
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:29,代码来源:users_controller.py

示例5: index

    def index(self):
        current_user_id = common.get_logged_user().id
        # In case the number of dynamics gets big we should add a filter in the ui.
        dynamics = dao.get_dynamics_for_user(current_user_id)

        if not dynamics:
            return self.no_dynamics_page()

        burst_config = common.get_from_session(common.KEY_BURST_CONFIG)
        des = SerializationManager(burst_config)

        connectivity = des.get_connectivity()

        if connectivity is None:
            msg = 'You have to select a connectivity before setting up the region Model. '
            common.set_error_message(msg)
            raise ValueError(msg)

        params = ConnectivityViewer.get_connectivity_parameters(connectivity)

        params.update({
            'title': 'Model parameters',
            'mainContent': 'burst/model_param_region',
            'isSingleMode': True,
            'submit_parameters_url': '/burst/modelparameters/regions/submit_model_parameters',
            'dynamics': dynamics,
            'dynamics_json': self._dynamics_json(dynamics),
            'initial_dynamic_ids': json.dumps(burst_config.dynamic_ids)
        })

        return self.fill_default_attributes(params, 'regionmodel')
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:31,代码来源:region_model_parameters_controller.py

示例6: settings

 def settings(self, save_settings=False, **data):
     """Main settings page submit and get"""
     template_specification = dict(mainContent="../settings/system_settings", title="System Settings")
     if save_settings:
         try:
             form = SettingsForm()
             data = form.to_python(data)
             isrestart, isreset = self.settingsservice.save_settings(**data)
             if isrestart:
                 thread = threading.Thread(target=self._restart_services, kwargs={'should_reset': isreset})
                 thread.start()
                 common.add2session(common.KEY_IS_RESTART, True)
                 common.set_important_message('Please wait until TVB is restarted properly!')
                 raise cherrypy.HTTPRedirect('/tvb')
             # Here we will leave the same settings page to be displayed.
             # It will continue reloading when CherryPy restarts.
         except formencode.Invalid as excep:
             template_specification[common.KEY_ERRORS] = excep.unpack_errors()
         except InvalidSettingsException as excep:
             self.logger.error('Invalid settings!  Exception %s was raised' % (str(excep)))
             common.set_error_message(excep.message)
     template_specification.update({'keys_order': self.settingsservice.KEYS_DISPLAY_ORDER,
                                    'config_data': self.settingsservice.configurable_keys,
                                    common.KEY_FIRST_RUN: TvbProfile.is_first_run()})
     return self.fill_default_attributes(template_specification)
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:25,代码来源:settings_controller.py

示例7: register

    def register(self, cancel=False, **data):
        """
        This register form send an e-mail to the user and to the site admin.
        """
        template_specification = dict(mainContent="register", title="Register", data=data)
        redirect = False
        if cherrypy.request.method == 'POST':
            if cancel:
                raise cherrypy.HTTPRedirect('/user')
            try:
                okmessage = self._create_user(**data)
                common.set_info_message(okmessage)
                redirect = True
            except formencode.Invalid as excep:
                template_specification[common.KEY_ERRORS] = excep.unpack_errors()
                redirect = False
            except Exception as excep1:
                self.logger.error("Could not create user:" + data["username"])
                self.logger.exception(excep1)
                common.set_error_message("We are very sorry, but we could not create your user. Most probably is "
                                         "because it was impossible to sent emails. Please try again later...")
                redirect = False

        if redirect:
            #Redirect to login page, with some success message to display
            raise cherrypy.HTTPRedirect('/user')
        else:
            #Stay on the same page
            return self.fill_default_attributes(template_specification)
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:29,代码来源:users_controller.py

示例8: deco

        def deco(*a, **b):
            try:

                return func(*a, **b)

            except common.NotAllowed as ex:
                log = get_logger(_LOGGER_NAME)
                log.error(str(ex))

                if redirect:
                    common.set_error_message(str(ex))
                    raise cherrypy.HTTPRedirect(ex.redirect_url)
                else:
                    raise cherrypy.HTTPError(ex.status, str(ex))

            except cherrypy.HTTPRedirect as ex:
                if redirect:
                    raise
                else:
                    log = get_logger(_LOGGER_NAME)
                    log.warn('Redirect converted to error: ' + str(ex))
                    # should we do this? Are browsers following redirects in ajax?
                    raise cherrypy.HTTPError(500, str(ex))

            except Exception:
                log = get_logger(_LOGGER_NAME)
                log.exception('An unexpected exception appeared')

                if redirect:
                    # set a default error message if one has not been set already
                    if not common.has_error_message():
                        common.set_error_message("An unexpected exception appeared. Please check the log files.")
                    raise cherrypy.HTTPRedirect("/tvb?error=True")
                else:
                    raise
开发者ID:amitsaroj001,项目名称:tvb-framework,代码行数:35,代码来源:decorators.py

示例9: execute_post

    def execute_post(self, project_id, submit_url, step_key, algorithm, **data):
        """ Execute HTTP POST on a generic step."""
        errors = None
        adapter_instance = ABCAdapter.build_adapter(algorithm)

        try:
            result = self.flow_service.fire_operation(adapter_instance, common.get_logged_user(), project_id, **data)

            # Store input data in session, for informing user of it.
            step = self.flow_service.get_category_by_id(step_key)
            if not step.rawinput:
                self.context.add_adapter_to_session(None, None, copy.deepcopy(data))

            if isinstance(adapter_instance, ABCDisplayer):
                if isinstance(result, dict):
                    result[common.KEY_OPERATION_ID] = adapter_instance.operation_id
                    return result
                else:
                    common.set_error_message("Invalid result returned from Displayer! Dictionary is expected!")
            else:
                if isinstance(result, list):
                    result = "Launched %s operations." % len(result)
                common.set_important_message(str(result))
        except formencode.Invalid, excep:
            errors = excep.unpack_errors()
开发者ID:transpersonify,项目名称:tvb-framework,代码行数:25,代码来源:flow_controller.py

示例10: index

    def index(self, **data):
        """
        Login page (with or without messages).
        """
        template_specification = dict(mainContent="login", title="Login", data=data)
        if cherrypy.request.method == 'POST':
            form = LoginForm()
            try:
                data = form.to_python(data)
                username = data[KEY_USERNAME]
                password = data[KEY_PASSWORD]
                user = self.user_service.check_login(username, password)
                if user is not None:
                    common.add2session(common.KEY_USER, user)
                    common.set_info_message('Welcome ' + username)
                    self.logger.debug("User " + username + " has just logged in!")
                    if user.selected_project is not None:
                        prj = user.selected_project
                        prj = ProjectService().find_project(prj)
                        self._mark_selected(prj)
                    raise cherrypy.HTTPRedirect('/user/profile')
                else:
                    common.set_error_message('Wrong username/password, or user not yet validated...')
                    self.logger.debug("Wrong username " + username + " !!!")
            except formencode.Invalid as excep:
                template_specification[common.KEY_ERRORS] = excep.unpack_errors()

        return self.fill_default_attributes(template_specification)
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:28,代码来源:users_controller.py

示例11: getfiltereddatatypes

    def getfiltereddatatypes(self, name, parent_div, tree_session_key, filters):
        """
        Given the name from the input tree, the dataType required and a number of
        filters, return the available dataType that satisfy the conditions imposed.
        """
        previous_tree = self.context.get_session_tree_for_key(tree_session_key)
        if previous_tree is None:
            common.set_error_message("Adapter Interface not in session for filtering!")
            raise cherrypy.HTTPRedirect("/tvb?error=True")
        current_node = self._get_node(previous_tree, name)
        if current_node is None:
            raise Exception("Could not find node :" + name)
        datatype = current_node[ABCAdapter.KEY_DATATYPE]

        filters = json.loads(filters)
        availablefilter = json.loads(FilterChain.get_filters_for_type(datatype))
        for i, filter_ in enumerate(filters[FILTER_FIELDS]):
            #Check for filter input of type 'date' as these need to be converted
            if filter_ in availablefilter and availablefilter[filter_][FILTER_TYPE] == 'date':
                try:
                    temp_date = string2date(filters[FILTER_VALUES][i], False)
                    filters[FILTER_VALUES][i] = temp_date
                except ValueError:
                    raise
        #In order for the filter object not to "stack up" on multiple calls to
        #this method, create a deepCopy to work with
        if ABCAdapter.KEY_CONDITION in current_node:
            new_filter = copy.deepcopy(current_node[ABCAdapter.KEY_CONDITION])
        else:
            new_filter = FilterChain()
        new_filter.fields.extend(filters[FILTER_FIELDS])
        new_filter.operations.extend(filters[FILTER_OPERATIONS])
        new_filter.values.extend(filters[FILTER_VALUES])
        #Get dataTypes that match the filters from DB then populate with values
        values, total_count = InputTreeManager().populate_option_values_for_dtype(
                                    common.get_current_project().id,
                                    datatype, new_filter,
                                    self.context.get_current_step() )
        #Create a dictionary that matches what the template expects
        parameters = {ABCAdapter.KEY_NAME: name,
                      ABCAdapter.KEY_FILTERABLE: availablefilter,
                      ABCAdapter.KEY_TYPE: ABCAdapter.TYPE_SELECT,
                      ABCAdapter.KEY_OPTIONS: values,
                      ABCAdapter.KEY_DATATYPE: datatype}

        if total_count > MAXIMUM_DATA_TYPES_DISPLAYED:
            parameters[KEY_WARNING] = WARNING_OVERFLOW

        if ABCAdapter.KEY_REQUIRED in current_node:
            parameters[ABCAdapter.KEY_REQUIRED] = current_node[ABCAdapter.KEY_REQUIRED]
            if len(values) > 0 and string2bool(str(parameters[ABCAdapter.KEY_REQUIRED])):
                parameters[ABCAdapter.KEY_DEFAULT] = str(values[-1][ABCAdapter.KEY_VALUE])
        previous_selected = self.context.get_current_default(name)
        if previous_selected in [str(vv['value']) for vv in values]:
            parameters[ABCAdapter.KEY_DEFAULT] = previous_selected

        template_specification = {"inputRow": parameters, "disabled": False,
                                  "parentDivId": parent_div, common.KEY_SESSION_TREE: tree_session_key}
        return self.fill_default_attributes(template_specification)
开发者ID:transpersonify,项目名称:tvb-framework,代码行数:59,代码来源:flow_controller.py

示例12: _remove_project

 def _remove_project(self, project_id):
     """Private method for removing project."""
     try:
         self.project_service.remove_project(project_id)
     except ServicesBaseException, exc:
         self.logger.error("Could not delete project!")
         self.logger.exception(exc)
         common.set_error_message(exc.message)
开发者ID:unimauro,项目名称:tvb-framework,代码行数:8,代码来源:project_controller.py

示例13: projectupload

 def projectupload(self, **data):
     """Upload Project from TVB ZIP."""
     self.logger.debug("Uploading ..." + str(data))
     try:
         upload_param = "uploadedfile"
         if upload_param in data and data[upload_param]:
             import_service = ImportService()
             import_service.import_project_structure(data[upload_param], common.get_logged_user().id)
     except ServicesBaseException, excep:
         self.logger.warning(excep.message)
         common.set_error_message(excep.message)
开发者ID:unimauro,项目名称:tvb-framework,代码行数:11,代码来源:project_controller.py

示例14: updatemetadata

    def updatemetadata(self, **data):
        """ Submit MetaData edited for DataType(Group) or Operation(Group). """
        try:

            self.project_service.update_metadata(data)

        except ServicesBaseException, excep:
            self.logger.error("Could not execute MetaData update!")
            self.logger.exception(excep)
            common.set_error_message(excep.message)
            return excep.message
开发者ID:unimauro,项目名称:tvb-framework,代码行数:11,代码来源:project_controller.py

示例15: validate

 def validate(self, name):
     """
     A link to this page will be sent to the administrator to validate 
     the registration of each user.
     """
     success = self.user_service.validate_user(name)
     if not success:
         common.set_error_message("Problem validating user:" + name + "!! Please check logs.")
         self.logger.error("Problem validating user " + name)
     else:
         common.set_info_message("User Validated successfully and notification email sent!")
     raise cherrypy.HTTPRedirect('/tvb')
开发者ID:LauHoiYanGladys,项目名称:tvb-framework,代码行数:12,代码来源:users_controller.py


注:本文中的tvb.interfaces.web.controllers.common.set_error_message函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。