def serve_controller(request, response, session): """ This function is used to generate a dynamic page. It first runs all models, then runs the function in the controller, and then tries to render the output using a view/template. this function must run from the [application] folder. A typical example would be the call to the url /[application]/[controller]/[function] that would result in a call to [function]() in applications/[application]/[controller].py rendered by applications/[application]/views/[controller]/[function].html """ # ################################################## # build environment for controller and view # ################################################## environment = build_environment(request, response, session) # set default view, controller can override it response.view = '%s/%s.%s' % (request.controller, request.function, request.extension) # also, make sure the flash is passed through # ################################################## # process models, controller and view (if required) # ################################################## run_models_in(environment) response._view_environment = copy.copy(environment) page = run_controller_in(request.controller, request.function, environment) if isinstance(page, dict): response._vars = page response._view_environment.update(page) page = run_view_in(response._view_environment) if not request.env.web2py_disable_garbage_collect: # logic to garbage collect after exec, not always, once every 100 requests global requests requests = ('requests' in globals()) and (requests + 1) % 100 or 0 if not requests: gc.collect() # end garbage collection logic # ################################################## # set default headers it not set # ################################################## default_headers = [ ('Content-Type', contenttype('.' + request.extension)), ('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'), ('Expires', time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())), ('Pragma', 'no-cache')] for key, value in default_headers: response.headers.setdefault(key, value) raise HTTP(response.status, page, **response.headers)
def build_web2py_environment(self): "build a namespace suitable for editor autocompletion and calltips" # warning: this can alter current global variable, use with care! try: from gluon.globals import Request, Response, Session from gluon.compileapp import build_environment, DAL request = Request({}) response = Response() session = Session() # fake request values request.folder = "" request.application = "welcome" request.controller = "default" request.function = "index" ns = build_environment(request, response, session) # fake common model objects db = ns["db"] = DAL("sqlite:memory") from gluon.tools import Auth, Crud, Service ns["auth"] = Auth(db) ns["crud"] = Crud(db) ns["service"] = Service() except Exception, e: traceback.print_exc() ns = {}
def build_web2py_environment(self): "build a namespace suitable for editor autocompletion and calltips" # warning: this can alter current global variable, use with care! try: from gluon.globals import Request, Response, Session from gluon.compileapp import build_environment, DAL request = Request() response = Response() session = Session() # fake request values request.folder = "" request.application = "welcome" request.controller = "default" request.function = "index" ns = build_environment( request, response, session, ) # fake common model objects db = ns['db'] = DAL("sqlite:memory") from gluon.tools import Auth, Crud, Service ns['auth'] = Auth(db) ns['crud'] = Crud(db) ns['service'] = Service() except Exception, e: print e ns = {}
def exec_environment( pyfile='', request=Request(), response=Response(), session=Session(), ): """ Environment builder and module loader. Builds a web2py environment and optionally executes a Python file into the environment. A Storage dictionary containing the resulting environment is returned. The working directory must be web2py root -- this is the web2py default. """ from gluon.compileapp import read_pyc if request.folder is None: mo = re.match(r'(|.*/)applications/(?P<appname>[^/]+)', pyfile) if mo: appname = mo.group('appname') request.folder = os.path.join('applications', appname) else: request.folder = '' env = build_environment(request, response, session) if pyfile: pycfile = pyfile + 'c' if os.path.isfile(pycfile): exec read_pyc(pycfile) in env else: execfile(pyfile, env) return Storage(env)
def serve_controller(request, response, session): """ This function is used to generate a dynamic page. It first runs all models, then runs the function in the controller, and then tries to render the output using a view/template. this function must run from the [application] folder. A typical example would be the call to the url /[application]/[controller]/[function] that would result in a call to [function]() in applications/[application]/[controller].py rendered by applications/[application]/views/[controller]/[function].html """ # ################################################## # build environment for controller and view # ################################################## environment = build_environment(request, response, session) # set default view, controller can override it response.view = '%s/%s.%s' % (request.controller, request.function, request.extension) # also, make sure the flash is passed through # ################################################## # process models, controller and view (if required) # ################################################## run_models_in(environment) response._view_environment = copy.copy(environment) page = run_controller_in(request.controller, request.function, environment) if isinstance(page, dict): response._vars = page response._view_environment.update(page) page = run_view_in(response._view_environment) if not request.env.web2py_disable_garbage_collect: # logic to garbage collect after exec, not always, once every 100 requests global requests requests = ('requests' in globals()) and (requests + 1) % 100 or 0 if not requests: gc.collect() # end garbage collection logic # ################################################## # set default headers it not set # ################################################## default_headers = [ ('Content-Type', contenttype('.' + request.extension)), ('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'), ('Expires', unlocalised_http_header_date(time.gmtime())), ('Pragma', 'no-cache') ] for key, value in default_headers: response.headers.setdefault(key, value) raise HTTP(response.status, page, **response.headers)
def env(a, import_models=False, c=None, f=None, dir="", extra_request={}): """ Return web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment. extra_request allows you to pass along any extra variables to the request object before your models get executed. This was mainly done to support web2py_utils.test_runner, however you can use it with any wrapper scripts that need access to the web2py environment. """ request = Request({}) response = Response() session = Session() request.application = a # Populate the dummy environment with sensible defaults. if not dir: request.folder = os.path.join("applications", a) else: request.folder = dir request.controller = c or "default" request.function = f or "index" response.view = "%s/%s.html" % (request.controller, request.function) request.env.http_host = "127.0.0.1:8000" request.env.remote_addr = "127.0.0.1" request.env.web2py_runtime_gae = global_settings.web2py_runtime_gae for k, v in extra_request.items(): request[k] = v path_info = "/%s/%s/%s" % (a, c, f) if request.args: path_info = "%s/%s" % (path_info, "/".join(request.args)) if request.vars: vars = ["%s=%s" % (k, v) if v else "%s" % k for (k, v) in request.vars.iteritems()] path_info = "%s?%s" % (path_info, "&".join(vars)) request.env.path_info = path_info # Monkey patch so credentials checks pass. def check_credentials(request, other_application="admin"): return True fileutils.check_credentials = check_credentials environment = build_environment(request, response, session) if import_models: try: run_models_in(environment) except RestrictedError, e: sys.stderr.write(e.traceback + "\n") sys.exit(1)
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, )
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, )
def env( a, import_models=False, c=None, f=None, dir='', ): """ Return web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the evironment. """ request = Request() response = Response() session = Session() request.application = a # Populate the dummy environment with sensible defaults. if not dir: request.folder = os.path.join('applications', a) else: request.folder = dir request.controller = c or 'default' request.function = f or 'index' response.view = '%s/%s.html' % (request.controller, request.function) request.env.path_info = '/%s/%s/%s' % (a, c, f) request.env.http_host = '127.0.0.1:8000' request.env.remote_addr = '127.0.0.1' # Monkey patch so credentials checks pass. def check_credentials(request, other_application='admin'): return True gluon.fileutils.check_credentials = check_credentials environment = build_environment(request, response, session) if import_models: run_models_in(environment) return environment
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, )
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, )
def exec_environment( pyfile='', request=None, response=None, session=None, ): """ .. function:: gluon.shell.exec_environment([pyfile=''[, request=Request() [, response=Response[, session=Session()]]]]) Environment builder and module loader. Builds a web2py environment and optionally executes a Python file into the environment. A Storage dictionary containing the resulting environment is returned. The working directory must be web2py root -- this is the web2py default. """ if request is None: request = Request({}) if response is None: response = Response() if session is None: session = Session() if request.folder is None: mo = re.match(r'(|.*/)applications/(?P<appname>[^/]+)', pyfile) if mo: appname = mo.group('appname') request.folder = os.path.join('applications', appname) else: request.folder = '' env = build_environment(request, response, session, store_current=False) if pyfile: pycfile = pyfile + 'c' if os.path.isfile(pycfile): exec read_pyc(pycfile) in env else: execfile(pyfile, env) return Storage(env)
def exec_environment( pyfile='', request=None, response=None, session=None, ): """Environment builder and module loader. Builds a web2py environment and optionally executes a Python file into the environment. A Storage dictionary containing the resulting environment is returned. The working directory must be web2py root -- this is the web2py default. """ if request is None: request = Request({}) if response is None: response = Response() if session is None: session = Session() if request.folder is None: mo = re.match(REGEX_APP_PATH, pyfile) if mo: a = mo.group('a') request.folder = os.path.abspath(os.path.join('applications', a)) else: request.folder = '' env = build_environment(request, response, session, store_current=False) if pyfile: pycfile = pyfile + 'c' if os.path.isfile(pycfile): exec(read_pyc(pycfile), env) else: execfile(pyfile, env) return Storage(env)
def cms_index(module, alt_function=None): """ Return a module index page retrieved from CMS - or run an alternate function if not found """ response = current.response settings = current.deployment_settings module_name = settings.modules[module].name_nice response.title = module_name item = None if settings.has_module("cms"): db = current.db table = current.s3db.cms_post ltable = db.cms_post_module query = (ltable.module == module) & \ (ltable.post_id == table.id) & \ (table.deleted != True) & \ ((ltable.resource == None) | \ (ltable.resource == "index")) _item = db(query).select(table.id, table.body, table.title, limitby=(0, 1)).first() # @ToDo: Replace this crude check with? #if current.auth.s3_has_permission("update", table, record_id=_item.id): auth = current.auth ADMIN = auth.get_system_roles().ADMIN ADMIN = auth.s3_has_role(ADMIN) if _item: if _item.title: response.title = _item.title if ADMIN: item = DIV( XML(_item.body), BR(), A(current.T("Edit"), _href=URL(c="cms", f="post", args=[_item.id, "update"], vars={"module": module}), _class="action-btn")) else: item = XML(_item.body) elif ADMIN: item = DIV( H2(module_name), A(current.T("Edit"), _href=URL(c="cms", f="post", args="create", vars={"module": module}), _class="action-btn")) if not item: if alt_function: # Serve the alternate controller function # Copied from gluon.main serve_controller() # (We don't want to re-run models) from gluon.compileapp import build_environment, run_controller_in, run_view_in request = current.request environment = build_environment(request, response, current.session) environment["settings"] = settings environment["s3db"] = current.s3db page = run_controller_in(request.controller, alt_function, environment) if isinstance(page, dict): response._vars = page response._view_environment.update(page) run_view_in(response._view_environment) page = response.body.getvalue() # Set default headers if not set default_headers = [ ("Content-Type", contenttype("." + request.extension)), ("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0" ), ("Expires", time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())), ("Pragma", "no-cache") ] for key, value in default_headers: response.headers.setdefault(key, value) raise HTTP(response.status, page, **response.headers) else: item = H2(module_name) # tbc report = "" response.view = "index.html" return dict(item=item, report=report) return None
def env( a, import_models=False, c=None, f=None, dir='', extra_request={}, ): """ Returns web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment. extra_request allows you to pass along any extra variables to the request object before your models get executed. This was mainly done to support web2py_utils.test_runner, however you can use it with any wrapper scripts that need access to the web2py environment. """ request = Request({}) response = Response() session = Session() request.application = a # Populate the dummy environment with sensible defaults. if not dir: request.folder = os.path.join('applications', a) else: request.folder = dir request.controller = c or 'default' request.function = f or 'index' response.view = '%s/%s.html' % (request.controller, request.function) if global_settings.cmd_options: ip = global_settings.cmd_options.ip port = global_settings.cmd_options.port request.is_shell = global_settings.cmd_options.shell is not None request.is_scheduler = global_settings.cmd_options.scheduler is not None else: ip, port = '127.0.0.1', '8000' request.env.http_host = '%s:%s' % (ip, port) request.env.remote_addr = '127.0.0.1' request.env.web2py_runtime_gae = global_settings.web2py_runtime_gae for k, v in extra_request.items(): request[k] = v path_info = '/%s/%s/%s' % (a, c, f) if request.args: path_info = '%s/%s' % (path_info, '/'.join(request.args)) if request.vars: vars = [ '%s=%s' % (k, v) if v else '%s' % k for (k, v) in request.vars.iteritems() ] path_info = '%s?%s' % (path_info, '&'.join(vars)) request.env.path_info = path_info # Monkey patch so credentials checks pass. def check_credentials(request, other_application='admin'): return True fileutils.check_credentials = check_credentials environment = build_environment(request, response, session) if import_models: try: run_models_in(environment) except RestrictedError, e: sys.stderr.write(e.traceback + '\n') sys.exit(1)
def cms_index(module, alt_function=None): """ Return a module index page retrieved from CMS - or run an alternate function if not found """ response = current.response settings = current.deployment_settings module_name = settings.modules[module].name_nice response.title = module_name item = None if settings.has_module("cms"): db = current.db table = current.s3db.cms_post ltable = db.cms_post_module query = (ltable.module == module) & \ (ltable.post_id == table.id) & \ (table.deleted != True) _item = db(query).select(table.id, table.body, limitby=(0, 1)).first() auth = current.auth ADMIN = auth.get_system_roles().ADMIN ADMIN = auth.s3_has_role(ADMIN) if _item: if ADMIN: item = DIV(XML(_item.body), BR(), A(current.T("Edit"), _href=URL(c="cms", f="post", args=[_item.id, "update"], vars={"module":module}), _class="action-btn")) else: item = XML(_item.body) elif ADMIN: item = DIV(H2(module_name), A(current.T("Edit"), _href=URL(c="cms", f="post", args="create", vars={"module":module}), _class="action-btn")) if not item: if alt_function: # Serve the alternate controller function # Copied from gluon.main serve_controller() # (We don't want to re-run models) from gluon.compileapp import build_environment, run_controller_in, run_view_in request = current.request environment = build_environment(request, response, current.session) environment["settings"] = settings page = run_controller_in(request.controller, alt_function, environment) if isinstance(page, dict): response._vars = page response._view_environment.update(page) run_view_in(response._view_environment) page = response.body.getvalue() # Set default headers if not set default_headers = [ ("Content-Type", contenttype("." + request.extension)), ("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"), ("Expires", time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())), ("Pragma", "no-cache")] for key, value in default_headers: response.headers.setdefault(key, value) raise HTTP(response.status, page, **response.headers) else: item = H2(module_name) # tbc report = "" response.view = "index.html" return dict(item=item, report=report) return None
def env( a, import_models=False, c=None, f=None, dir='', extra_request={}, ): """ Returns web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment. extra_request allows you to pass along any extra variables to the request object before your models get executed. This was mainly done to support web2py_utils.test_runner, however you can use it with any wrapper scripts that need access to the web2py environment. """ request = Request({}) response = Response() session = Session() request.application = a # Populate the dummy environment with sensible defaults. if not dir: request.folder = os.path.join('applications', a) else: request.folder = dir request.controller = c or 'default' request.function = f or 'index' response.view = '%s/%s.html' % (request.controller, request.function) if global_settings.cmd_options: ip = global_settings.cmd_options.ip port = global_settings.cmd_options.port request.is_shell = global_settings.cmd_options.shell is not None request.is_scheduler = global_settings.cmd_options.scheduler is not None else: ip, port = '127.0.0.1', '8000' request.env.http_host = '%s:%s' % (ip, port) request.env.remote_addr = '127.0.0.1' request.env.web2py_runtime_gae = global_settings.web2py_runtime_gae for k, v in extra_request.items(): request[k] = v path_info = '/%s/%s/%s' % (a, c, f) if request.args: path_info = '%s/%s' % (path_info, '/'.join(request.args)) if request.vars: vars = ['%s=%s' % (k, v) if v else '%s' % k for (k, v) in request.vars.iteritems()] path_info = '%s?%s' % (path_info, '&'.join(vars)) request.env.path_info = path_info # Monkey patch so credentials checks pass. def check_credentials(request, other_application='admin'): return True fileutils.check_credentials = check_credentials environment = build_environment(request, response, session) if import_models: try: run_models_in(environment) except RestrictedError, e: sys.stderr.write(e.traceback + '\n') sys.exit(1)