Example #1
0
    def __init__(self):

        request = current.request

        # Load s3cfg => but why do this so complicated?
        #name = "applications.%s.modules.s3cfg" % request.application
        #s3cfg = __import__(name)
        #for item in name.split(".")[1:]:
        ## Remove the dot
        #s3cfg = getattr(s3cfg, item)
        #settings = s3cfg.S3Config()

        # Can use normal import here since executed in web2py environment:
        import s3cfg
        settings = s3cfg.S3Config()

        # Pass into template
        current.deployment_settings = settings

        # Read settings
        model = "%s/models/000_config.py" % request.folder
        code = getcfs(model, model, None)
        response = current.response

        # Needed as some Templates look at this & we don't wish to crash:
        response.s3 = Storage()

        # Global variables for 000_config.py
        environment = build_environment(request, response, current.session)
        environment["settings"] = settings
        # Some (older) 000_config.py also use "deployment_settings":
        environment["deployment_settings"] = settings
        # For backwards-compatibility with older 000_config.py:
        #def template_path():
        #    # When you see this warning, you should update 000_config.py
        #    # See: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Templates/Migration#Changesin000_config.py
        #    print "template_path() is deprecated, please update 000_config.py"
        #    # Return just any valid path to make sure the path-check succeeds,
        #    # => modern S3Config will find the template itself
        #    return request.folder
        #environment["template_path"] = template_path
        environment["os"] = os
        environment["Storage"] = Storage

        # Execute 000_config.py
        restricted(code, environment, layer=model)

        self.db_engine = settings.get_database_type()
        (db_string, pool_size) = settings.get_database_string()

        # Get a handle to the database
        self.db = DAL(
            db_string,
            #folder="%s/databases" % request.folder,
            auto_import=True,
            # @ToDo: Set to False until we migrate
            migrate_enabled=True,
        )
Example #2
0
 def exec_template(self, path):
     """
         Execute the template
     """
     from gluon.fileutils import read_file
     from gluon.restricted import restricted
     code = read_file(path)
     restricted(code, layer=path)
     return
Example #3
0
 def exec_template(self, path):
     """
         Execute the template
     """
     from gluon.fileutils import read_file
     from gluon.restricted import restricted
     code = read_file(path)
     restricted(code, layer=path)
     return
Example #4
0
    def __init__(self):

        request = current.request

        # Load s3cfg => but why do this so complicated?
        #name = "applications.%s.modules.s3cfg" % request.application
        #s3cfg = __import__(name)
        #for item in name.split(".")[1:]:
            ## Remove the dot
            #s3cfg = getattr(s3cfg, item)
        #settings = s3cfg.S3Config()

        # Can use normal import here since executed in web2py environment:
        import s3cfg
        settings = s3cfg.S3Config()

        # Pass into template
        current.deployment_settings = settings

        # Read settings
        model = "%s/models/000_config.py" % request.folder
        code = getcfs(model, model, None)
        response = current.response

        # Needed as some Templates look at this & we don't wish to crash:
        response.s3 = Storage()

        # Global variables for 000_config.py
        environment = build_environment(request, response, current.session)
        environment["settings"] = settings
        # Some (older) 000_config.py also use "deployment_settings":
        environment["deployment_settings"] = settings
        # For backwards-compatibility with older 000_config.py:
        #def template_path():
        #    # When you see this warning, you should update 000_config.py
        #    # See: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Templates/Migration#Changesin000_config.py
        #    print "template_path() is deprecated, please update 000_config.py"
        #    # Return just any valid path to make sure the path-check succeeds,
        #    # => modern S3Config will find the template itself
        #    return request.folder
        #environment["template_path"] = template_path
        environment["os"] = os
        environment["Storage"] = Storage

        # Execute 000_config.py
        restricted(code, environment, layer=model)

        self.db_engine = settings.get_database_type()
        (db_string, pool_size) = settings.get_database_string()

        # Get a handle to the database
        self.db = DAL(db_string,
                      #folder="%s/databases" % request.folder,
                      auto_import=True,
                      # @ToDo: Set to False until we migrate
                      migrate_enabled=True,
                      )
