Example #1
0
def sim_request():
    """Return test request."""
    request = Request()
    request.application = 'app'
    request.controller = 'cont'
    request.function = 'func'
    return request
Example #2
0
    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt'), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(first_name='Bart',
                                 last_name='Simpson',
                                 username='******',
                                 email='*****@*****.**',
                                 password='******',
                                 registration_key=None,
                                 registration_id=None)

        self.db.commit()
Example #3
0
    def setUp(self):
        request = Request(env={})
        request.application = "a"
        request.controller = "c"
        request.function = "f"
        request.folder = "applications/admin"
        response = Response()
        session = Session()
        T = translator("", "en")
        session.connect(request, response)
        from gluon.globals import current

        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=["all"])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table("t0", Field("tt"), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(
            first_name="Bart",
            last_name="Simpson",
            username="******",
            email="*****@*****.**",
            password="******",
            registration_key=None,
            registration_id=None,
        )

        self.db.commit()
Example #4
0
    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 setUp(self):
        global request, session, auth
        request = Request(globals())  # Use a clean Request object
        request.application = 'runestone'
        session = Session()
        auth = Auth(db, hmac_key=Auth.get_or_create_key())
        # bring in the ajax controllers
        exec(compile(open("applications/runestone/controllers/ajax.py").read(), "applications/runestone/controllers/ajax.py", 'exec'), globals())

        # Create a default user and course.
        self.course_name_1 = 'test_course_1'
        self.course_id_1 = self.createCourse(self.course_name_1)
        self.user_name_1 = 'test_user_1'
        self.user_id_1 = self.createUser(self.user_name_1, self.course_id_1)
Example #6
0
    def setUp(self):
        global request, session, auth
        request = Request(globals())  # Use a clean Request object
        request.application = 'runestone'
        session = Session()
        auth = Auth(db, hmac_key=Auth.get_or_create_key())
        # bring in the ajax controllers
        execfile("applications/runestone/controllers/ajax.py", globals())

        # Create a default user and course.
        self.course_name_1 = 'test_course_1'
        self.course_id_1 = self.createCourse(self.course_name_1)
        self.user_name_1 = 'test_user_1'
        self.user_id_1 = self.createUser(self.user_name_1, self.course_id_1)
Example #7
0
    def app_new(self, name):
        # Fake a request
        from gluon.admin import app_create
        from gluon.globals import Request
        request = Request()
        request.folder = opj(self.w2p_path, 'applications', 'admin')

        ret = app_create(name, request)
        if ret:
            self.tree.rebuild_tree()
            return ret
        import errno
        raise IOError(errno.ENOENT, "'welcome.w2p' probably missing",
                opj(self.w2p_path, 'welcome.w2p'))
Example #8
0
def setup_clean_session():
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        return current
Example #9
0
def initVars():
	global current, request, response, session, cache, T
	current.request = request = Request()
	current.response = response = Response()
	current.session = session = Session()
	current.cache = cache = Cache(request)
	current.T = T = m__T__
Example #10
0
    def test__server_production_mode(self):
        default = '_test__server_production_mode_'

        # Test that environment is prepared properly.
        self.assertTrue('SERVER_PRODUCTION_MODE' in os.environ)
        self.assertTrue('MYSQL_TCP_PORT' in os.environ)

        request = Request(globals())
        if 'SERVER_PRODUCTION_MODE' in os.environ:
            del os.environ['SERVER_PRODUCTION_MODE']
        self.assertRaises(ServerEnvironmentError, server_production_mode,
                request)

        request.env.server_production_mode = default
        self.assertRaises(ServerEnvironmentError, server_production_mode,
                request)

        request.env.http_host = '_something_'   # Anything but '127.0.0.1:8000'
        self.assertEqual(server_production_mode(request), default)

        request.env.server_production_mode = None
        request.env.http_host = '127.0.0.1:8000'
        self.assertRaises(ServerEnvironmentError, server_production_mode,
                request)

        os.environ['SERVER_PRODUCTION_MODE'] = default
        self.assertEqual(server_production_mode(request), default)
Example #11
0
    def setUp(self):
        # Load the to-be-tested file
        execfile("applications/vidjil/controllers/patient.py", globals())
        # set up default session/request/auth/...
        global response, session, request, auth
        session = Session()
        request = Request({})
        auth = VidjilAuth(globals(), db)
        auth.login_bare("*****@*****.**", "1234")

        # rewrite info / error functions
        # for some reasons we lost them between the testRunner and the testCase but we need them to avoid error so ...
        def f(a, **kwargs):
            pass

        log.info = f
        log.error = f
        log.debug = f

        # for defs
        current.db = db
        current.auth = auth

        auth.add_permission(group_id, 'admin', db.patient, 0)
        auth.add_permission(group_id, 'read', db.patient, 0)
        auth.add_permission(group_id, 'create', db.patient, 0)
 def setUp(self):
     self.request = Request(env={})
     self.request.application = 'a'
     self.request.controller = 'c'
     self.request.function = 'f'
     self.request.folder = 'applications/admin'
     self.response = Response()
     self.session = Session()
     T = translator('', 'en')
     self.session.connect(self.request, self.response)
     from gluon.globals import current
     self.current = current
     self.current.request = self.request
     self.current.response = self.response
     self.current.session = self.session
     self.current.T = T
     self.db = DAL(DEFAULT_URI, check_reserved=['all'])
     self.auth = AuthAPI(self.db)
     self.auth.define_tables(username=True, signature=False)
     # Create a user
     self.auth.table_user().validate_and_insert(first_name='Bart',
                                                last_name='Simpson',
                                                username='******',
                                                email='*****@*****.**',
                                                password='******',
                                                registration_key='',
                                                registration_id='')
     self.db.commit()
Example #13
0
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)
Example #14
0
    def testRun(self):
        # setup
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        db = DAL(DEFAULT_URI, check_reserved=['all'])
        auth = Auth(db)
        auth.define_tables(username=True, signature=False)
        self.assertTrue('auth_user' in db)
        self.assertTrue('auth_group' in db)
        self.assertTrue('auth_membership' in db)
        self.assertTrue('auth_permission' in db)
        self.assertTrue('auth_event' in db)
        db.define_table('t0', Field('tt'), auth.signature)
        auth.enable_record_versioning(db)
        self.assertTrue('t0_archive' in db)
        for f in ['login', 'register', 'retrieve_password',
                  'retrieve_username']:
            html_form = getattr(auth, f)().xml()
            self.assertTrue('name="_formkey"' in html_form)

        for f in ['logout', 'verify_email', 'reset_password',
                  'change_password', 'profile', 'groups']:
            self.assertRaisesRegexp(HTTP, "303*", getattr(auth, f))

        self.assertRaisesRegexp(HTTP, "401*", auth.impersonate)

        try:
            for t in ['t0_archive', 't0', 'auth_cas', 'auth_event',
                      'auth_membership', 'auth_permission', 'auth_group',
                      'auth_user']:
                db[t].drop()
        except SyntaxError as e:
            # GAE doesn't support drop
            pass
        return
 def setUp(self):
     global request
     request = Request(globals())  # Use a clean Request object
     exec(
         compile(
             open("applications/runestone/controllers/assignments.py").read(
             ), "applications/runestone/controllers/assignments.py",
             'exec'), globals())
