Example #1
0
def configure_handler(req, default):

    req.allow_methods(["GET", "POST"])
    if req.method not in ["GET", "POST"]:
        raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

    func_path = ""
    if req.path_info:
        func_path = req.path_info[1:]  # skip first /
        # func_path = func_path.replace("/", ".")
        # if func_path[-1:] == ".":
        #    func_path = func_path[:-1]
        # changed: only keep the first directory
        func_path = re.sub("/.*", "", func_path)

    # default to 'index' if no path_info was given
    if not func_path:
        func_path = "index"

    # if any part of the path begins with "_", abort
    if func_path[0] == "_" or func_path.count("._"):
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    ## import the script
    path, module_name = os.path.split(req.filename)
    if not module_name:
        module_name = "index"

    # get rid of the suffix
    #   explanation: Suffixes that will get stripped off
    #   are those that were specified as an argument to the
    #   AddHandler directive. Everything else will be considered
    #   a package.module rather than module.suffix
    exts = req.get_addhandler_exts()
    if not exts:
        # this is SetHandler, make an exception for Python suffixes
        exts = imp_suffixes
    if req.extension:  # this exists if we're running in a | .ext handler
        exts += req.extension[1:]
    if exts:
        suffixes = exts.strip().split()
        exp = "\\." + "$|\\.".join(suffixes)
        suff_matcher = re.compile(exp)  # python caches these, so its fast
        module_name = suff_matcher.sub("", module_name)

    # import module (or reload if needed)
    # the [path] argument tells import_module not to allow modules whose
    # full path is not in [path] or below.
    config = req.get_config()
    autoreload = int(config.get("PythonAutoReload", 1))
    log = int(config.get("PythonDebug", 0))
    try:
        module = apache.import_module(module_name, autoreload=autoreload, log=log, path=[path])
    except ImportError:
        et, ev, etb = sys.exc_info()
        # try again, using default module, perhaps this is a
        # /directory/function (as opposed to /directory/module/function)
        func_path = module_name
        module_name = "index"
        try:
            module = apache.import_module(module_name, autoreload=autoreload, log=log, path=[path])
        except ImportError:
            # raise the original exception
            raise et, ev, etb

    # does it have an __auth__?
    realm, user, passwd = process_auth(req, module)

    # resolve the object ('traverse')
    try:
        object = resolve_object(req, module, func_path, realm, user, passwd)
    except AttributeError:
        # changed, return the default path instead
        # raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
        object = default
    # not callable, a class or an unbound method
    if not callable(object) or type(object) is ClassType or (hasattr(object, "im_self") and not object.im_self):

        result = str(object)

    else:
        # callable, (but not a class or unbound method)

        # process input, if any
        req.form = util.FieldStorage(req, keep_blank_values=1)

        result = util.apply_fs_data(object, req.form, req=req)

    if result or req.bytes_sent > 0 or req.next:

        if result is None:
            result = ""
        else:
            result = str(result)

        # unless content_type was manually set, we will attempt
        # to guess it
        if not req._content_type_set:
            # make an attempt to guess content-type
            if result[:100].strip()[:6].lower() == "<html>" or result.find("</") > 0:
                req.content_type = "text/html"
            else:
                req.content_type = "text/plain"

        if req.method != "HEAD":
            req.write(result)
        else:
            req.write("")
        return apache.OK
    else:
        req.log_error("mod_python.publisher: %s returned nothing." % ` object `)
        return apache.HTTP_INTERNAL_SERVER_ERROR