Example #5
0
def run_models_in(environment):
    """
    Runs all models (in the app specified by the current folder)
    It tries pre-compiled models first before compiling them.
    """

    request = current.request
    folder = request.folder
    c = request.controller
    #f = environment['request'].function
    response = current.response

    path = pjoin(folder, 'models')
    cpath = pjoin(folder, 'compiled')
    compiled = os.path.exists(cpath)
    if PY2:
        if compiled:
            models = sorted(listdir(cpath, '^models[_.][\w.]+\.pyc$', 0),
                            model_cmp)
        else:
            models = sorted(listdir(path, '^\w+\.py$', 0, sort=False),
                            model_cmp_sep)
    else:
        if compiled:
            models = sorted(listdir(cpath, '^models[_.][\w.]+\.pyc$', 0),
                            key=lambda f: '{0:03d}'.format(f.count('.')) + f)
        else:
            models = sorted(
                listdir(path, '^\w+\.py$', 0, sort=False),
                key=lambda f: '{0:03d}'.format(f.count(os.path.sep)) + f)

    models_to_run = None
    for model in models:
        if response.models_to_run != models_to_run:
            regex = models_to_run = response.models_to_run[:]
            if isinstance(regex, list):
                regex = re_compile('|'.join(regex))
        if models_to_run:
            if compiled:
                n = len(cpath) + 8
                fname = model[n:-4].replace('.', '/') + '.py'
            else:
                n = len(path) + 1
                fname = model[n:].replace(os.path.sep, '/')
            if not regex.search(fname) and c != 'appadmin':
                continue
            elif compiled:
                code = read_pyc(model)
            elif is_gae:
                code = getcfs(model, model,
                              lambda: compile2(read_file(model), model))
            else:
                code = getcfs(model, model, None)
            restricted(code, environment, layer=model)
Example #6
0
 def exec_template(self, path):
     """
         Execute the template
     """
     #from gluon.compileapp import build_environment
     from gluon.fileutils import read_file
     from gluon.restricted import restricted
     #environment = build_environment(request, response, session)
     code = read_file(path)
     #restricted(code, environment, layer=path)
     restricted(code, layer=path)
     return
Example #7
0
 def exec_template(self, path):
     """
         Execute the template
     """
     #from gluon.compileapp import build_environment
     from gluon.fileutils import read_file
     from gluon.restricted import restricted
     #environment = build_environment(request, response, session)
     code = read_file(path)
     #restricted(code, environment, layer=path)
     restricted(code, layer=path)
     return
Example #8
0
def run_models_in(environment):
    """
    Runs all models (in the app specified by the current folder)
    It tries pre-compiled models first before compiling them.
    """
    request = current.request
    folder = request.folder
    c = request.controller
    # f = environment['request'].function
    response = current.response

    path = pjoin(folder, 'models')
    cpath = pjoin(folder, 'compiled')
    compiled = exists(cpath)
    if PY2:
        if compiled:
            models = sorted(listdir(cpath, REGEX_COMPILED_MODEL, 0),
                            model_cmp)
        else:
            models = sorted(listdir(path, REGEX_MODEL, 0, sort=False),
                            model_cmp_sep)
    else:
        if compiled:
            models = sorted(listdir(cpath, REGEX_COMPILED_MODEL, 0),
                            key=lambda f: '{0:03d}'.format(f.count('.')) + f)
        else:
            models = sorted(listdir(path, REGEX_MODEL, 0, sort=False),
                            key=lambda f: '{0:03d}'.format(f.count(os.sep)) + f)

    models_to_run = None
    for model in models:
        if response.models_to_run != models_to_run:
            regex = models_to_run = response.models_to_run[:]
            if isinstance(regex, list):
                regex = re_compile('|'.join(regex))
        if models_to_run:
            if compiled:
                n = len(cpath)+8
                fname = model[n:-4].replace('.', '/')+'.py'
            else:
                n = len(path)+1
                fname = model[n:].replace(os.sep, '/')
            if not regex.search(fname) and c != 'appadmin':
                continue
            elif compiled:
                f = lambda: read_pyc(model)
            else:
                f = lambda: compile2(read_file(model), model)
            ccode = getcfs(model, model, f)
            restricted(ccode, environment, layer=model)
Example #9
0
    def __init__(self):

        request = current.request

        # Load s3cfg
        name = "applications.%s.modules.s3cfg" % request.application
        s3cfg = __import__(name)
        for item in name.split(".")[1:]:
            # Remove the dot
            s3cfg = getattr(s3cfg, item)
        settings = s3cfg.S3Config()
        # Pass into template
        current.deployment_settings = settings

        # Read settings
        model = "%s/models/000_config.py" % request.folder
        code = getcfs(model, model, None)
        response = current.response
        response.s3 = Storage(
        )  # Needed as some Templates look at this & we don't wish to crash
        environment = build_environment(request, response, current.session)
        environment["settings"] = settings

        def template_path():
            " Return the path of the Template config.py to load "
            path = os.path.join(request.folder, "private", "templates",
                                settings.get_template(), "config.py")
            return path

        environment["template_path"] = template_path
        environment["os"] = os
        environment["Storage"] = Storage
        restricted(code, environment, layer=model)

        self.db_engine = settings.get_database_type()
        (db_string, pool_size) = settings.get_database_string()

        # Get a handle to the database
        self.db = DAL(
            db_string,
            #folder="%s/databases" % request.folder,
            auto_import=True,
            # @ToDo: Set to False until we migrate
            migrate_enabled=True,
        )