Example #16
0
def env(app, dir='', nomodel=False):
    import gluon.html as html
    import gluon.validators as validators
    from gluon.http import HTTP, redirect
    from gluon.languages import translator
    from gluon.cache import Cache
    from gluon.globals import Request, Response, Session
    from gluon.sql import SQLDB, SQLField
    from gluon.sqlhtml import SQLFORM, SQLTABLE

    request=Request()
    response=Response()
    session=Session()
    
    if not dir:
        request.folder = os.path.join('applications', app)
    else:
        request.folder = dir
        
    environment={}
    for key in html.__all__: environment[key]=eval('html.%s' % key)
    for key in validators.__all__: environment[key]=eval('validators.%s' % key)
    environment['T']=translator(request)
    environment['HTTP']=HTTP
    environment['redirect']=redirect
    environment['request']=request
    environment['response']=response
    environment['session']=session
    environment['cache']=Cache(request)
    environment['SQLDB']=SQLDB
    SQLDB._set_thread_folder(os.path.join(request.folder,'databases'))
    environment['SQLField']=SQLField
    environment['SQLFORM']=SQLFORM
    environment['SQLTABLE']=SQLTABLE
    
    if not nomodel:
        model_path = os.path.join(request.folder,'models', '*.py')
        from glob import glob
        for f in glob(model_path):
            fname, ext = os.path.splitext(f)
            execfile(f, environment)
#            print 'Imported "%s" model file' % fname
    
    return environment
Example #17
0
 def OnMenuAppNew(self, evt):
     if not self.panel:
         if not self.ChooseApp():
             return
     p = None
     dlg = wx.TextEntryDialog(self, 'App name', 'App name', '')
     if dlg.ShowModal() == wx.ID_OK:
         p = dlg.GetValue().strip()
     dlg.Destroy()
     if p:
         from gluon.admin import app_create
         from gluon.globals import Request
         request = Request()
         request.folder = opj(self.w2p_path, 'applications', 'admin')
         ret = app_create(p, request)
         if not ret:
             wx.MessageDialog(self, 'Could not create app %s' % p, "error").ShowModal()
         else:
             self.panel.tree.rebuild_tree()
 def setUp(self):
     global request, session, auth
     request = Request(globals())  # Use a clean Request object
     session = Session()
     auth = Auth(db, hmac_key=Auth.get_or_create_key())
     exec(
         compile(
             open("applications/runestone/controllers/dashboard.py").read(),
             "applications/runestone/controllers/dashboard.py", 'exec'),
         globals())
Example #19
0
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)
Example #20
0
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)
Example #21
0
 def test_admin_compile(self):
     #apps = ['welcome', 'admin', 'examples']
     request = Request(env={})
     request.application = 'a'
     request.controller = 'c'
     request.function = 'f'
     request.folder = 'applications/admin'
     apps = ['welcome']
     for appname in apps:
         appname_path = os.path.join(os.getcwd(), 'applications', appname)
         self.assertEqual(app_compile(appname_path, request), None)
         # remove any existing test_app
         new_app = 'test_app_%s' % (appname)
         if(os.path.exists('applications/%s' % (new_app))):
             shutil.rmtree('applications/%s' % (new_app))
         self.assertEqual(app_create(new_app, request), True)
         self.assertEqual(os.path.exists('applications/test_app_%s/controllers/default.py' % (appname)), True)
         self.assertEqual(app_cleanup(new_app, request), True)
         self.assertEqual(app_uninstall(new_app, request), True)
     self.assertNotEqual(check_new_version(global_settings.web2py_version, WEB2PY_VERSION_URL), -1)
     return