Example #2
0
    def handler(req):
        req.allow_methods(["GET", "POST"])
        if req.method not in ["GET", "POST"]:
            raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

        # Derive the name of the actual module which will be
        # loaded. In older version of mod_python.publisher
        # you can't actually have a code file name which has
        # an embedded '.' in it except for that used by the
        # extension. This is because the standard Python
        # module import system which is used will think that
        # you are importing a submodule of a package. In
        # this code, because the standard Python module
        # import system isn't used and the actual file is
        # opened directly by name, an embedded '.' besides
        # that used for the extension will technically work.
        
        path,module_name =  os.path.split(req.filename)
    
        # If the request is against a directory, fallback to
        # looking for the 'index' module. This is determined
        # by virtue of the fact that Apache will always add
        # a trailing slash to 'req.filename' when it matches
        # a directory. This will mean that the calculated
        # module name will be empty.

        if not module_name:  
            module_name = 'index'

        # Now need to strip off any special extension which
        # was used to trigger this handler in the first place.
            
        suffixes = ['py']
        suffixes += req.get_addhandler_exts().split()
        if req.extension:
            suffixes.append(req.extension[1:])

        exp = '\\.' + '$|\\.'.join(suffixes) + '$'
        suff_matcher = re.compile(exp)
        module_name = suff_matcher.sub('',module_name)

        # Next need to determine the path for the function
        # which will be called from 'req.path_info'. The
        # leading slash and possibly any trailing slash are
        # eliminated. There would normally be at most one
        # trailing slash as Apache eliminates duplicates
        # from the original URI.

        func_path = ''

        if req.path_info:
            func_path = req.path_info[1:]
            if func_path[-1:] == '/':
                func_path = func_path[:-1]

        # Now determine the actual Python module code file
        # to load. This will first try looking for the file
        # '/path/<module_name>.py'. If this doesn't exist,
        # will try fallback of using the 'index' module,
        # ie., look for '/path/index.py'. In doing this, the
        # 'func_path' gets adjusted so the lead part is what
        # 'module_name' was set to.

        req.filename = path + '/' + module_name + '.py'

        if not publisher.exists(req.filename):
            if publisher.exists(path + '/' + module_name + '.rpy'):
                req.filename = path + '/' + module_name + '.rpy'
            else:
                if func_path:
                    func_path = module_name + '/' + func_path
                else:
                    func_path = module_name

                module_name = 'index' 
                req.filename = path + '/' + module_name + '.py'

            if not publisher.exists(req.filename):
                raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

        # Default to looking for the 'index' function if no
        # function path definition was supplied.

        if not func_path:
            func_path = 'resource'

        # Turn slashes into dots.

        func_path = func_path.replace('/', '.')

        # Normalise req.filename to avoid Win32 issues.

        req.filename = publisher.normpath(req.filename)


        # We use the page cache to load the module
        module = publisher.page_cache[req]

        # does it have an __auth__?
        realm, user, passwd = publisher.process_auth(req, module)

        # resolve the object ('traverse')
        resource = publisher.resolve_object(req, module, func_path, 
                                            realm, user, passwd)

        if req.method == 'GET':
            modelGraph = resource.getServiceDescription()
            accept = 'application/rdf+xml'
            if 'Accept' in req.headers_in:
                accept = req.headers_in["Accept"]
            acceptType = resource.getFormat(accept)
            req.content_type = acceptType[0]
            req.headers_out['Access-Control-Allow-Origin'] = '*'
            req.write(resource.serialize(modelGraph,req.headers_in['Accept']))
        else:
            content = req.read()
            contentType = "application/rdf+xml"
            if 'Content-Type' in req.headers_in:
                contentType = req.headers_in["Content-Type"]
            graph = resource.processGraph(content, contentType)
            accept = "application/rdf+xml"
            if 'Accept' in req.headers_in:
                accept = req.headers_in["Accept"]
            acceptType = resource.getFormat(accept)
            req.headers_out["Content-Type"] = acceptType[0]
            req.headers_out['Access-Control-Allow-Origin'] = '*'
            req.write(resource.serialize(graph,accept))
        return apache.OK
Example #3
0
    def handler(req):
        req.allow_methods(["GET", "POST"])
        if req.method not in ["GET", "POST"]:
            raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

        # Derive the name of the actual module which will be
        # loaded. In older version of mod_python.publisher
        # you can't actually have a code file name which has
        # an embedded '.' in it except for that used by the
        # extension. This is because the standard Python
        # module import system which is used will think that
        # you are importing a submodule of a package. In
        # this code, because the standard Python module
        # import system isn't used and the actual file is
        # opened directly by name, an embedded '.' besides
        # that used for the extension will technically work.

        path, module_name = os.path.split(req.filename)

        # If the request is against a directory, fallback to
        # looking for the 'index' module. This is determined
        # by virtue of the fact that Apache will always add
        # a trailing slash to 'req.filename' when it matches
        # a directory. This will mean that the calculated
        # module name will be empty.

        if not module_name:
            module_name = 'index'

        # Now need to strip off any special extension which
        # was used to trigger this handler in the first place.

        suffixes = ['py']
        suffixes += req.get_addhandler_exts().split()
        if req.extension:
            suffixes.append(req.extension[1:])

        exp = '\\.' + '$|\\.'.join(suffixes) + '$'
        suff_matcher = re.compile(exp)
        module_name = suff_matcher.sub('', module_name)

        # Next need to determine the path for the function
        # which will be called from 'req.path_info'. The
        # leading slash and possibly any trailing slash are
        # eliminated. There would normally be at most one
        # trailing slash as Apache eliminates duplicates
        # from the original URI.

        func_path = ''

        if req.path_info:
            func_path = req.path_info[1:]
            if func_path[-1:] == '/':
                func_path = func_path[:-1]

        # Now determine the actual Python module code file
        # to load. This will first try looking for the file
        # '/path/<module_name>.py'. If this doesn't exist,
        # will try fallback of using the 'index' module,
        # ie., look for '/path/index.py'. In doing this, the
        # 'func_path' gets adjusted so the lead part is what
        # 'module_name' was set to.

        req.filename = path + '/' + module_name + '.py'

        if not publisher.exists(req.filename):
            if publisher.exists(path + '/' + module_name + '.rpy'):
                req.filename = path + '/' + module_name + '.rpy'
            else:
                if func_path:
                    func_path = module_name + '/' + func_path
                else:
                    func_path = module_name

                module_name = 'index'
                req.filename = path + '/' + module_name + '.py'

            if not publisher.exists(req.filename):
                raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

        # Default to looking for the 'index' function if no
        # function path definition was supplied.

        if not func_path:
            func_path = 'resource'

        # Turn slashes into dots.

        func_path = func_path.replace('/', '.')

        # Normalise req.filename to avoid Win32 issues.

        req.filename = publisher.normpath(req.filename)

        # We use the page cache to load the module
        module = publisher.page_cache[req]

        # does it have an __auth__?
        realm, user, passwd = publisher.process_auth(req, module)

        # resolve the object ('traverse')
        resource = publisher.resolve_object(req, module, func_path, realm,
                                            user, passwd)

        if req.method == 'GET':
            modelGraph = resource.getServiceDescription()
            accept = 'application/rdf+xml'
            if 'Accept' in req.headers_in:
                accept = req.headers_in["Accept"]
            acceptType = resource.getFormat(accept)
            req.content_type = acceptType[0]
            req.headers_out['Access-Control-Allow-Origin'] = '*'
            req.write(resource.serialize(modelGraph, req.headers_in['Accept']))
        else:
            content = req.read()
            contentType = "application/rdf+xml"
            if 'Content-Type' in req.headers_in:
                contentType = req.headers_in["Content-Type"]
            graph = resource.processGraph(content, contentType)
            accept = "application/rdf+xml"
            if 'Accept' in req.headers_in:
                accept = req.headers_in["Accept"]
            acceptType = resource.getFormat(accept)
            req.headers_out["Content-Type"] = acceptType[0]
            req.headers_out['Access-Control-Allow-Origin'] = '*'
            req.write(resource.serialize(graph, accept))
        return apache.OK
