Exemplo n.º 1
0
def show(section='', options='', config=None, deep=False):
    section, options = get_config_str(section, options, config)
    try:
        if section != '' and options == '':
            if config.has_section(section):
                print('''[{0}]'''.format(section))
                for option in config[section]:
                    print('\t{0}={1}'.format(option, config[section][option]))
            else:
                print('{0}属性未找到'.format(section))
        elif section != '' and options != '':
            if config.has_option(section, options):
                print('{0}={1}'.format(options, config[section][options]))
            else:
                print('[{0}][{1}]属性未找到'.format(section, options))
        elif section != '' and options != '' and (
                not config.has_section(section)
                or not config.has_option(section, option)):
            print('属性不存在。')
        elif deep:
            for line in config:
                print('[{0}]'.format(line))
                if deep and type(config) is configparser.ConfigParser:
                    for row in config[line]:
                        print('\t{0}={1}'.format(row, config[line][row]))
        else:
            print('超出预期')
    except configparser.InterpolationSyntaxError as e:
        print(e)
        print('特殊字符,请使用configparser.RawConfigParser,暂时不处理')
Exemplo n.º 2
0
def check_params():
    if not config.has_section('database'):
        service_logger.error("Not found 'database' section in config file.")
    else:
        if not config.has_option('database', 'database_path'):
            service_logger.error("Not found 'database_path' in database section.")

    if not config.has_section('server'):
        service_logger.error("Not found 'database' section in config file.")
    else:
        if not config.has_option('server', 'listen_host') or not config.has_option('server', 'listen_port'):
            service_logger.error("Not found 'listen_host' or 'listen_port' in server section.")
Exemplo n.º 3
0
def get_config_str(section='', options='', config=None):
    if section != '':
        try:
            size_s = int(section)
        except ValueError as e:
            section = section
        else:
            if config != None and size_s >= 0 and size_s < len(config):
                section = config.sections()[size_s]
            else:
                section = section
    else:
        raise ValueError('错误使用')
    if options != '':
        try:
            size_o = int(options)
        except ValueError as e:
            options = options
        else:
            if config.has_section(section) and size_o >= 0 and size_o < len(
                    config[section]):
                options = config.options(section)[size_o]
            else:
                options = options
    return [section, options]
Exemplo n.º 4
0
 def migrateOldConfig(self): #Legacy support code
   import ConfigParser, ast
   config = ConfigParser.ConfigParser()
   if os.path.exists(self.getOldConfigFile()):
     with codecs.open(self.getOldConfigFile(), "r", "utf8") as fp:
       config.readfp(fp)
   if not config.has_section("__SYSTEM__"):
     config.add_section("__SYSTEM__")
   self.settings = dict(config.items("__SYSTEM__"))
   for name in config.sections():
     if name != "__SYSTEM__":
       dat = dict(config.items(name))
       if dat["program"] and dat["program"].startswith("["):
         args = ast.literal_eval(dat["program"])
       else:
         args = shlex.split(str(dat["program"]))
       dat["program"] = args[0]
       if "\\\\" in dat["program"]:
         dat["program"] = ast.literal_eval('"'+dat["program"]+'"')
       dat["arguments"] = args[1:]
       self.shortcutData[name] = dat
Exemplo n.º 5
0
def add_username_to_config_ini(username):
    config = SafeConfigParser()
    config.read('config.ini')

    if not config.has_section('main'):
        config.add_section('main')
        config.set('main', 'users', username)
    else:
        users = config.get('main', 'users')

        user_already_in_config = False
        for user in users.split(','):
            if user == username:
                user_already_in_config = True
                break

        if user_already_in_config is False:
            config.set('main', 'users', users + ',' + username)

    with open('config.ini', 'w') as f:
        config.write(f)