Example #10
0
    def __init__(self):

        request = current.request

        # Load s3cfg
        name = "applications.%s.modules.s3cfg" % request.application
        s3cfg = __import__(name)
        for item in name.split(".")[1:]:
            # Remove the dot
            s3cfg = getattr(s3cfg, item)
        settings = s3cfg.S3Config()
        # Pass into template
        current.deployment_settings = settings

        # Read settings
        model = "%s/models/000_config.py" % request.folder
        code = getcfs(model, model, None)
        response = current.response
        response.s3 = Storage() # Needed as some Templates look at this & we don't wish to crash
        environment = build_environment(request, response,
                                        current.session)
        environment["settings"] = settings
        def template_path():
            " Return the path of the Template config.py to load "
            path = os.path.join(request.folder,
                                "private", "templates",
                                settings.get_template(),
                                "config.py")
            return path
        environment["template_path"] = template_path
        environment["os"] = os
        environment["Storage"] = Storage
        restricted(code, environment, layer=model)

        self.db_engine = settings.get_database_type()
        (db_string, pool_size) = settings.get_database_string()

        # Get a handle to the database
        self.db = DAL(db_string,
                      #folder="%s/databases" % request.folder,
                      auto_import=True,
                      # @ToDo: Set to False until we migrate
                      migrate_enabled=True,
                      )
Example #11
0
def run_models_in(environment):
    """
    Runs all models (in the app specified by the current folder)
    It tries pre-compiled models first before compiling them.
    """

    request = current.request
    folder = request.folder
    c = request.controller
    #f = environment['request'].function
    response = current.response

    path = pjoin(folder, 'models')
    cpath = pjoin(folder, 'compiled')
    compiled = os.path.exists(cpath)
    if compiled:
        models = sorted(listdir(cpath, '^models[_.][\w.]+\.pyc$', 0), model_cmp)
    else:
        models = sorted(listdir(path, '^\w+\.py$', 0, sort=False), model_cmp_sep)
    models_to_run = None
    for model in models:
        if response.models_to_run != models_to_run:
            regex = models_to_run = response.models_to_run[:]
            if isinstance(regex, list):
                regex = re_compile('|'.join(regex))
        if models_to_run:
            if compiled:
                n = len(cpath)+8
                fname = model[n:-4].replace('.','/')+'.py'
            else:
                n = len(path)+1
                fname = model[n:].replace(os.path.sep,'/')
            if not regex.search(fname) and c != 'appadmin':
                continue
            elif compiled:
                code = read_pyc(model)
            elif is_gae:
                code = getcfs(model, model,
                              lambda: compile2(read_file(model), model))
            else:
                code = getcfs(model, model, None)
            restricted(code, environment, layer=model)
Example #12
0
def run_controller_in(controller, function, environment):
    """
    Runs the controller.function() (for the app specified by
    the current folder).
    It tries pre-compiled controller_function.pyc first before compiling it.
    """

    # if compiled should run compiled!
    folder = environment["request"].folder
    path = pjoin(folder, "compiled")
    badc = "invalid controller (%s/%s)" % (controller, function)
    badf = "invalid function (%s/%s)" % (controller, function)
    if os.path.exists(path):
        filename = pjoin(path, "controllers.%s.%s.pyc" % (controller, function))
        if not os.path.exists(filename):
            ### for backward compatibility
            filename = pjoin(path, "controllers_%s_%s.pyc" % (controller, function))
            ### end for backward compatibility
            if not os.path.exists(filename):
                raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf)
        restricted(read_pyc(filename), environment, layer=filename)
    elif function == "_TEST":
        # TESTING: adjust the path to include site packages
        from settings import global_settings
        from admin import abspath, add_path_first

        paths = (global_settings.gluon_parent, abspath("site-packages", gluon=True), abspath("gluon", gluon=True), "")
        [add_path_first(path) for path in paths]
        # TESTING END

        filename = pjoin(folder, "controllers/%s.py" % controller)
        if not os.path.exists(filename):
            raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc)
        environment["__symbols__"] = environment.keys()
        code = read_file(filename)
        code += TEST_CODE
        restricted(code, environment, layer=filename)
    else:
        filename = pjoin(folder, "controllers/%s.py" % controller)
        if not os.path.exists(filename):
            raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc)
        code = read_file(filename)
        exposed = find_exposed_functions(code)
        if not function in exposed:
            raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf)
        code = "%s\nresponse._vars=response._caller(%s)\n" % (code, function)
        if is_gae:
            layer = filename + ":" + function
            code = getcfs(layer, filename, lambda: compile2(code, layer))
        restricted(code, environment, filename)
    response = environment["response"]
    vars = response._vars
    if response.postprocessing:
        vars = reduce(lambda vars, p: p(vars), response.postprocessing, vars)
    if isinstance(vars, unicode):
        vars = vars.encode("utf8")
    elif hasattr(vars, "xml") and callable(vars.xml):
        vars = vars.xml()
    return vars