Example #22
0
    def test_restful_simple(self):
        env = {'request_method': 'GET', 'PATH_INFO': '/welcome/default/index/1.pdf'}
        r = Request(env)
        regex_url_in(r, env)

        @r.restful()
        def simple_rest():
            def GET(*args, **vars):
                return args[0]
            return locals()

        self.assertEqual(simple_rest(), '1')
Example #23
0
    def test_restful_calls_post(self):
        env = {'request_method': 'POST', 'PATH_INFO': '/welcome/default/index'}
        r = Request(env)
        regex_url_in(r, env)

        @r.restful()
        def post_rest():
            def POST(*args, **vars):
                return 'I posted'
            return locals()

        self.assertEqual(post_rest(), 'I posted')
Example #24
0
    def test_restful_ignore_extension(self):
        env = {'request_method': 'GET', 'PATH_INFO': '/welcome/default/index/127.0.0.1'}
        r = Request(env)
        regex_url_in(r, env)

        @r.restful(ignore_extension=True)
        def ignore_rest():
            def GET(*args, **vars):
                return args[0]
            return locals()

        self.assertEqual(ignore_rest(), '127.0.0.1')
Example #25
0
 def test_admin_compile(self):
     #apps = ['welcome', 'admin', 'examples']
     request = Request(env={})
     request.application = 'a'
     request.controller = 'c'
     request.function = 'f'
     request.folder = 'applications/admin'
     apps = ['welcome']
     for appname in apps:
         appname_path = os.path.join(os.getcwd(), 'applications', appname)
         self.assertEqual(app_compile(appname_path, request), None)
         # remove any existing test_app
         new_app = 'test_app_%s' % (appname)
         if (os.path.exists('applications/%s' % (new_app))):
             shutil.rmtree('applications/%s' % (new_app))
         self.assertEqual(app_create(new_app, request), True)
         self.assertEqual(
             os.path.exists(
                 'applications/test_app_%s/controllers/default.py' %
                 (appname)), True)
         self.assertEqual(app_cleanup(new_app, request), True)
         self.assertEqual(app_uninstall(new_app, request), True)
     self.assertNotEqual(
         check_new_version(global_settings.web2py_version,
                           WEB2PY_VERSION_URL), -1)
     return
Example #26
0
 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 = {}
Example #27
0
 def setUp(self):
     from gluon.globals import Request, Response, Session, current
     from gluon.html import A, DIV, FORM, MENU, TABLE, TR, INPUT, URL, XML
     from gluon.html import ASSIGNJS
     from gluon.validators import IS_NOT_EMPTY
     from gluon.compileapp import LOAD
     from gluon.http import HTTP, redirect
     from gluon.tools import Auth
     from gluon.sql import SQLDB
     from gluon.sqlhtml import SQLTABLE, SQLFORM
     self.original_check_credentials = fileutils.check_credentials
     fileutils.check_credentials = fake_check_credentials
     request = Request(env={})
     request.application = 'welcome'
     request.controller = 'appadmin'
     request.function = self._testMethodName.split('_')[1]
     request.folder = 'applications/welcome'
     request.env.http_host = '127.0.0.1:8000'
     request.env.remote_addr = '127.0.0.1'
     response = Response()
     session = Session()
     T = TranslatorFactory('', 'en')
     session.connect(request, response)
     current.request = request
     current.response = response
     current.session = session
     current.T = T
     db = DAL(DEFAULT_URI, check_reserved=['all'])
     auth = Auth(db)
     auth.define_tables(username=True, signature=False)
     db.define_table('t0', Field('tt'), auth.signature)
     # Create a user
     db.auth_user.insert(first_name='Bart',
                         last_name='Simpson',
                         username='******',
                         email='*****@*****.**',
                         password='******',
                         registration_key=None,
                         registration_id=None)
     self.env = locals()
Example #28
0
    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt'), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(first_name='Bart',
                                 last_name='Simpson',
                                 username='******',
                                 email='*****@*****.**',
                                 password='******',
                                 registration_key=None,
                                 registration_id=None)

        self.db.commit()
Example #29
0
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)
Example #30
0
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)
Example #31
0
    def testRun(self):
        # setup
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        db = DAL(DEFAULT_URI, check_reserved=['all'])
        auth = Auth(db)
        auth.define_tables(username=True, signature=False)
        self.assertTrue('auth_user' in db)
        self.assertTrue('auth_group' in db)
        self.assertTrue('auth_membership' in db)
        self.assertTrue('auth_permission' in db)
        self.assertTrue('auth_event' in db)
        db.define_table('t0', Field('tt'), auth.signature)
        auth.enable_record_versioning(db)
        self.assertTrue('t0_archive' in db)
        for f in [
                'login', 'register', 'retrieve_password', 'retrieve_username'
        ]:
            html_form = getattr(auth, f)().xml()
            self.assertTrue('name="_formkey"' in html_form)

        for f in [
                'logout', 'verify_email', 'reset_password', 'change_password',
                'profile', 'groups'
        ]:
            self.assertRaisesRegexp(HTTP, "303*", getattr(auth, f))

        self.assertRaisesRegexp(HTTP, "401*", auth.impersonate)

        try:
            for t in [
                    't0_archive', 't0', 'auth_cas', 'auth_event',
                    'auth_membership', 'auth_permission', 'auth_group',
                    'auth_user'
            ]:
                db[t].drop()
        except SyntaxError as e:
            # GAE doesn't support drop
            pass
        return