Exemplo n.º 6
0
def checkRequired(parsed):
	log.log(log.DEBUG, 'Checking required fields')
	if not 'doc-tag' in parsed:
		log.log(log.ERROR, 'No tag specified')
		return (1, 'No tag specified')
	tag = parsed['doc-tag'][0].split('-', 1)
	event_type = tag[0]

	if config.has_section('fields-' + event_type):
		items = config.items('fields-' + event_type)
		for i in items:
			if i[0] == 'required':
				required_fields = i[1].split(', ')
				for field in required_fields:
					if not field in parsed:
						log.log(log.ERROR, 'Required field "' + field + '" is missing')
						return (1, 'Required field "' + field + '" is missing')
			elif i[0] == 'optional':
				return (0, '')
				#optional_fields = i[1].split(', ')
				#for field in optional_fields:
				#	if field in parsed:
				#		pass
			else:
				log.log(log.ERROR, 'Unknown definition in config: ' + repr(i))
				return (1, 'Unknown definition in config: ' + repr(i))
	else:
		log.log(log.ERROR, 'Event type not specified in config file. Adding section. All fields will be added as optional. Fix this soon.')
		config.add_section('fields-' + event_type)
		oldkey = ''
		for key in parsed:
			if oldkey == '':
				newkey = key
			else:
				newkey = oldkey + ', ' + key
			config.set('fields-' + event_type, 'optional', newkey)
			oldkey = config.get('fields-' + event_type, 'optional')
		config.write()
		return (0, '')
Exemplo n.º 7
0
  couch_config = config.items(couch_engine)

  man.set_database(
    twentyc.database.ClientFromConfig(
      couch_engine, couch_config, "modules"
    )
  )

  if config.has_option("xbahn", "username") and config.has_option("xbahn", "password"):
    xbahn_user = config.get("xbahn", "username")
    xbahn_pass = config.get("xbahn", "password")
  else:
    xbahn_user = None
    xbahn_pass = None

  if config.has_section("xbahn") and config.get("xbahn", "host"):
    xb = xbahn.xBahn(
      config.get("xbahn", "host"),
      int(config.get("xbahn", "port")),
      config.get("xbahn", "exchange"),
      None,
      None,
      username = xbahn_user,
      password = xbahn_pass
    )
    man.xbahn = xb
  
  users = []
  user_id = 0

  if options.user_id:
Exemplo n.º 8
0
    def profile_window(self):
        self.eventTypes = ["keypress", "mouse", "brightness"]
        self.mouseEvents = [
            "click", "move-left", "move-right", "move-up", "move-down"
        ]

        if (self.appStatus != 0):
            self.stop()
        self.profileWindow = Toplevel(self.window)
        self.profileWindow.geometry('+100+100')
        self.profileWindow.resizable(False, False)
        profileSettingsFrame = Frame(self.profileWindow)
        profileSettingsFrame.pack(fill=X, side=BOTTOM)

        self.profileNotebook = ttk.Notebook(profileSettingsFrame)
        self.profileNotebook.pack(pady=15)

        self.profileExerciseFrame = Frame(self.profileNotebook,
                                          width=500,
                                          height=1000)
        self.profileExtremityFrame = Frame(self.profileNotebook,
                                           width=500,
                                           height=1000)

        self.profileExerciseFrame.pack(fill="both", expand=1)
        self.profileExtremityFrame.pack(fill="both", expand=1)

        self.defaultProfiles = []
        self.customizedProfiles = []
        self.extremityProfiles = []
        config = ConfigParser()
        config.read('config.ini')
        currentInputs = ConfigParser()
        currentInputs.read('current_inputs.ini')
        defaultExercisesDict = dict(config.items('default'))
        currentDefaultInputsDict = dict(currentInputs.items('default'))
        customizedExerciseDict = dict(config.items('customized'))
        currentCustomizedInputsDict = dict(currentInputs.items('customized'))
        extremityTriggersDict = dict(config.items('extremity'))
        extremityTriggerInputsDict = dict(currentInputs.items('extremity'))

        rowCount = 0
        defaultLabel = Label(self.profileExerciseFrame,
                             text="DEFAULT",
                             font=('Helvetica', 18, 'bold'))
        defaultLabel.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5)
        rowCount += 1
        for key in defaultExercisesDict:
            checkBoxVar = IntVar()
            if (int(currentDefaultInputsDict.get(key))) == 1:
                checkBoxVar.set(1)
            else:
                checkBoxVar.set(0)
            checkBox = Checkbutton(self.profileExerciseFrame,
                                   text=key,
                                   variable=checkBoxVar)
            checkBox.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5)
            if ('+' in defaultExercisesDict.get(key)):
                eventType = defaultExercisesDict.get(key).split('+')[0]
                eventContent = defaultExercisesDict.get(key).split('+')[1]
            else:
                eventType = defaultExercisesDict.get(key)
                eventContent = None

            eventTypeOption = StringVar()
            eventTypeOption.set(eventType)
            eventTypeOption.trace(
                "w",
                lambda *args, row=rowCount, eventTypeOptionInstance=
                eventTypeOption: self.default_event_type_changed(
                    eventTypeOptionInstance, row, *args))

            eventTypeOptionMenu = OptionMenu(self.profileExerciseFrame,
                                             eventTypeOption, *self.eventTypes)
            eventTypeOptionMenu.config(width=18)
            eventTypeOptionMenu.grid(row=rowCount, column=1, pady=5, padx=0)

            if eventType == "keypress":
                keyLabel = Label(self.profileExerciseFrame,
                                 text=eventContent,
                                 background='light grey')
                keyLabel.grid(sticky="W",
                              row=rowCount,
                              column=2,
                              pady=5,
                              padx=5)
                keyLabel.bind("<Button-1>", self.key_map)
                self.defaultProfiles.append(
                    (checkBoxVar, checkBox, eventTypeOption, keyLabel))

            elif eventType == "mouse":
                mouseEventOption = StringVar()
                mouseEventOption.set(eventContent)
                mouseEventTypeOptionMenu = OptionMenu(
                    self.profileExerciseFrame, mouseEventOption,
                    *self.mouseEvents)
                mouseEventTypeOptionMenu.config(width=18)
                mouseEventTypeOptionMenu.grid(row=rowCount,
                                              column=2,
                                              pady=5,
                                              padx=0)
                self.defaultProfiles.append(
                    (checkBoxVar, checkBox, eventTypeOption, mouseEventOption))
            elif eventType == "brightness":
                self.defaultProfiles.append(
                    (checkBoxVar, checkBox, eventTypeOption))
            rowCount += 1

        customizedLabel = Label(self.profileExerciseFrame,
                                text="CUSTOMIZED",
                                font=('Helvetica', 18, 'bold'))
        customizedLabel.grid(sticky="W",
                             row=rowCount,
                             column=0,
                             pady=5,
                             padx=5)
        rowCount += 1

        for key in customizedExerciseDict:
            checkBoxVar = IntVar()
            if (int(currentCustomizedInputsDict.get(key))) == 1:
                checkBoxVar.set(1)
            else:
                checkBoxVar.set(0)
            checkBox = Checkbutton(self.profileExerciseFrame,
                                   text=key,
                                   variable=checkBoxVar)
            checkBox.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5)

            if ('+' in customizedExerciseDict.get(key)):
                eventType = customizedExerciseDict.get(key).split('+')[0]
                eventContent = customizedExerciseDict.get(key).split('+')[1]
            else:
                eventType = customizedExerciseDict.get(key)
                eventContent = ''

            eventTypeOption = StringVar()
            eventTypeOption.set(eventType)
            eventTypeOption.trace(
                "w",
                lambda *args, row=rowCount, eventTypeOptionInstance=
                eventTypeOption: self.customized_event_type_changed(
                    eventTypeOptionInstance, row, *args))

            eventTypeOptionMenu = OptionMenu(self.profileExerciseFrame,
                                             eventTypeOption, *self.eventTypes)
            eventTypeOptionMenu.config(width=18)
            eventTypeOptionMenu.grid(row=rowCount, column=1, pady=5, padx=0)

            if eventType == "keypress":
                keyLabel = Label(self.profileExerciseFrame,
                                 text=eventContent,
                                 background='light grey')
                keyLabel.grid(sticky="W",
                              row=rowCount,
                              column=2,
                              pady=5,
                              padx=5)
                keyLabel.bind("<Button-1>", self.key_map)
                self.customizedProfiles.append(
                    (checkBoxVar, checkBox, eventTypeOption, keyLabel))

            elif eventType == "mouse":
                mouseEventOption = StringVar()
                mouseEventOption.set(eventContent)
                mouseEventTypeOptionMenu = OptionMenu(
                    self.profileExerciseFrame, mouseEventOption,
                    *self.mouseEvents)
                mouseEventTypeOptionMenu.config(width=18)
                mouseEventTypeOptionMenu.grid(row=rowCount,
                                              column=2,
                                              pady=5,
                                              padx=0)
                self.customizedProfiles.append(
                    (checkBoxVar, checkBox, eventTypeOption, mouseEventOption))

            elif eventType == "brightness":
                self.customizedProfiles.append(
                    (checkBoxVar, checkBox, eventTypeOption))
            rowCount += 1

        addNewCustomizedButton = Button(
            self.profileExerciseFrame,
            text="Add a new customized exercise",
            command=self.add_customized_motion_window)
        addNewCustomizedButton.grid(sticky="W",
                                    row=rowCount,
                                    column=0,
                                    pady=5,
                                    padx=5)
        rowCount += 1
        removeCustomizedButton = Button(
            self.profileExerciseFrame,
            text="Delete existed customized exercise",
            command=self.remove_customized_motion_window)
        removeCustomizedButton.grid(sticky="W",
                                    row=rowCount,
                                    column=0,
                                    pady=5,
                                    padx=5)
        rowCount += 1

        initialConfigtLabel1 = Label(self.profileExerciseFrame,
                                     text="INITIAL CONFIGURATION",
                                     font=('Helvetica', 18, 'bold'))
        initialConfigtLabel1.grid(sticky="W",
                                  row=rowCount,
                                  column=0,
                                  pady=5,
                                  padx=5)
        rowCount += 1

        initialConfigtLabel2 = Label(
            self.profileExerciseFrame,
            text="Initial configuration is necessary if this is your "
            "first time using the Exercise Module",
            wraplengt=400,
            justify=LEFT,
            font=('Helvetica', 10))
        initialConfigtLabel2.grid(sticky="W",
                                  row=rowCount,
                                  column=0,
                                  pady=5,
                                  padx=5)
        rowCount += 1

        if not config.has_section('roi'):
            initialConfigtLabel3 = Label(self.profileExerciseFrame,
                                         text='Initial Config not completed',
                                         fg='red',
                                         justify=LEFT,
                                         font=('Helvetica', 10))
        else:
            initialConfigtLabel3 = Label(self.profileExerciseFrame,
                                         text='Initial Config completed',
                                         fg='green',
                                         justify=LEFT,
                                         font=('Helvetica', 10))
        initialConfigtLabel3.grid(sticky="W",
                                  row=rowCount,
                                  column=0,
                                  pady=5,
                                  padx=5)
        rowCount += 1

        initialConfigButton = Button(self.profileExerciseFrame,
                                     text="Initial Configuration",
                                     command=self.initial_config_window)
        initialConfigButton.grid(sticky="W",
                                 row=rowCount,
                                 column=0,
                                 pady=5,
                                 padx=5)

        rowCount = 0
        extremityLabel = Label(self.profileExtremityFrame,
                               text="DEFAULT",
                               font=('Helvetica', 18, 'bold'))
        extremityLabel.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5)
        rowCount += 1
        for key in extremityTriggersDict:
            checkBoxVar = IntVar()
            if (int(extremityTriggerInputsDict.get(key))) == 1:
                checkBoxVar.set(1)
            else:
                checkBoxVar.set(0)
            checkBox = Checkbutton(self.profileExtremityFrame,
                                   text=key,
                                   variable=checkBoxVar)
            checkBox.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5)

            if (len(extremityTriggersDict.get(key).split('+')) == 3):
                pos = extremityTriggersDict.get(key).split('+')[0]
                eventType = extremityTriggersDict.get(key).split('+')[1]
                eventContent = extremityTriggersDict.get(key).split('+')[2]
            else:
                pos = extremityTriggersDict.get(key).split('+')[0]
                eventType = extremityTriggersDict.get(key).split('+')[1]
                eventContent = ''

            posLabel = Label(self.profileExtremityFrame,
                             text=pos,
                             background='light grey')
            posLabel.grid(sticky="W", row=rowCount, column=1, pady=5, padx=5)
            posLabel.bind("<Button-1>", self.change_trigger_pos_window)

            eventTypeOption = StringVar()
            eventTypeOption.set(eventType)
            eventTypeOption.trace(
                "w",
                lambda *args, row=rowCount, eventTypeOptionInstance=
                eventTypeOption: self.extremity_event_type_changed(
                    eventTypeOptionInstance, row, *args))

            eventTypeOptionMenu = OptionMenu(self.profileExtremityFrame,
                                             eventTypeOption, *self.eventTypes)
            eventTypeOptionMenu.config(width=18)
            eventTypeOptionMenu.grid(row=rowCount, column=2, pady=5, padx=0)

            if eventType == "keypress":
                keyLabel = Label(self.profileExtremityFrame,
                                 text=eventContent,
                                 background='light grey')
                keyLabel.grid(sticky="W",
                              row=rowCount,
                              column=3,
                              pady=5,
                              padx=5)
                keyLabel.bind("<Button-1>", self.key_map)
                self.extremityProfiles.append((checkBoxVar, checkBox, posLabel,
                                               eventTypeOption, keyLabel))
            elif eventType == "mouse":
                mouseEventOption = StringVar()
                mouseEventOption.set(eventContent)
                mouseEventTypeOptionMenu = OptionMenu(
                    self.profileExtremityFrame, mouseEventOption,
                    *self.mouseEvents)
                mouseEventTypeOptionMenu.config(width=18)
                mouseEventTypeOptionMenu.grid(row=rowCount,
                                              column=3,
                                              pady=5,
                                              padx=0)
                self.extremityProfiles.append(
                    (checkBoxVar, checkBox, posLabel, eventTypeOption,
                     mouseEventOption))
            elif eventType == "brightness":
                self.extremityProfiles.append(
                    (checkBoxVar, checkBox, posLabel, eventTypeOption))
            rowCount += 1

        addNewExtremityButton = Button(self.profileExtremityFrame,
                                       text="Add a new extremity trigger",
                                       command=self.add_extremity_window)
        addNewExtremityButton.grid(sticky="W",
                                   row=rowCount,
                                   column=0,
                                   pady=5,
                                   padx=5)
        rowCount += 1
        removeExtremityButton = Button(
            self.profileExtremityFrame,
            text="Delete existed extremity triggers",
            command=self.remove_extremity_window)
        removeExtremityButton.grid(sticky="W",
                                   row=rowCount,
                                   column=0,
                                   pady=5,
                                   padx=5)

        self.profileNotebook.add(self.profileExerciseFrame, text="Exercise")
        self.profileNotebook.add(self.profileExtremityFrame, text="Extremity")

        self.instructionLabel2 = Label(
            profileSettingsFrame,
            text=
            'Click APPLY to save the settings.\nClick \'X\' on the upper right corner to close'
            ' the page.',
            font=("Courier", 10))
        self.instructionLabel2.config(anchor=CENTER)
        self.instructionLabel2.pack()
        apply_button = Button(profileSettingsFrame,
                              text="APPLY",
                              command=self.apply_profile).pack()