Example #13
0
def run_models_in(environment):
    """
    Runs all models (in the app specified by the current folder)
    It tries pre-compiled models first before compiling them.
    """

    folder = environment['request'].folder
    c = environment['request'].controller
    f = environment['request'].function
    cpath = pjoin(folder, 'compiled')
    if os.path.exists(cpath):
        for model in listdir(cpath, '^models_\w+\.pyc$', 0):
            restricted(read_pyc(model), environment, layer=model)
        path = pjoin(cpath, 'models')
        models = listdir(path, '^\w+\.pyc$', 0, sort=False)
        compiled = True
    else:
        path = pjoin(folder, 'models')
        models = listdir(path, '^\w+\.py$', 0, sort=False)
        compiled = False
    n = len(path) + 1
    for model in models:
        regex = environment['response'].models_to_run
        if isinstance(regex, list):
            regex = re_compile('|'.join(regex))
        file = model[n:].replace(os.path.sep, '/').replace('.pyc', '.py')
        if not regex.search(file) and c != 'appadmin':
            continue
        elif compiled:
            code = read_pyc(model)
        elif is_gae:
            code = getcfs(model, model,
                          lambda: compile2(read_file(model), model))
        else:
            code = getcfs(model, model, None)
        restricted(code, environment, layer=model)
Example #14
0
def run_models_in(environment):
    """
    Runs all models (in the app specified by the current folder)
    It tries pre-compiled models first before compiling them.
    """

    folder = environment['request'].folder
    c = environment['request'].controller
    f = environment['request'].function
    cpath = pjoin(folder, 'compiled')
    if os.path.exists(cpath):
        for model in listdir(cpath, '^models_\w+\.pyc$', 0):
            restricted(read_pyc(model), environment, layer=model)
        path = pjoin(cpath, 'models')
        models = listdir(path, '^\w+\.pyc$', 0, sort=True)
        compiled = True
    else:
        path = pjoin(folder, 'models')
        models = listdir(path, '^\w+\.py$', 0, sort=True)
        compiled = False
    n = len(path) + 1
    for model in models:
        regex = environment['response'].models_to_run
        if isinstance(regex, list):
            regex = re_compile('|'.join(regex))
        file = model[n:].replace(os.path.sep, '/').replace('.pyc', '.py')
        if not regex.search(file) and c != 'appadmin':
            continue
        elif compiled:
            code = read_pyc(model)
        elif is_gae:
            code = getcfs(model, model,
                          lambda: compile2(read_file(model), model))
        else:
            code = getcfs(model, model, None)
        restricted(code, environment, layer=model)