Example #32
0
    def setUp(self):
        # Load the to-be-tested file
        execfile("applications/vidjil/controllers/admin.py", globals())

        # Set up default session/request/auth/...
        global response, session, request, auth
        session = Session()
        request = Request([])
        auth = VidjilAuth(globals(), db)
        auth.login_bare("*****@*****.**", "1234")

        # rewrite info / error functions
        # for some reasons we lost them between the testRunner and the testCase but we need them to avoid error so ...
        def f(a, **kwargs):
            pass

        log.info = f
        log.error = f
        log.debug = f
Example #33
0
def setup_clean_session():
    request = Request(env={})
    request.application = 'a'
    request.controller = 'c'
    request.function = 'f'
    request.folder = 'applications/admin'
    response = Response()
    session = Session()
    session.connect(request, response)
    from gluon.globals import current
    current.request = request
    current.response = response
    current.session = session
    return current
Example #34
0
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 test_admin_compile(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        # remove any existing test app
        app_path = os.path.join('applications', test_app2_name)
        if os.path.exists(app_path):
            shutil.rmtree(app_path)

        self.assertTrue(app_create(test_app2_name, request))
        self.assertTrue(os.path.exists('applications/%s/controllers/default.py' % test_app2_name))
        self.assertIsNone(app_compile(test_app2_name, request))
        self.assertTrue(app_cleanup(test_app2_name, request))
        self.assertTrue(app_uninstall(test_app2_name, request))
Example #36
0
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
Example #37
0
 def setUp(self):
     request = Request(env={})
     request.application = 'a'
     request.controller = 'c'
     request.function = 'f'
     request.folder = 'applications/admin'
     response = Response()
     session = Session()
     session.connect(request, response)
     from gluon.globals import current
     current.request = request
     current.response = response
     current.session = session
     self.current = current
     rconn = RConn(host='localhost')
     self.db = RedisSession(redis_conn=rconn, session_expiry=False)
     self.tname = 'testtablename'
     return current
 def setUp(self):
     from gluon.globals import Request, Response, Session, current
     from gluon.html import A, DIV, FORM, MENU, TABLE, TR, INPUT, URL, XML
     from gluon.html import ASSIGNJS
     from gluon.validators import IS_NOT_EMPTY
     from gluon.compileapp import LOAD
     from gluon.http import HTTP, redirect
     from gluon.tools import Auth
     from gluon.sql import SQLDB
     from gluon.sqlhtml import SQLTABLE, SQLFORM
     self.original_check_credentials = fileutils.check_credentials
     fileutils.check_credentials = fake_check_credentials
     request = Request(env={})
     request.application = 'welcome'
     request.controller = 'appadmin'
     request.function = self._testMethodName.split('_')[1]
     request.folder = 'applications/welcome'
     request.env.http_host = '127.0.0.1:8000'
     request.env.remote_addr = '127.0.0.1'
     response = Response()
     session = Session()
     T = translator('', 'en')
     session.connect(request, response)
     current.request = request
     current.response = response
     current.session = session
     current.T = T
     db = DAL(DEFAULT_URI, check_reserved=['all'])
     auth = Auth(db)
     auth.define_tables(username=True, signature=False)
     db.define_table('t0', Field('tt'), auth.signature)
     # Create a user
     db.auth_user.insert(first_name='Bart',
                         last_name='Simpson',
                         username='******',
                         email='*****@*****.**',
                         password='******',
                         registration_key=None,
                         registration_id=None)
     self.env = locals()
# Copyright 2011 - Thomas Bellembois [email protected]
# Cecill licence, see LICENSE
# $Id: chimitheque_ide_autocomplete.py 194 2015-02-23 16:27:16Z tbellemb $
# -*- coding: utf-8 -*-
if False:
    #
    # never imported - just for IDE autocompletion
    #
    from gluon import DAL
    db = DAL()
    from gluon import settings
    from gluon.cache import Cache
    from gluon.dal import Field
    from gluon.globals import Request
    request = Request()
    from gluon.globals import Response
    response = Response()
    from gluon.globals import Session
    session = Session()
    from gluon.html import *
    from gluon.http import HTTP
    from gluon.http import redirect
    from gluon.languages import translator
    T = translator(request)
    from gluon.sqlhtml import SQLFORM
    from gluon.tools import Auth
    auth = Auth()
    from gluon.tools import Crud, Mail
    from gluon.validators import *
    import sys
    mail = Mail()
Example #40
0
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)
Example #41
0
 def setUp(self):
     global request, session, auth
     request = Request(globals())  # Use a clean Request object
     session = Session()
     auth = Auth(db, hmac_key=Auth.get_or_create_key())
     execfile("applications/runestone/controllers/admin.py", globals())