Exemplo n.º 9
0
def _handler(req):

  # Create a working area in request object if it
  # doesn't exist already.

  if not hasattr(req,"vampire"):
    req.vampire = {}

  # Record in request object which handler is servicing
  # the request. This can be used by a handler to
  # accomodate being able to be called as a handler or
  # publisher type method.

  req.vampire["handler"] = "vampire::handler"

  # Translate a request against a directory to a request
  # against a specified index file.

  if req.path_info == "" and os.path.isdir(req.filename):
    options = req.get_options()
    if options.has_key("VampireDirectoryIndex"):
      value = options["VampireDirectoryIndex"]
      if value != ".":
        if req.args:
          value = "%s?%s" % (value,req.args)
        if hasattr(req,"internal_redirect"):
          req.internal_redirect(req.uri+value)
        else:
          req.headers_out["location"] = "%s" % value
          req.status = apache.HTTP_MOVED_TEMPORARILY
        return apache.OK

  # Determine type of file based on extension.

  stub,extn = os.path.splitext(req.filename)

  # Forbid requests against Python code files or
  # anything which may be generated from them.

  if extn in [".py",".pyc",".pyo"]:
    if os.path.exists(req.filename):
      return apache.HTTP_NOT_FOUND

  # Determine name of the content handler to be used.

  if extn != "":
    method = "handler_%s" % extn[1:]
  else:
    method = "handler"

  # Search for handler in associated python code.

  file = stub + ".py"
  module = _import(req,file)

  # If we have already found a valid module, first check
  # to see if it provides an appropriate handler.

  objects = []
  status = apache.HTTP_NOT_FOUND

  rules = _handler_rules

  if module:
    if not hasattr(module,"__handle__") or extn in module.__handle__:
      status,traverse,execute,access,objects = _resolve(
          req,module,[method],rules)

  # Look for any default handlers.

  req.vampire["__login__"] = None
  req.vampire["defaults"] = None

  options = req.get_options()
  if options.has_key("VampireDefaultHandlers"):
    if options["VampireDefaultHandlers"] in ["On","on"]:
      file = ".vampire"
      if options.has_key("VampireHandlersConfig"):
        file = options["VampireHandlersConfig"]
      config = _configCache.loadConfig(req,file)
      section = "Handlers"
      if options.has_key("VampireHandlersSection"):
        section = options["VampireHandlersSection"]

      # Section defined for default handlers.

      if config.has_section(section):

        # Look for module of default handlers.

        file = None
        if config.has_option(section,"defaults"):
          file = config.get(section,"defaults")
        if file != None:
          if os.path.splitext(file)[1] != ".py":
            return apache.HTTP_INTERNAL_SERVER_ERROR
          req.vampire["defaults"] = _import(req,file)
          if not req.vampire["defaults"]:
            raise ImportError("No file named %s"%file)

        # Look for default login handler in module of
        # default handlers to override the inbuilt basic
        # authentication login handler.

        if req.vampire["defaults"]:
          module = req.vampire["defaults"]
          if hasattr(module,"loginhandler"):
            req.vampire["__login__"] = getattr(module,"loginhandler")

        # Look for explicitly defined default login
        # handler. These can still be overridden by
        # "__login__" function present within objects
        # which are traversed.

        file = None
        if config.has_option(section,"loginhandler"):
          file = config.get(section,"loginhandler")
        if file != None:
          if os.path.splitext(file)[1] != ".py":
            return apache.HTTP_INTERNAL_SERVER_ERROR
          module = _import(req,file)
          if module:
            if hasattr(module,"loginhandler"):
              req.vampire["__login__"] = getattr(module,"loginhandler")
            else:
              raise ImportError("Cannot import loginhandler from %s"%file)
          else:
            raise ImportError("No file named %s"%file)

        # If a specific content handler wasn't already
        # found for the actual request, see if default
        # content handler has been specified.

        if status != apache.OK:

          # First look in module of default handlers.

          if req.vampire["defaults"]:
            status,traverse,execute,access,objects = _resolve(
                req,req.vampire["defaults"],[method],rules)

          # Now check for an explicitly defined handler.

          if len(objects) <= 1:
            file = None
            if config.has_option(section,method):
              file = config.get(section,method)
            if file != None:
              if os.path.splitext(file)[1] != ".py":
                return apache.HTTP_INTERNAL_SERVER_ERROR
              module = _import(req,file)
              if module:
                status,traverse,execute,access,objects = _resolve(
                    req,module,[method],rules)
                if status != apache.OK:
                  raise ImportError("Cannot import %s from %s"%(method,file))
              else:
                raise ImportError("No file named %s"%file)

  req.vampire["objects"] = objects

  # Perform authentication even if we did not find an
  # acceptable handler.

  _authenticate(req)

  # Return control to Apache if we were unable to find
  # an acceptable handler to execute.

  if status != apache.OK:
    return apache.DECLINED

  # Execute the content handler which was found.

  result = _execute(req,objects[-1],lazy=True)

  # To try and make standard content handlers and
  # publisher style handlers interchangeable, allow a
  # return value of "None" to be interchangeable with
  # returning "apache.OK".

  if result is None:
    return apache.OK

  return result