Example #15
0
def run_controller_in(controller, function, environment):
    """
    Runs the controller.function() (for the app specified by
    the current folder).
    It tries pre-compiled controller.function.pyc first before compiling it.
    """

    # if compiled should run compiled!
    folder = current.request.folder
    cpath = pjoin(folder, 'compiled')
    badc = 'invalid controller (%s/%s)' % (controller, function)
    badf = 'invalid function (%s/%s)' % (controller, function)
    if os.path.exists(cpath):
        filename = pjoin(cpath, 'controllers.%s.%s.pyc'
                         % (controller, function))
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badf,
                       web2py_error=badf)
        ccode = getcfs(filename, filename, lambda: read_pyc(filename))
    elif function == '_TEST':
        # TESTING: adjust the path to include site packages
        from gluon.settings import global_settings
        from gluon.admin import abspath, add_path_first
        paths = (global_settings.gluon_parent, abspath(
            'site-packages', gluon=True), abspath('gluon', gluon=True), '')
        [add_path_first(path) for path in paths]
        # TESTING END

        filename = pjoin(folder, 'controllers/%s.py'
                                 % controller)
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badc,
                       web2py_error=badc)
        environment['__symbols__'] = environment.keys()
        code = read_file(filename)
        code += TEST_CODE
        ccode = compile2(code, filename)
    else:
        filename = pjoin(folder, 'controllers/%s.py'
                                 % controller)
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badc,
                       web2py_error=badc)
        code = getcfs(filename, filename, lambda: read_file(filename))
        exposed = find_exposed_functions(code)
        if not function in exposed:
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badf,
                       web2py_error=badf)
        code = "%s\nresponse._vars=response._caller(%s)" % (code, function)
        layer = "%s:%s" % (filename, function)
        ccode = getcfs(layer, filename, lambda: compile2(code, filename))

    restricted(ccode, environment, layer=filename)
    response = environment["response"]
    vars = response._vars
    if response.postprocessing:
        vars = reduce(lambda vars, p: p(vars), response.postprocessing, vars)
    if isinstance(vars, unicodeT):
        vars = to_native(vars)
    elif hasattr(vars, 'xml') and callable(vars.xml):
        vars = vars.xml()
    return vars
Example #16
0
def run_controller_in(controller, function, environment):
    """
    Runs the controller.function() (for the app specified by
    the current folder).
    It tries pre-compiled controller.function.pyc first before compiling it.
    """
    # if compiled should run compiled!
    folder = current.request.folder
    cpath = pjoin(folder, 'compiled')
    badc = 'invalid controller (%s/%s)' % (controller, function)
    badf = 'invalid function (%s/%s)' % (controller, function)
    if exists(cpath):
        filename = pjoin(cpath,
                         'controllers.%s.%s.pyc' % (controller, function))
        try:
            ccode = getcfs(filename, filename, lambda: read_pyc(filename))
        except IOError:
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badf,
                       web2py_error=badf)
    elif function == '_TEST':
        # TESTING: adjust the path to include site packages
        paths = (global_settings.gluon_parent,
                 abspath('site-packages',
                         gluon=True), abspath('gluon', gluon=True), '')
        [add_path_first(path) for path in paths]
        # TESTING END

        filename = pjoin(folder, 'controllers/%s.py' % controller)
        if not exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badc,
                       web2py_error=badc)
        environment['__symbols__'] = list(environment.keys())
        code = read_file(filename)
        code += TEST_CODE
        ccode = compile2(code, filename)
    else:
        filename = pjoin(folder, 'controllers/%s.py' % controller)
        try:
            code = getcfs(filename, filename, lambda: read_file(filename))
        except IOError:
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badc,
                       web2py_error=badc)
        exposed = find_exposed_functions(code)
        if function not in exposed:
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badf,
                       web2py_error=badf)
        code = "%s\nresponse._vars=response._caller(%s)" % (code, function)
        layer = "%s:%s" % (filename, function)
        ccode = getcfs(layer, filename, lambda: compile2(code, filename))

    restricted(ccode, environment, layer=filename)
    response = environment["response"]
    vars = response._vars
    if response.postprocessing:
        vars = reduce(lambda vars, p: p(vars), response.postprocessing, vars)
    if isinstance(vars, unicodeT):
        vars = to_native(vars)
    elif hasattr(vars, 'xml') and callable(vars.xml):
        vars = vars.xml()
    return vars