Example #42
0
 def setUp(self):
     global request
     request = Request(globals())  # Use a clean Request object
     execfile("applications/runestone/controllers/assignments.py",
              globals())
Example #43
0
def env(app, dir='', nomodel=False):
    import gluon.html as html
    import gluon.validators as validators
    from gluon.http import HTTP, redirect
    from gluon.languages import translator
    from gluon.cache import Cache
    from gluon.globals import Request, Response, Session
    from gluon.sqlhtml import SQLFORM, SQLTABLE
    from gluon.dal import BaseAdapter, SQLDB, SQLField, DAL, Field
    from gluon.compileapp import local_import_aux, LoadFactory
    
    request=Request()
    response=Response()
    session=Session()
    
    if not dir:
        request.folder = os.path.join('applications', app)
    else:
        request.folder = dir
        
    environment={}
#    for key in html.__all__: environment[key]=eval('html.%s' % key)
#    for key in validators.__all__: environment[key]=eval('validators.%s' % key)
    for key in html.__all__:
        environment[key] = getattr(html, key)
    for key in validators.__all__:
        environment[key] = getattr(validators, key)
    global __builtins__
    environment['__builtins__'] = __builtins__
    environment['T']=translator(request)
#    environment['HTTP']=HTTP
#    environment['redirect']=redirect
#    environment['request']=request
#    environment['response']=response
#    environment['session']=session
#    environment['cache']=Cache(request)
#    environment['SQLDB']=SQLDB
#    SQLDB._set_thread_folder(os.path.join(request.folder,'databases'))
#    environment['SQLField']=SQLField
#    environment['SQLFORM']=SQLFORM
#    environment['SQLTABLE']=SQLTABLE
#    
#    if not nomodel:
#        model_path = os.path.join(request.folder,'models', '*.py')
#        from glob import glob
#        for f in glob(model_path):
#            fname, ext = os.path.splitext(f)
#            execfile(f, environment)
##            print 'Imported "%s" model file' % fname

    environment['HTTP'] = HTTP
    environment['redirect'] = redirect
    environment['request'] = request
    environment['response'] = response
    environment['session'] = session
    environment['DAL'] = DAL
    environment['Field'] = Field
    environment['SQLDB'] = SQLDB        # for backward compatibility
    environment['SQLField'] = SQLField  # for backward compatibility
    environment['SQLFORM'] = SQLFORM
    environment['SQLTABLE'] = SQLTABLE
    environment['LOAD'] = LoadFactory(environment)
    environment['local_import'] = \
        lambda name, reload=False, app=request.application:\
        local_import_aux(name,reload,app)
    BaseAdapter.set_folder(os.path.join(request.folder, 'databases'))
    response._view_environment = copy.copy(environment)
    
    return environment
Example #44
0
web2py_environment["load_module"] = load_module
web2py_env_module = ModuleType("web2py_env")
web2py_env_module.__dict__.update(web2py_environment)
sys.modules["web2py_env"] = web2py_env_module


application_name = request.application
application_folder_path = os.path.join("applications",application_name)

application = application_name
controller = "controller"
function = "function"
folder = os.path.join(os.getcwd(), "applications", application_name)

web2py_environment["Request"] = Request
request = Request()
request.application = application
request.controller = controller
request.function = function
request.folder = folder

web2py_environment["request"] = request
current.request = request