Exemplo n.º 10
0
def _select(req,name):

  # Create a working area in request object if it
  # doesn't exist already.

  if not hasattr(req,"vampire"):
    req.vampire = {}

  # Try and find entry in appropriate config.

  options = req.get_options()

  file = ".vampire"
  if options.has_key("VampireHandlersConfig"):
    file = options["VampireHandlersConfig"]

  config = _configCache.loadConfig(req,file)

  section = "Handlers"
  if options.has_key("VampireHandlersSection"):
    section = options["VampireHandlersSection"]

  handler = None

  if config.has_section(section):
    if config.has_option(section,name):
      handler = config.get(section,name)

  # If there is no entry or it is empty, skip it.

  if not handler:
    return apache.OK

  # Ensure handler is a Python module file.

  if os.path.splitext(handler)[1] != ".py":
    return apache.HTTP_INTERNAL_SERVER_ERROR

  # The handler is supposed to be the actual
  # file name of the module to load. The actual
  # handler within it must be matching name for
  # the directive, it can't be something else.

  directory = os.path.dirname(handler)
  stub = os.path.splitext(os.path.basename(handler))[0]

  module = _moduleCache.importModule(stub,directory,req)

  if not module:
    raise ImportError("No file named %s"%handler)

  # Determine the appropriate content handler.

  function = None

  if hasattr(module,name):
    function = getattr(module,name)

  if function == None:
    raise ImportError("Cannot import %s from %s"%(name,handler))

  # Execute the actual handler function.

  result = function(req)

  if result is None:
    return apache.OK

  return result