Example #17
0
def run_view_in(environment):
    """
    Executes the view for the requested action.
    The view is the one specified in `response.view` or determined by the url
    or `view/generic.extension`
    It tries the pre-compiled views.controller.function.pyc before compiling it.
    """
    request = current.request
    response = current.response
    view = environment['response'].view
    folder = request.folder
    cpath = pjoin(folder, 'compiled')
    badv = 'invalid view (%s)' % view
    patterns = response.get('generic_patterns')
    layer = None
    scode = None
    if patterns:
        regex = re_compile('|'.join(fnmatch.translate(p) for p in patterns))
        short_action = '%(controller)s/%(function)s.%(extension)s' % request
        allow_generic = regex.search(short_action)
    else:
        allow_generic = False
    if not isinstance(view, str):
        ccode = parse_template(view,
                               pjoin(folder, 'views'),
                               context=environment)
        layer = 'file stream'
    else:
        filename = pjoin(folder, 'views', view)
        if exists(cpath):  # compiled views
            x = view.replace('/', '.')
            files = ['views.%s.pyc' % x]
            is_compiled = exists(pjoin(cpath, files[0]))
            # Don't use a generic view if the non-compiled view exists.
            if is_compiled or (not is_compiled and not exists(filename)):
                if allow_generic:
                    files.append('views.generic.%s.pyc' % request.extension)
                # for backward compatibility
                if request.extension == 'html':
                    files.append('views.%s.pyc' % x[:-5])
                    if allow_generic:
                        files.append('views.generic.pyc')
                # end backward compatibility code
                for f in files:
                    compiled = pjoin(cpath, f)
                    if exists(compiled):
                        ccode = getcfs(compiled, compiled,
                                       lambda: read_pyc(compiled))
                        layer = compiled
                        break
        # if the view is not compiled
        if not layer:
            if not exists(filename) and allow_generic:
                view = 'generic.' + request.extension
                filename = pjoin(folder, 'views', view)
            if not exists(filename):
                raise HTTP(404,
                           rewrite.THREAD_LOCAL.routes.error_message % badv,
                           web2py_error=badv)
            # Parse template
            scode = parse_template(view,
                                   pjoin(folder, 'views'),
                                   context=environment)
            # Compile template
            ccode = compile2(scode, filename)
            layer = filename
    restricted(ccode, environment, layer=layer, scode=scode)
    # parse_template saves everything in response body
    return environment['response'].body.getvalue()
Example #18
0
def run_controller_in(controller, function, environment):
    """
    Runs the controller.function() (for the app specified by
    the current folder).
    It tries pre-compiled controller_function.pyc first before compiling it.
    """

    # if compiled should run compiled!
    folder = current.request.folder
    path = pjoin(folder, 'compiled')
    badc = 'invalid controller (%s/%s)' % (controller, function)
    badf = 'invalid function (%s/%s)' % (controller, function)
    if os.path.exists(path):
        filename = pjoin(path,
                         'controllers.%s.%s.pyc' % (controller, function))
        if not os.path.exists(filename):
            ### for backward compatibility
            filename = pjoin(path,
                             'controllers_%s_%s.pyc' % (controller, function))
            ### end for backward compatibility
            if not os.path.exists(filename):
                raise HTTP(404,
                           rewrite.THREAD_LOCAL.routes.error_message % badf,
                           web2py_error=badf)
        restricted(read_pyc(filename), environment, layer=filename)
    elif function == '_TEST':
        # TESTING: adjust the path to include site packages
        from settings import global_settings
        from admin import abspath, add_path_first
        paths = (global_settings.gluon_parent,
                 abspath('site-packages',
                         gluon=True), abspath('gluon', gluon=True), '')
        [add_path_first(path) for path in paths]
        # TESTING END

        filename = pjoin(folder, 'controllers/%s.py' % controller)
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badc,
                       web2py_error=badc)
        environment['__symbols__'] = environment.keys()
        code = read_file(filename)
        code += TEST_CODE
        restricted(code, environment, layer=filename)
    else:
        filename = pjoin(folder, 'controllers/%s.py' % controller)
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badc,
                       web2py_error=badc)
        code = read_file(filename)
        exposed = find_exposed_functions(code)
        if not function in exposed:
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badf,
                       web2py_error=badf)
        code = "%s\nresponse._vars=response._caller(%s)\n" % (code, function)
        if is_gae:
            layer = filename + ':' + function
            code = getcfs(layer, filename, lambda: compile2(code, layer))
        restricted(code, environment, filename)
    response = current.response
    vars = response._vars
    if response.postprocessing:
        vars = reduce(lambda vars, p: p(vars), response.postprocessing, vars)
    if isinstance(vars, unicode):
        vars = vars.encode('utf8')
    elif hasattr(vars, 'xml') and callable(vars.xml):
        vars = vars.xml()
    return vars