controller_configuration = OrderedDict()
for controller_name in ["default"]+glob.glob(
    os.path.join(application_folder_path, "controllers", "*.py")
):
    controller_configuration[controller_name] = Storage(
        name_nice = controller_name,
        description = controller_name,
Example #45
0
def env(app, dir='', nomodel=False):
    import gluon.html as html
    import gluon.validators as validators
    from gluon.http import HTTP, redirect
    from gluon.languages import translator
    from gluon.cache import Cache
    from gluon.globals import Request, Response, Session
    from gluon.sqlhtml import SQLFORM, SQLTABLE
    from gluon.dal import BaseAdapter, SQLDB, SQLField, DAL, Field
    from gluon.compileapp import local_import_aux, LoadFactory

    request = Request()
    response = Response()
    session = Session()

    if not dir:
        request.folder = os.path.join('applications', app)
    else:
        request.folder = dir

    environment = {}
    #    for key in html.__all__: environment[key]=eval('html.%s' % key)
    #    for key in validators.__all__: environment[key]=eval('validators.%s' % key)
    for key in html.__all__:
        environment[key] = getattr(html, key)
    for key in validators.__all__:
        environment[key] = getattr(validators, key)
    global __builtins__
    environment['__builtins__'] = __builtins__
    environment['T'] = translator(request)
    #    environment['HTTP']=HTTP
    #    environment['redirect']=redirect
    #    environment['request']=request
    #    environment['response']=response
    #    environment['session']=session
    #    environment['cache']=Cache(request)
    #    environment['SQLDB']=SQLDB
    #    SQLDB._set_thread_folder(os.path.join(request.folder,'databases'))
    #    environment['SQLField']=SQLField
    #    environment['SQLFORM']=SQLFORM
    #    environment['SQLTABLE']=SQLTABLE
    #
    #    if not nomodel:
    #        model_path = os.path.join(request.folder,'models', '*.py')
    #        from glob import glob
    #        for f in glob(model_path):
    #            fname, ext = os.path.splitext(f)
    #            execfile(f, environment)
    ##            print 'Imported "%s" model file' % fname

    environment['HTTP'] = HTTP
    environment['redirect'] = redirect
    environment['request'] = request
    environment['response'] = response
    environment['session'] = session
    environment['DAL'] = DAL
    environment['Field'] = Field
    environment['SQLDB'] = SQLDB  # for backward compatibility
    environment['SQLField'] = SQLField  # for backward compatibility
    environment['SQLFORM'] = SQLFORM
    environment['SQLTABLE'] = SQLTABLE
    environment['LOAD'] = LoadFactory(environment)
    environment['local_import'] = \
        lambda name, reload=False, app=request.application:\
        local_import_aux(name,reload,app)
    BaseAdapter.set_folder(os.path.join(request.folder, 'databases'))
    response._view_environment = copy.copy(environment)

    return environment
Example #46
0
def wsgibase(environ, responder):
    """
    this is the gluon wsgi application. the first function called when a page
    is requested (static or dynamic). it can be called by paste.httpserver
    or by apache mod_wsgi.

      - fills request with info
      - the environment variables, replacing '.' with '_'
      - adds web2py path and version info
      - compensates for fcgi missing path_info and query_string
      - validates the path in url

    The url path must be either:

    1. for static pages:

      - /<application>/static/<file>

    2. for dynamic pages:

      - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>]
      - (sub may go several levels deep, currently 3 levels are supported:
         sub1/sub2/sub3)

    The naming conventions are:

      - application, controller, function and extension may only contain
        [a-zA-Z0-9_]
      - file and sub may also contain '-', '=', '.' and '/'
    """
    eget = environ.get
    current.__dict__.clear()
    request = Request(environ)
    response = Response()
    session = Session()
    env = request.env
    #env.web2py_path = global_settings.applications_parent
    env.web2py_version = web2py_version
    #env.update(global_settings)
    static_file = False
    try:
        try:
            try:
                # ##################################################
                # handle fcgi missing path_info and query_string
                # select rewrite parameters
                # rewrite incoming URL
                # parse rewritten header variables
                # parse rewritten URL
                # serve file if static
                # ##################################################

                fixup_missing_path_info(environ)
                (static_file, version, environ) = url_in(request, environ)
                response.status = env.web2py_status_code or response.status

                if static_file:
                    if eget('QUERY_STRING', '').startswith('attachment'):
                        response.headers['Content-Disposition'] \
                            = 'attachment'
                    if version:
                        response.headers['Cache-Control'] = 'max-age=315360000'
                        response.headers[
                            'Expires'] = 'Thu, 31 Dec 2037 23:59:59 GMT'
                    response.stream(static_file, request=request)


                # ##################################################
                # fill in request items
                # ##################################################
                app = request.application  # must go after url_in!

                if not global_settings.local_hosts:
                    local_hosts = set(['127.0.0.1', '::ffff:127.0.0.1', '::1'])
                    if not global_settings.web2py_runtime_gae:
                        try:
                            fqdn = socket.getfqdn()
                            local_hosts.add(socket.gethostname())
                            local_hosts.add(fqdn)
                            local_hosts.update([
                                addrinfo[4][0] for addrinfo
                                in getipaddrinfo(fqdn)])
                            if env.server_name:
                                local_hosts.add(env.server_name)
                                local_hosts.update([
                                        addrinfo[4][0] for addrinfo
                                        in getipaddrinfo(env.server_name)])
                        except (socket.gaierror, TypeError):
                            pass
                    global_settings.local_hosts = list(local_hosts)
                else:
                    local_hosts = global_settings.local_hosts
                client = get_client(env)
                x_req_with = str(env.http_x_requested_with).lower()

                request.update(
                    client = client,
                    folder = abspath('applications', app) + os.sep,
                    ajax = x_req_with == 'xmlhttprequest',
                    cid = env.http_web2py_component_element,
                    is_local = env.remote_addr in local_hosts,
                    is_https = env.wsgi_url_scheme in HTTPS_SCHEMES or \
                        request.env.http_x_forwarded_proto in HTTPS_SCHEMES \
                        or env.https == 'on'
                    )
                request.compute_uuid()  # requires client
                request.url = environ['PATH_INFO']

                # ##################################################
                # access the requested application
                # ##################################################

                disabled = pjoin(request.folder, 'DISABLED')
                if not exists(request.folder):
                    if app == rwthread.routes.default_application \
                            and app != 'welcome':
                        redirect(URL('welcome', 'default', 'index'))
                    elif rwthread.routes.error_handler:
                        _handler = rwthread.routes.error_handler
                        redirect(URL(_handler['application'],
                                     _handler['controller'],
                                     _handler['function'],
                                     args=app))
                    else:
                        raise HTTP(404, rwthread.routes.error_message
                                   % 'invalid request',
                                   web2py_error='invalid application')
                elif not request.is_local and exists(disabled):
                    raise HTTP(503, "<html><body><h1>Temporarily down for maintenance</h1></body></html>")

                # ##################################################
                # build missing folders
                # ##################################################

                create_missing_app_folders(request)

                # ##################################################
                # get the GET and POST data
                # ##################################################

                #parse_get_post_vars(request, environ)

                # ##################################################
                # expose wsgi hooks for convenience
                # ##################################################

                request.wsgi = LazyWSGI(environ, request, response)

                # ##################################################
                # load cookies
                # ##################################################

                if env.http_cookie:
                    try:
                        request.cookies.load(env.http_cookie)
                    except Cookie.CookieError, e:
                        pass  # invalid cookies

                # ##################################################
                # try load session or create new session file
                # ##################################################

                if not env.web2py_disable_session:
                    session.connect(request, response)

                # ##################################################
                # run controller
                # ##################################################

                if global_settings.debugging and app != "admin":
                    import gluon.debug
                    # activate the debugger
                    gluon.debug.dbg.do_debug(mainpyfile=request.folder)

                serve_controller(request, response, session)

            except HTTP, http_response:

                if static_file:
                    return http_response.to(responder, env=env)

                if request.body:
                    request.body.close()

                if hasattr(current,'request'):

                    # ##################################################
                    # on success, try store session in database
                    # ##################################################
                    session._try_store_in_db(request, response)

                    # ##################################################
                    # on success, commit database
                    # ##################################################

                    if response.do_not_commit is True:
                        BaseAdapter.close_all_instances(None)
                    elif response.custom_commit:
                        BaseAdapter.close_all_instances(response.custom_commit)
                    else:
                        BaseAdapter.close_all_instances('commit')

                    # ##################################################
                    # if session not in db try store session on filesystem
                    # this must be done after trying to commit database!
                    # ##################################################

                    session._try_store_in_cookie_or_file(request, response)

                    # Set header so client can distinguish component requests.
                    if request.cid:
                        http_response.headers.setdefault(
                            'web2py-component-content', 'replace')

                    if request.ajax:
                        if response.flash:
                            http_response.headers['web2py-component-flash'] = \
                                urllib2.quote(xmlescape(response.flash)\
                                                  .replace('\n',''))
                        if response.js:
                            http_response.headers['web2py-component-command'] = \
                                urllib2.quote(response.js.replace('\n',''))

                    # ##################################################
                    # store cookies in headers
                    # ##################################################

                    session._fixup_before_save()
                    http_response.cookies2headers(response.cookies)

                ticket = None

            except RestrictedError, e:

                if request.body:
                    request.body.close()

                # ##################################################
                # on application error, rollback database
                # ##################################################

                # log tickets before rollback if not in DB
                if not request.tickets_db:
                    ticket = e.log(request) or 'unknown'
                # rollback
                if response._custom_rollback:
                    response._custom_rollback()
                else:
                    BaseAdapter.close_all_instances('rollback')
                # if tickets in db, reconnect and store it in db
                if request.tickets_db:
                    ticket = e.log(request) or 'unknown'

                http_response = \
                    HTTP(500, rwthread.routes.error_message_ticket %
                         dict(ticket=ticket),
                         web2py_error='ticket %s' % ticket)
Example #47
0
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)
Example #48
0
def wsgibase(environ, responder):
    """
    The gluon wsgi application. The first function called when a page
    is requested (static or dynamic). It can be called by paste.httpserver
    or by apache mod_wsgi (or any WSGI-compatible server).

      - fills request with info
      - the environment variables, replacing '.' with '_'
      - adds web2py path and version info
      - compensates for fcgi missing path_info and query_string
      - validates the path in url

    The url path must be either:

    1. for static pages:

      - /<application>/static/<file>

    2. for dynamic pages:

      - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>]

    The naming conventions are:

      - application, controller, function and extension may only contain
        `[a-zA-Z0-9_]`
      - file and sub may also contain '-', '=', '.' and '/'
    """
    eget = environ.get
    current.__dict__.clear()
    request = Request(environ)
    response = Response()
    session = Session()
    env = request.env
    #env.web2py_path = global_settings.applications_parent
    env.web2py_version = web2py_version
    #env.update(global_settings)
    static_file = False
    try:
        try:
            try:
                # ##################################################
                # handle fcgi missing path_info and query_string
                # select rewrite parameters
                # rewrite incoming URL
                # parse rewritten header variables
                # parse rewritten URL
                # serve file if static
                # ##################################################

                fixup_missing_path_info(environ)
                (static_file, version, environ) = url_in(request, environ)
                response.status = env.web2py_status_code or response.status

                if static_file:
                    if eget('QUERY_STRING', '').startswith('attachment'):
                        response.headers['Content-Disposition'] \
                            = 'attachment'
                    if version:
                        response.headers['Cache-Control'] = 'max-age=315360000'
                        response.headers[
                            'Expires'] = 'Thu, 31 Dec 2037 23:59:59 GMT'
                    response.stream(static_file, request=request)

                # ##################################################
                # fill in request items
                # ##################################################
                app = request.application  # must go after url_in!

                if not global_settings.local_hosts:
                    local_hosts = set(['127.0.0.1', '::ffff:127.0.0.1', '::1'])
                    if not global_settings.web2py_runtime_gae:
                        try:
                            fqdn = socket.getfqdn()
                            local_hosts.add(socket.gethostname())
                            local_hosts.add(fqdn)
                            local_hosts.update([
                                addrinfo[4][0]
                                for addrinfo in getipaddrinfo(fqdn)
                            ])
                            if env.server_name:
                                local_hosts.add(env.server_name)
                                local_hosts.update([
                                    addrinfo[4][0] for addrinfo in
                                    getipaddrinfo(env.server_name)
                                ])
                        except (socket.gaierror, TypeError):
                            pass
                    global_settings.local_hosts = list(local_hosts)
                else:
                    local_hosts = global_settings.local_hosts
                client = get_client(env)
                x_req_with = str(env.http_x_requested_with).lower()

                request.update(
                    client = client,
                    folder = abspath('applications', app) + os.sep,
                    ajax = x_req_with == 'xmlhttprequest',
                    cid = env.http_web2py_component_element,
                    is_local = env.remote_addr in local_hosts,
                    is_https = env.wsgi_url_scheme in HTTPS_SCHEMES or \
                        request.env.http_x_forwarded_proto in HTTPS_SCHEMES \
                        or env.https == 'on'
                    )
                request.compute_uuid()  # requires client
                request.url = environ['PATH_INFO']

                # ##################################################
                # access the requested application
                # ##################################################

                disabled = pjoin(request.folder, 'DISABLED')
                if not exists(request.folder):
                    if app == rwthread.routes.default_application \
                            and app != 'welcome':
                        redirect(URL('welcome', 'default', 'index'))
                    elif rwthread.routes.error_handler:
                        _handler = rwthread.routes.error_handler
                        redirect(
                            URL(_handler['application'],
                                _handler['controller'],
                                _handler['function'],
                                args=app))
                    else:
                        raise HTTP(404,
                                   rwthread.routes.error_message %
                                   'invalid request',
                                   web2py_error='invalid application')
                elif not request.is_local and exists(disabled):
                    raise HTTP(
                        503,
                        "<html><body><h1>Temporarily down for maintenance</h1></body></html>"
                    )

                # ##################################################
                # build missing folders
                # ##################################################

                create_missing_app_folders(request)

                # ##################################################
                # get the GET and POST data
                # ##################################################

                #parse_get_post_vars(request, environ)

                # ##################################################
                # expose wsgi hooks for convenience
                # ##################################################

                request.wsgi = LazyWSGI(environ, request, response)

                # ##################################################
                # load cookies
                # ##################################################

                if env.http_cookie:
                    try:
                        request.cookies.load(env.http_cookie)
                    except Cookie.CookieError, e:
                        pass  # invalid cookies

                # ##################################################
                # try load session or create new session file
                # ##################################################

                if not env.web2py_disable_session:
                    session.connect(request, response)

                # ##################################################
                # run controller
                # ##################################################

                if global_settings.debugging and app != "admin":
                    import gluon.debug
                    # activate the debugger
                    gluon.debug.dbg.do_debug(mainpyfile=request.folder)

                serve_controller(request, response, session)

            except HTTP, http_response:

                if static_file:
                    return http_response.to(responder, env=env)

                if request.body:
                    request.body.close()

                if hasattr(current, 'request'):

                    # ##################################################
                    # on success, try store session in database
                    # ##################################################
                    session._try_store_in_db(request, response)

                    # ##################################################
                    # on success, commit database
                    # ##################################################

                    if response.do_not_commit is True:
                        BaseAdapter.close_all_instances(None)
                    elif response.custom_commit:
                        BaseAdapter.close_all_instances(response.custom_commit)
                    else:
                        BaseAdapter.close_all_instances('commit')

                    # ##################################################
                    # if session not in db try store session on filesystem
                    # this must be done after trying to commit database!
                    # ##################################################

                    session._try_store_in_cookie_or_file(request, response)

                    # Set header so client can distinguish component requests.
                    if request.cid:
                        http_response.headers.setdefault(
                            'web2py-component-content', 'replace')

                    if request.ajax:
                        if response.flash:
                            http_response.headers['web2py-component-flash'] = \
                                urllib2.quote(xmlescape(response.flash)\
                                                  .replace('\n',''))
                        if response.js:
                            http_response.headers['web2py-component-command'] = \
                                urllib2.quote(response.js.replace('\n',''))

                    # ##################################################
                    # store cookies in headers
                    # ##################################################

                    session._fixup_before_save()
                    http_response.cookies2headers(response.cookies)

                ticket = None

            except RestrictedError, e:

                if request.body:
                    request.body.close()

                # ##################################################
                # on application error, rollback database
                # ##################################################

                # log tickets before rollback if not in DB
                if not request.tickets_db:
                    ticket = e.log(request) or 'unknown'
                # rollback
                if response._custom_rollback:
                    response._custom_rollback()
                else:
                    BaseAdapter.close_all_instances('rollback')
                # if tickets in db, reconnect and store it in db
                if request.tickets_db:
                    ticket = e.log(request) or 'unknown'

                http_response = \
                    HTTP(500, rwthread.routes.error_message_ticket %
                         dict(ticket=ticket),
                         web2py_error='ticket %s' % ticket)
Example #49
0
 def setUp(self):
     self.request = Request([])  # Use a clean Request object