Example #4
0
def configure_handler(req, default):

    req.allow_methods(["GET", "POST"])
    if req.method not in ["GET", "POST"]:
        raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED

    func_path = ""
    if req.path_info:
        func_path = req.path_info[1:]  # skip first /
        #func_path = func_path.replace("/", ".")
        #if func_path[-1:] == ".":
        #    func_path = func_path[:-1]
        # changed: only keep the first directory
        func_path = re.sub('/.*', '', func_path)

    # default to 'index' if no path_info was given
    if not func_path:
        func_path = "index"

    # if any part of the path begins with "_", abort
    if func_path[0] == '_' or func_path.count("._"):
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    ## import the script
    path, module_name = os.path.split(req.filename)
    if not module_name:
        module_name = "index"

    # get rid of the suffix
    #   explanation: Suffixes that will get stripped off
    #   are those that were specified as an argument to the
    #   AddHandler directive. Everything else will be considered
    #   a package.module rather than module.suffix
    exts = req.get_addhandler_exts()
    if not exts:
        # this is SetHandler, make an exception for Python suffixes
        exts = imp_suffixes
    if req.extension:  # this exists if we're running in a | .ext handler
        exts += req.extension[1:]
    if exts:
        suffixes = exts.strip().split()
        exp = "\\." + "$|\\.".join(suffixes)
        suff_matcher = re.compile(exp)  # python caches these, so its fast
        module_name = suff_matcher.sub("", module_name)

    # import module (or reload if needed)
    # the [path] argument tells import_module not to allow modules whose
    # full path is not in [path] or below.
    config = req.get_config()
    autoreload = int(config.get("PythonAutoReload", 1))
    log = int(config.get("PythonDebug", 0))
    try:
        module = apache.import_module(module_name,
                                      autoreload=autoreload,
                                      log=log,
                                      path=[path])
    except ImportError:
        et, ev, etb = sys.exc_info()
        # try again, using default module, perhaps this is a
        # /directory/function (as opposed to /directory/module/function)
        func_path = module_name
        module_name = "index"
        try:
            module = apache.import_module(module_name,
                                          autoreload=autoreload,
                                          log=log,
                                          path=[path])
        except ImportError:
            # raise the original exception
            raise et, ev, etb

    # does it have an __auth__?
    realm, user, passwd = process_auth(req, module)

    # resolve the object ('traverse')
    try:
        object = resolve_object(req, module, func_path, realm, user, passwd)
    except AttributeError:
        # changed, return the default path instead
        #raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
        object = default
    # not callable, a class or an unbound method
    if (not callable(object) or type(object) is ClassType
            or (hasattr(object, 'im_self') and not object.im_self)):

        result = str(object)

    else:
        # callable, (but not a class or unbound method)

        # process input, if any
        req.form = util.FieldStorage(req, keep_blank_values=1)

        result = util.apply_fs_data(object, req.form, req=req)

    if result or req.bytes_sent > 0 or req.next:

        if result is None:
            result = ""
        else:
            result = str(result)

        # unless content_type was manually set, we will attempt
        # to guess it
        if not req._content_type_set:
            # make an attempt to guess content-type
            if result[:100].strip()[:6].lower() == '<html>' \
               or result.find('</') > 0:
                req.content_type = 'text/html'
            else:
                req.content_type = 'text/plain'

        if req.method != "HEAD":
            req.write(result)
        else:
            req.write("")
        return apache.OK
    else:
        req.log_error("mod_python.publisher: %s returned nothing." %
                      ` object `)
        return apache.HTTP_INTERNAL_SERVER_ERROR