Example #19
0
def run_view_in(environment):
    """
    Executes the view for the requested action.
    The view is the one specified in `response.view` or determined by the url
    or `view/generic.extension`
    It tries the pre-compiled views_controller_function.pyc before compiling it.
    """
    request = environment['request']
    response = environment['response']
    view = response.view
    folder = request.folder
    path = pjoin(folder, 'compiled')
    badv = 'invalid view (%s)' % view
    if response.generic_patterns:
        patterns = response.generic_patterns
        regex = re_compile('|'.join(map(fnmatch.translate, patterns)))
        short_action = '%(controller)s/%(function)s.%(extension)s' % request
        allow_generic = regex.search(short_action)
    else:
        allow_generic = False
    if not isinstance(view, str):
        ccode = parse_template(view, pjoin(folder, 'views'),
                               context=environment)
        restricted(ccode, environment, 'file stream')
    elif os.path.exists(path):
        x = view.replace('/', '.')
        files = ['views.%s.pyc' % x]
        if allow_generic:
            files.append('views.generic.%s.pyc' % request.extension)
        # for backward compatibility
        x = view.replace('/', '_')
        files.append('views_%s.pyc' % x)
        if allow_generic:
            files.append('views_generic.%s.pyc' % request.extension)
        if request.extension == 'html':
            files.append('views_%s.pyc' % x[:-5])
            if allow_generic:
                files.append('views_generic.pyc')
        # end backward compatibility code
        for f in files:
            filename = pjoin(path, f)
            if os.path.exists(filename):
                code = read_pyc(filename)
                restricted(code, environment, layer=filename)
                return
        raise HTTP(404,
                   rewrite.THREAD_LOCAL.routes.error_message % badv,
                   web2py_error=badv)
    else:
        filename = pjoin(folder, 'views', view)
        if not os.path.exists(filename) and allow_generic:
            view = 'generic.' + request.extension
            filename = pjoin(folder, 'views', view)
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badv,
                       web2py_error=badv)
        layer = filename
        if is_gae:
            ccode = getcfs(layer, filename,
                           lambda: compile2(parse_template(view,
                                            pjoin(folder, 'views'),
                                            context=environment), layer))
        else:
            ccode = parse_template(view,
                                   pjoin(folder, 'views'),
                                   context=environment)
        restricted(ccode, environment, layer)
Example #20
0
def verify_admin_password(password):
    _config = {}
    port = int(request.env.server_port or 0)
    restricted(read_file(apath('../parameters_%i.py' % port, request)), _config)
    return _config['password'] == CRYPT()(password)[0]
Example #21
0
def run_view_in(environment):
    """
    Executes the view for the requested action.
    The view is the one specified in `response.view` or determined by the url
    or `view/generic.extension`
    It tries the pre-compiled views_controller_function.pyc before compiling it.
    """
    request = current.request
    response = current.response
    view = environment['response'].view
    folder = request.folder
    path = pjoin(folder, 'compiled')
    badv = 'invalid view (%s)' % view
    patterns = response.get('generic_patterns')
    if patterns:
        regex = re_compile('|'.join(map(fnmatch.translate, patterns)))
        short_action = '%(controller)s/%(function)s.%(extension)s' % request
        allow_generic = regex.search(short_action)
    else:
        allow_generic = False
    if not isinstance(view, str):
        ccode = parse_template(view,
                               pjoin(folder, 'views'),
                               context=environment)
        restricted(ccode, environment, 'file stream')
    elif os.path.exists(path):
        x = view.replace('/', '.')
        files = ['views.%s.pyc' % x]
        if allow_generic:
            files.append('views.generic.%s.pyc' % request.extension)
        # for backward compatibility
        x = view.replace('/', '_')
        files.append('views_%s.pyc' % x)
        if allow_generic:
            files.append('views_generic.%s.pyc' % request.extension)
        if request.extension == 'html':
            files.append('views_%s.pyc' % x[:-5])
            if allow_generic:
                files.append('views_generic.pyc')
        # end backward compatibility code
        for f in files:
            filename = pjoin(path, f)
            if os.path.exists(filename):
                code = read_pyc(filename)
                restricted(code, environment, layer=filename)
                return
        raise HTTP(404,
                   rewrite.THREAD_LOCAL.routes.error_message % badv,
                   web2py_error=badv)
    else:
        filename = pjoin(folder, 'views', view)
        if not os.path.exists(filename) and allow_generic:
            view = 'generic.' + request.extension
            filename = pjoin(folder, 'views', view)
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badv,
                       web2py_error=badv)
        layer = filename
        if is_gae:
            ccode = getcfs(
                layer, filename, lambda: compile2(
                    parse_template(view,
                                   pjoin(folder, 'views'),
                                   context=environment), layer))
        else:
            ccode = parse_template(view,
                                   pjoin(folder, 'views'),
                                   context=environment)
        restricted(ccode, environment, layer)
Example #22
0
def run_view_in(environment):
    """
    Executes the view for the requested action.
    The view is the one specified in `response.view` or determined by the url
    or `view/generic.extension`
    It tries the pre-compiled views.controller.function.pyc before compiling it.
    """
    request = current.request
    response = current.response
    view = environment['response'].view
    folder = request.folder
    cpath = pjoin(folder, 'compiled')
    badv = 'invalid view (%s)' % view
    patterns = response.get('generic_patterns')
    layer = None
    if patterns:
        regex = re_compile('|'.join(map(fnmatch.translate, patterns)))
        short_action = '%(controller)s/%(function)s.%(extension)s' % request
        allow_generic = regex.search(short_action)
    else:
        allow_generic = False
    if not isinstance(view, str):
        ccode = parse_template(view, pjoin(folder, 'views'),
                               context=environment)
        layer = 'file stream'
    else:
        filename = pjoin(folder, 'views', view)
        if os.path.exists(cpath): # compiled views
            x = view.replace('/', '.')
            files = ['views.%s.pyc' % x]
            is_compiled = os.path.exists(pjoin(cpath, files[0]))
            # Don't use a generic view if the non-compiled view exists.
            if is_compiled or (not is_compiled and not os.path.exists(filename)):
                if allow_generic:
                    files.append('views.generic.%s.pyc' % request.extension)
                # for backward compatibility
                if request.extension == 'html':
                    files.append('views.%s.pyc' % x[:-5])
                    if allow_generic:
                        files.append('views.generic.pyc')
                # end backward compatibility code
                for f in files:
                    compiled = pjoin(cpath, f)
                    if os.path.exists(compiled):
                        ccode = getcfs(compiled, compiled, lambda: read_pyc(compiled))
                        layer = compiled
                        break
        if not os.path.exists(filename) and allow_generic:
            view = 'generic.' + request.extension
            filename = pjoin(folder, 'views', view)
        if not os.path.exists(filename):
            raise HTTP(404,
                       rewrite.THREAD_LOCAL.routes.error_message % badv,
                       web2py_error=badv)
        layer = filename
        # Compile the template
        ccode = parse_template(view,
                               pjoin(folder, 'views'),
                               context=environment)

    restricted(ccode, environment, layer=layer)
    # parse_template saves everything in response body
    return environment['response'].body.getvalue()
Example #23
0
def verify_admin_password(password):
    _config = {}
    port = int(request.env.server_port or 0)
    restricted(read_file(apath('../parameters_%i.py' % port, request)),
               _config)
    return _config['password'] == CRYPT()(password)[0]
Example #24
0
def run_view_in(environment):
    """
    Executes the view for the requested action.
    The view is the one specified in `response.view` or determined by the url
    or `view/generic.extension`
    It tries the pre-compiled views_controller_function.pyc before compiling it.
    """
    request = environment["request"]
    response = environment["response"]
    view = response.view
    folder = request.folder
    path = pjoin(folder, "compiled")
    badv = "invalid view (%s)" % view
    patterns = response.get("generic_patterns")
    if patterns:
        regex = re_compile("|".join(map(fnmatch.translate, patterns)))
        short_action = "%(controller)s/%(function)s.%(extension)s" % request
        allow_generic = regex.search(short_action)
    else:
        allow_generic = False
    if not isinstance(view, str):
        ccode = parse_template(view, pjoin(folder, "views"), context=environment)
        restricted(ccode, environment, "file stream")
    elif os.path.exists(path):
        x = view.replace("/", ".")
        files = ["views.%s.pyc" % x]
        if allow_generic:
            files.append("views.generic.%s.pyc" % request.extension)
        # for backward compatibility
        x = view.replace("/", "_")
        files.append("views_%s.pyc" % x)
        if allow_generic:
            files.append("views_generic.%s.pyc" % request.extension)
        if request.extension == "html":
            files.append("views_%s.pyc" % x[:-5])
            if allow_generic:
                files.append("views_generic.pyc")
        # end backward compatibility code
        for f in files:
            filename = pjoin(path, f)
            if os.path.exists(filename):
                code = read_pyc(filename)
                restricted(code, environment, layer=filename)
                return
        raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badv, web2py_error=badv)
    else:
        filename = pjoin(folder, "views", view)
        if not os.path.exists(filename) and allow_generic:
            view = "generic." + request.extension
            filename = pjoin(folder, "views", view)
        if not os.path.exists(filename):
            raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badv, web2py_error=badv)
        layer = filename
        if is_gae:
            ccode = getcfs(
                layer,
                filename,
                lambda: compile2(parse_template(view, pjoin(folder, "views"), context=environment), layer),
            )
        else:
            ccode = parse_template(view, pjoin(folder, "views"), context=environment)
        restricted(ccode, environment, layer)