Ejemplo n.º 1
0
 def test_decode(self):
     T = languages.translator(self.langpath, self.http_accept_language)
     elem = SPAN(T("Complete"))
     self.assertEqual(elem.flatten(), "Complete")
     elem = SPAN(T("Cannot be empty", language="ru"))
     self.assertEqual(elem.xml(), to_bytes('<span>Пустое значение недопустимо</span>'))
     self.assertEqual(elem.flatten(), 'Пустое значение недопустимо')
Ejemplo n.º 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()
Ejemplo n.º 3
0
 def test_plain(self):
     T = languages.translator(self.langpath, self.http_accept_language)
     self.assertEqual(str(T('Hello World')),
                      'Hello World')
     self.assertEqual(str(T('Hello World## comment')),
                      'Hello World')
     self.assertEqual(str(T('%s %%{shop}', 1)),
                      '1 shop')
     self.assertEqual(str(T('%s %%{shop}', 2)),
                      '2 shops')
     self.assertEqual(str(T('%s %%{shop[0]}', 1)),
                      '1 shop')
     self.assertEqual(str(T('%s %%{shop[0]}', 2)),
                      '2 shops')
     self.assertEqual(str(T('%s %%{quark[0]}', 1)),
                      '1 quark')
     self.assertEqual(str(T('%s %%{quark[0]}', 2)),
                      '2 quarks')
     self.assertEqual(str(T.M('**Hello World**')),
                      '<strong>Hello World</strong>')
     T.force('it')
     self.assertEqual(str(T('Hello World')),
                      'Salve Mondo')
     self.assertEqual(to_unicode(T('Hello World')),
                      'Salve Mondo')
Ejemplo n.º 4
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()
Ejemplo n.º 5
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()
Ejemplo n.º 6
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()
Ejemplo n.º 7
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()
Ejemplo n.º 8
0
 def __init__(self):
     import gluon
     self.compldict = gluon.__dict__ #{}
     from gluon.globals import Request, Response, Session
     self.compldict['request'] = request = Request()
     self.compldict['response'] = response = Response()
     self.compldict['session'] = session = Session()
     from gluon.cache import Cache
     self.compldict['cache'] = Cache(request)
     from gluon.languages import translator
     self.compldict['T'] = T = translator(request)
     from gluon.dal import DAL
     self.compldict['db'] = db = DAL("sqlite:memory")
     from gluon import current
     current.request = request
     current.session = session
     current.response = response
     current.T = T
     #current.request.env.http_host = '127.0.0.1'
     #from gluon.tools import Auth, Crud, Mail, Service, PluginManager
     #self.compldict['auth'] = Auth(db)
     #self.compldict['crud'] = Crud(db)
     #self.compldict['service'] = Service()
     #self.compldict['plugins'] = PluginManager()
     self.parser = PyParser()
Ejemplo n.º 9
0
 def test_decode(self):
     T = languages.translator(self.langpath, self.http_accept_language)
     elem = SPAN(T("Complete"))
     self.assertEqual(elem.flatten(), "Complete")
     elem = SPAN(T("Cannot be empty", language="ru"))
     self.assertEqual(elem.xml(),
                      to_bytes('<span>Пустое значение недопустимо</span>'))
     self.assertEqual(elem.flatten(), 'Пустое значение недопустимо')
Ejemplo n.º 10
0
 def setUp(self):
     self.db = None
     self.cleanfolder()
     from gluon import current
     s = Storage({'application': 'welcome',
                  'folder': 'applications/welcome',
                  'controller': 'default'})
     current.request = s
     T = translator('', 'en')
     current.T = T
     self.db = DAL('sqlite://dummy2.db', check_reserved=['all'])
Ejemplo n.º 11
0
 def setUp(self):
     self.db = None
     self.cleanfolder()
     from gluon.globals import current
     s = Storage({'application': 'welcome',
                  'folder': 'applications/welcome',
                  'controller': 'default'})
     current.request = s
     T = translator('', 'en')
     current.T = T
     self.db = DAL('sqlite://dummy2.db', check_reserved=['all'])
Ejemplo n.º 12
0
 def test_plain(self):
     T = languages.translator(self.langpath, self.http_accept_language)
     self.assertEqual(str(T('Hello World')), 'Hello World')
     self.assertEqual(str(T('Hello World## comment')), 'Hello World')
     self.assertEqual(str(T('%s %%{shop}', 1)), '1 shop')
     self.assertEqual(str(T('%s %%{shop}', 2)), '2 shops')
     self.assertEqual(str(T('%s %%{shop[0]}', 1)), '1 shop')
     self.assertEqual(str(T('%s %%{shop[0]}', 2)), '2 shops')
     self.assertEqual(str(T('%s %%{quark[0]}', 1)), '1 quark')
     self.assertEqual(str(T('%s %%{quark[0]}', 2)), '2 quarks')
     self.assertEqual(str(T.M('**Hello World**')),
                      '<strong>Hello World</strong>')
     T.force('it')
     self.assertEqual(str(T('Hello World')), 'Salve Mondo')
Ejemplo n.º 13
0
def build_environment(request, response, session, store_current=True):
    """
    Build the environment dictionary into which web2py files are executed.
    """
    #h,v = html,validators
    environment = dict(_base_environment_)

    if not request.env:
        request.env = Storage()
    # Enable standard conditional models (i.e., /*.py, /[controller]/*.py, and
    # /[controller]/[function]/*.py)
    response.models_to_run = [
        r'^\w+\.py$',
        r'^%s/\w+\.py$' % request.controller,
        r'^%s/%s/\w+\.py$' % (request.controller, request.function)
    ]

    t = environment['T'] = translator(
        os.path.join(request.folder, 'languages'),
        request.env.http_accept_language)
    c = environment['cache'] = Cache(request)

    if store_current:
        current.globalenv = environment
        current.request = request
        current.response = response
        current.session = session
        current.T = t
        current.cache = c

    global __builtins__
    if is_jython:  # jython hack
        __builtins__ = mybuiltin()
    elif is_pypy:  # apply the same hack to pypy too
        __builtins__ = mybuiltin()
    else:
        __builtins__['__import__'] = __builtin__.__import__  # WHY?
    environment['request'] = request
    environment['response'] = response
    environment['session'] = session
    environment['local_import'] = \
        lambda name, reload=False, app=request.application:\
        local_import_aux(name, reload, app)
    BaseAdapter.set_folder(pjoin(request.folder, 'databases'))
    response._view_environment = copy.copy(environment)
    custom_import_install()
    return environment
Ejemplo n.º 14
0
def build_environment(request, response, session, store_current=True):
    """
    Build the environment dictionary into which web2py files are executed.
    """
    #h,v = html,validators
    environment = dict(_base_environment_)

    if not request.env:
        request.env = Storage()
    # Enable standard conditional models (i.e., /*.py, /[controller]/*.py, and
    # /[controller]/[function]/*.py)
    response.models_to_run = [
        r'^\w+\.py$', 
        r'^%s/\w+\.py$' % request.controller,
        r'^%s/%s/\w+\.py$' % (request.controller, request.function)
        ]

    t = environment['T'] = translator(os.path.join(request.folder,'languages'),
                                      request.env.http_accept_language)
    c = environment['cache'] = Cache(request)

    if store_current:
        current.globalenv = environment
        current.request = request
        current.response = response
        current.session = session
        current.T = t
        current.cache = c

    global __builtins__
    if is_jython:  # jython hack
        __builtins__ = mybuiltin()
    elif is_pypy:  # apply the same hack to pypy too
        __builtins__ = mybuiltin()
    else:
        __builtins__['__import__'] = __builtin__.__import__  # WHY?
    environment['request'] = request
    environment['response'] = response
    environment['session'] = session
    environment['local_import'] = \
        lambda name, reload=False, app=request.application:\
        local_import_aux(name, reload, app)
    BaseAdapter.set_folder(pjoin(request.folder, 'databases'))
    response._view_environment = copy.copy(environment)
    custom_import_install()
    return environment
Ejemplo n.º 15
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
Ejemplo n.º 16
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 = 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()
Ejemplo n.º 17
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 = 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()
Ejemplo n.º 18
0
    def testJSON(self):
        # the main and documented "way" is to use the json() function
        # it has a few corner-cases that make json() be somewhat
        # different from the standard buyt being compliant
        # it's just a matter of conventions

        # incompatible spacing, newer simplejson already account
        # for this but it's still better to remember
        weird = {'JSON': u"ro" + u'\u2028' + u'ck' + u'\u2029' + u's!'}
        rtn = json(weird)
        self.assertEqual(rtn, u'{"JSON": "ro\\u2028ck\\u2029s!"}')
        # date, datetime, time strictly as strings in isoformat, minus the T
        objs = [
            datetime.datetime(2014, 1, 1, 12, 15, 35),
            datetime.date(2014, 1, 1),
            datetime.time(12, 15, 35)
            ]
        iso_objs = [obj.isoformat()[:19].replace('T', ' ') for obj in objs]
        json_objs = [json(obj) for obj in objs]
        json_web2pyfied = [json(obj) for obj in iso_objs]
        self.assertEqual(json_objs, json_web2pyfied)
        # int or long int()ified
        # self.assertEqual(json(1), json(1))
        # decimal stringified
        obj = {'a': decimal.Decimal('4.312312312312')}
        self.assertEqual(json(obj), u'{"a": "4.312312312312"}')
        # lazyT translated
        T = translator('', 'en')
        lazy_translation = T('abc')
        self.assertEqual(json(lazy_translation), u'"abc"')
        # html helpers are xml()ed before too
        self.assertEqual(json(SPAN('abc')), u'"<span>abc</span>"')
        # unicode keys make a difference with loads_json
        base = {u'è': 1, 'b': 2}
        base_enc = json(base)
        base_load = loads_json(base_enc)
        self.assertTrue(base == base_load)
        # if unicode_keys is false, the standard behaviour is assumed
        base_load = loads_json(base_enc, unicode_keys=False)
        self.assertFalse(base == base_load)
Ejemplo n.º 19
0
    def testJSON(self):
        # the main and documented "way" is to use the json() function
        # it has a few corner-cases that make json() be somewhat
        # different from the standard buyt being compliant
        # it's just a matter of conventions

        # incompatible spacing, newer simplejson already account
        # for this but it's still better to remember
        weird = {'JSON': u"ro" + u'\u2028' + u'ck' + u'\u2029' + u's!'}
        rtn = json(weird)
        self.assertEqual(rtn, u'{"JSON": "ro\\u2028ck\\u2029s!"}')
        # date, datetime, time strictly as strings in isoformat, minus the T
        objs = [
            datetime.datetime(2014, 1, 1, 12, 15, 35),
            datetime.date(2014, 1, 1),
            datetime.time(12, 15, 35)
            ]
        iso_objs = [obj.isoformat()[:19].replace('T', ' ') for obj in objs]
        json_objs = [json(obj) for obj in objs]
        json_web2pyfied = [json(obj) for obj in iso_objs]
        self.assertEqual(json_objs, json_web2pyfied)
        # int or long int()ified
        # self.assertEqual(json(1), json(1))
        # decimal stringified
        obj = {'a': decimal.Decimal('4.312312312312')}
        self.assertEqual(json(obj), u'{"a": "4.312312312312"}')
        # lazyT translated
        T = translator('', 'en')
        lazy_translation = T('abc')
        self.assertEqual(json(lazy_translation), u'"abc"')
        # html helpers are xml()ed before too
        self.assertEqual(json(SPAN('abc')), u'"<span>abc</span>"')
        # unicode keys make a difference with loads_json
        base = {u'è': 1, 'b': 2}
        base_enc = json(base)
        base_load = loads_json(base_enc)
        self.assertTrue(base == base_load)
        # if unicode_keys is false, the standard behaviour is assumed
        base_load = loads_json(base_enc, unicode_keys=False)
        self.assertFalse(base == base_load)
Ejemplo n.º 20
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
Ejemplo n.º 21
0
if 0:

    from gluon.html import *
    from gluon.validators import *
    from gluon.http import redirect, HTTP
    from gluon.sqlhtml import SQLFORM, SQLTABLE
    from gluon.compileapp import LOAD

    from gluon.globals import Request, Response, Session, current
    from gluon.cache import Cache
    from gluon.languages import translator
    from gluon.tools import Auth, Crud, Mail, Service, PluginManager
    from gluon.dal import DAL, Field
    from chimitheque_multiple_widget import CHIMITHEQUE_MULTIPLE_widget

    # API objects
    request = Request()
    response = Response()
    session = Session()
    cache = Cache(request)
    T = translator(request, 'fr')

    # Objects commonly defined in application model files
    # (names are conventions only -- not part of API)
    db = DAL()
    auth = Auth(db)
    crud = Crud(db)
    mail = Mail()
    service = Service()
    plugins = PluginManager()
    settings = {}
Ejemplo n.º 22
0
 def test_plain(self):
     T = languages.translator(self.langpath, self.http_accept_language)
     self.assertEqual(str(T('Hello World')), 'Hello World')
     self.assertEqual(str(T('Hello World## comment')), 'Hello World')
     self.assertEqual(str(T.M('**Hello World**')),
                      '<strong>Hello World</strong>')
     # sub_tuple testing
     self.assertEqual(str(T('%s %%{shop}', 1)), '1 shop')
     self.assertEqual(str(T('%s %%{shop}', 2)), '2 shops')
     self.assertEqual(str(T('%%{quark(%s)}', 1)), 'quark')
     self.assertEqual(str(T('%%{quark(%i)}', 2)), 'quarks')
     self.assertEqual(str(T('%%{!quark(%s)}', 1)), 'Quark')
     self.assertEqual(str(T('%%{!!quark(%i)}', 2)), 'Quarks')
     self.assertEqual(str(T('%%{!!!quark(%s)}', 0)), 'QUARKS')
     self.assertEqual(str(T('%%{?an?%i}', 1)), 'an')
     self.assertEqual(str(T('%%{?an?%s}', 0)), '0')
     self.assertEqual(str(T('%%{??%i}', 1)), '')
     self.assertEqual(str(T('%%{??%s}', 2)), '2')
     self.assertEqual(str(T('%%{?%i}', 1)), '')
     self.assertEqual(str(T('%%{?%s}', 0)), '0')
     self.assertEqual(str(T('%%{?one?%i?zero}', 1)), 'one')
     self.assertEqual(str(T('%%{?one?%s?zero}', 23)), '23')
     self.assertEqual(str(T('%%{?one?%i?zero}', 0)), 'zero')
     self.assertEqual(str(T('%%{?one?%s?}', 1)), 'one')
     self.assertEqual(str(T('%%{?one?%i?}', 23)), '23')
     self.assertEqual(str(T('%%{?one?%s?}', 0)), '')
     self.assertEqual(str(T('%%{??%i?zero}', 1)), '')
     self.assertEqual(str(T('%%{??%s?zero}', 23)), '23')
     self.assertEqual(str(T('%%{??%i?zero}', 0)), 'zero')
     self.assertEqual(str(T('%%{??1?}%s', '')), '')
     self.assertEqual(str(T('%%{??%s?}', 23)), '23')
     self.assertEqual(str(T('%%{??0?}%s', '')), '')
     self.assertEqual(str(T('%s %%{shop[0]}', 1)), '1 shop')
     self.assertEqual(str(T('%s %%{shop[0]}', 2)), '2 shops')
     self.assertEqual(str(T('%i %%{?one?not_one[0]}', 1)), '1 one')
     self.assertEqual(str(T('%i %%{?one?not_one[0]}', 2)), '2 not_one')
     self.assertEqual(str(T('%%{??on[0]} %i', 1)), ' 1')
     self.assertEqual(str(T('%%{??on[0]} %s', 0)), 'on 0')
     self.assertEqual(str(T('%%{?on[0]} %s', 1)), ' 1')
     self.assertEqual(str(T('%%{?on[0]} %i', 2)), 'on 2')
     self.assertEqual(str(T('%i %%{?one?or_more?zero[0]}', 1)), '1 one')
     self.assertEqual(str(T('%i %%{?one?or_more?zero[0]}', 2)), '2 or_more')
     self.assertEqual(str(T('%i %%{?one?or_more?zero[0]}', 0)), '0 zero')
     self.assertEqual(str(T('%i %%{?one?hands?[0]}', 1)), '1 one')
     self.assertEqual(str(T('%s %%{?one?hands?[0]}', 2)), '2 hands')
     self.assertEqual(str(T('%i %%{?one?hands?[0]}', 0)), '0 ')
     self.assertEqual(str(T('%s %%{??or_more?zero[0]}', 1)), '1 ')
     self.assertEqual(str(T('%i %%{??or_more?zero[0]}', 2)), '2 or_more')
     self.assertEqual(str(T('%s %%{??or_more?zero[0]}', 0)), '0 zero')
     self.assertEqual(str(T('%i%%{??nd?[0]}', 1)), '1')
     self.assertEqual(str(T('%i%%{??nd?[0]}', 2)), '2nd')
     self.assertEqual(str(T('%i%%{??nd?[0]}', 0)), '0')
     self.assertEqual(str(T('%i%%{?st?[0]}', 1)), '1st')
     self.assertEqual(str(T('%i%%{?st?[0]}', 2)), '2')
     self.assertEqual(str(T('%i%%{?st?[0]}', 0)), '0')
     # sub_dict testing
     self.assertEqual(str(T('%(key)s %%{is(key)}', dict(key=1))), '1 is')
     self.assertEqual(str(T('%(key)i %%{is(key)}', dict(key=2))), '2 are')
     self.assertEqual(str(T('%%{!!!is(%(key)s)}', dict(key=2))), 'ARE')
     self.assertEqual(str(T('%(key)i %%{?not_one(key)}', dict(key=1))),
                      '1 ')
     self.assertEqual(str(T('%(key)s %%{?not_one(key)}', dict(key=2))),
                      '2 not_one')
     self.assertEqual(str(T('%(key)i %%{?not_one(key)}', dict(key=0))),
                      '0 not_one')
     self.assertEqual(str(T('%(key)s %%{?one?not_one(key)}', dict(key=1))),
                      '1 one')
     self.assertEqual(str(T('%(key)i %%{?one?not_one(key)}', dict(key=2))),
                      '2 not_one')
     self.assertEqual(str(T('%(key)s %%{?one?not_one(key)}', dict(key=0))),
                      '0 not_one')
     self.assertEqual(str(T('%(key)i %%{?one?(key)}', dict(key=1))),
                      '1 one')
     self.assertEqual(str(T('%(key)s %%{?one?(key)}', dict(key=2))), '2 ')
     self.assertEqual(str(T('%(key)i %%{?one?(key)}', dict(key=0))), '0 ')
     self.assertEqual(str(T('%(key)s %%{??not_one(key)}', dict(key=1))),
                      '1 ')
     self.assertEqual(str(T('%(key)i %%{??not_one(key)}', dict(key=2))),
                      '2 not_one')
     self.assertEqual(str(T('%(key)s %%{?not_one(key)}', dict(key=1))),
                      '1 ')
     self.assertEqual(str(T('%(key)i %%{?not_one(key)}', dict(key=0))),
                      '0 not_one')
     self.assertEqual(
         str(T('%(key)s %%{?one?other?zero(key)}', dict(key=1))), '1 one')
     self.assertEqual(
         str(T('%(key)i %%{?one?other?zero(key)}', dict(key=4))), '4 other')
     self.assertEqual(
         str(T('%(key)s %%{?one?other?zero(key)}', dict(key=0))), '0 zero')
     self.assertEqual(
         str(T('%(key)i %%{?one?two_or_more?(key)}', dict(key=1))), '1 one')
     self.assertEqual(
         str(T('%(key)s %%{?one?two_or_more?(key)}', dict(key=2))),
         '2 two_or_more')
     self.assertEqual(
         str(T('%(key)i %%{?one?two_or_more?(key)}', dict(key=0))), '0 ')
     self.assertEqual(
         str(T('%(key)s %%{??two_or_more?zero(key)}', dict(key=1))), '1 ')
     self.assertEqual(
         str(T('%(key)i %%{??two_or_more?zero(key)}', dict(key=2))),
         '2 two_or_more')
     self.assertEqual(
         str(T('%(key)s %%{??two_or_more?zero(key)}', dict(key=0))),
         '0 zero')
     self.assertEqual(
         str(T('%(key)i %%{??two_or_more?(key)}', dict(key=1))), '1 ')
     self.assertEqual(
         str(T('%(key)s %%{??two_or_more?(key)}', dict(key=0))), '0 ')
     self.assertEqual(
         str(T('%(key)i %%{??two_or_more?(key)}', dict(key=2))),
         '2 two_or_more')
     T.force('it')
     self.assertEqual(str(T('Hello World')), 'Salve Mondo')
     self.assertEqual(to_unicode(T('Hello World')), 'Salve Mondo')
Ejemplo n.º 23
0
 def test_decode(self):
     T = languages.translator(self.langpath, self.http_accept_language)
     messages = Messages(T)
     messages.update({'email_sent': 'Email sent', 'test': "ä"})
     self.assertEqual(to_unicode(messages.email_sent, 'utf-8'),
                      'Email sent')
Ejemplo n.º 24
0
def main_wsgi_app(environ, start_response):
    import gluon
    common_context = {key:getattr(gluon,key) for key in dir(gluon)}
    have_databases = False
    try:
        try:
            current.request = request = Request(environ)
            response = session = None
            request_folder = request.folder           
            # if client requested a static page
            if request.controller == 'static':
                current.response = None
                current.session = None
                static_folder =  os_path_join(request_folder,'static')
                n = 3 if request.items[2].startswith('_') else 2
                filename = os_path_join(static_folder,*request.items[n:])
                if not filename.startswith(static_folder+'/'): raise HTTP(404)
                if not os_path_exists(filename): raise HTTP(404)
                stream_file_or_304_or_206(filename, environ=environ) # raise HTTP 200
            # if instead client requested a dynamic page
            else:
                # build context and inject variables into context
                runner = CodeRunner(common_context.copy())
                # inject request specific variables into context
                runner.context['request'] = request
                runner.context['response'] = current.response = response = Response()
                runner.context['session'] = current.session = session = Session()
                runner.context['T'] = current.T = translator(
                    os_path_join(request_folder,'languages'),
                    request.environ.get('HTTP_ACCEPT_LANGUAGE'))
                # check if there is a database folder and set the folder
                database_folder =  os_path_join(request_folder,'databases')
                have_databases = os_path_exists(database_folder)
                if have_databases:
                    BaseAdapter.set_folder(os_path_join(request_folder, 'databases'))
                # raise an error if the controller file is missing
                controllers_folder = os_path_join(request_folder,'controllers') 
                controller_filename = os_path_join(controllers_folder,request.controller+'.py')
                if not controller_filename.startswith(controllers_folder+'/'): raise HTTP(404)
                if not os_path_exists(controller_filename): raise HTTP(404)
                # import models, ugly but faster than glob
                models_folder = os_path_join(request_folder,'models')
                if os_path_exists(models_folder):
                    for filename in sorted(filter(lambda x: x[-3:]=='.py',os.listdir(models_folder))): 
                        runner.import_code(models_folder+os.sep+filename)
                # run controller action
                view_context = runner.context.copy()
                content = runner.import_code(controller_filename, request.function)
                # optionally run view
                func_ext = request.function+'.'+request.extension
                if isinstance(content, dict):
                    view_context.update(content)
                    template_folder = os_path_join(request_folder,'views')
                    # maybe a response.view is specified
                    if response.view:
                        template_filename = os_path_join(template_folder,response.view)
                    # or maybe not
                    else:
                        template_filename = os_path_join(template_folder,request.controller,func_ext)
                    # if the view exists use it
                    if os_path_exists(template_filename):
                        content = render(filename=template_filename, path = template_folder, context = view_context)
                    # else but represent the context as a dict (generic views?)
                    else:
                        content = repr(view_context)
                # set the content type
                response.headers["Content-type"] = contenttype(func_ext)                
                raise HTTP(response.status, content, headers=response.headers)
        # if a HTTP is raised, everything is ok, return
        except HTTP, http:       
            if response:
                # commit databases, if any
                have_databases = have_databases and response.auto_commit
                if have_databases:
                    session._try_store_in_db(request, response)
                    BaseAdapter.close_all_instances('commit')
                    have_databases = False
                # save session, if changed
                session._try_store_in_cookie_or_file(request, response)
                # deal with cookies
                if hasattr(response,'_cookies'):
                    http.cookies2headers(response.cookies)
            return http.to(start_response, env=environ)
        # there was an error
        except Exception, err: 
            # maybe log the ticket
            if isinstance(err, RestrictedError):
                ticket = err.log(request)
            # or maybe not
            else:
                print traceback.format_exc()
                #request.logger.error(traceback.format_exc())
                ticket = 'unknown'
            # return HTTP 500
            return  HTTP(500, ticket).to(start_response, env=environ)
# $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()
    cache = Cache()
    crud = Crud(globals(), db)
Ejemplo n.º 26
0
 def test_decode(self):
     T = languages.translator(self.langpath, self.http_accept_language)
     messages = Messages(T)
     messages.update({'email_sent':'Email sent', 'test': "ä"})
     self.assertEqual(to_unicode(messages.email_sent, 'utf-8'), 'Email sent')
Ejemplo n.º 27
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
Ejemplo n.º 28
0
    def test_plain(self):
        T = languages.translator(self.langpath, self.http_accept_language)
        self.assertEqual(str(T('Hello World')),
                         'Hello World')
        self.assertEqual(str(T('Hello World## comment')),
                         'Hello World')
        self.assertEqual(str(T.M('**Hello World**')),
                         '<strong>Hello World</strong>')
		# sub_tuple testing
        self.assertEqual(str(T('%s %%{shop}', 1)),
                         '1 shop')
        self.assertEqual(str(T('%s %%{shop}', 2)),
                         '2 shops')
        self.assertEqual(str(T('%%{quark(%s)}', 1)),
                         'quark')
        self.assertEqual(str(T('%%{quark(%i)}', 2)),
                         'quarks')
        self.assertEqual(str(T('%%{!quark(%s)}', 1)),
                         'Quark')
        self.assertEqual(str(T('%%{!!quark(%i)}', 2)),
                         'Quarks')
        self.assertEqual(str(T('%%{!!!quark(%s)}', 0)),
                         'QUARKS')
        self.assertEqual(str(T('%%{?an?%i}', 1)),
                         'an')
        self.assertEqual(str(T('%%{?an?%s}', 0)),
                         '0')
        self.assertEqual(str(T('%%{??%i}', 1)),
                         '')
        self.assertEqual(str(T('%%{??%s}', 2)),
                         '2')
        self.assertEqual(str(T('%%{?%i}', 1)),
                         '')
        self.assertEqual(str(T('%%{?%s}', 0)),
                         '0')
        self.assertEqual(str(T('%%{?one?%i?zero}', 1)),
                         'one')
        self.assertEqual(str(T('%%{?one?%s?zero}', 23)),
                         '23')
        self.assertEqual(str(T('%%{?one?%i?zero}', 0)),
                         'zero')
        self.assertEqual(str(T('%%{?one?%s?}', 1)),
                         'one')
        self.assertEqual(str(T('%%{?one?%i?}', 23)),
                         '23')
        self.assertEqual(str(T('%%{?one?%s?}', 0)),
                         '')
        self.assertEqual(str(T('%%{??%i?zero}', 1)),
                         '')
        self.assertEqual(str(T('%%{??%s?zero}', 23)),
                         '23')
        self.assertEqual(str(T('%%{??%i?zero}', 0)),
                         'zero')
        self.assertEqual(str(T('%%{??1?}%s', '')),
                         '')
        self.assertEqual(str(T('%%{??%s?}', 23)),
                         '23')
        self.assertEqual(str(T('%%{??0?}%s', '')),
                         '')
        self.assertEqual(str(T('%s %%{shop[0]}', 1)),
                         '1 shop')
        self.assertEqual(str(T('%s %%{shop[0]}', 2)),
                         '2 shops')
        self.assertEqual(str(T('%i %%{?one?not_one[0]}', 1)),
                         '1 one')
        self.assertEqual(str(T('%i %%{?one?not_one[0]}', 2)),
                         '2 not_one')
        self.assertEqual(str(T('%%{??on[0]} %i', 1)),
                         ' 1')
        self.assertEqual(str(T('%%{??on[0]} %s', 0)),
                         'on 0')
        self.assertEqual(str(T('%%{?on[0]} %s', 1)),
                         ' 1')
        self.assertEqual(str(T('%%{?on[0]} %i', 2)),
                         'on 2')
        self.assertEqual(str(T('%i %%{?one?or_more?zero[0]}', 1)),
                         '1 one')
        self.assertEqual(str(T('%i %%{?one?or_more?zero[0]}', 2)),
                         '2 or_more')
        self.assertEqual(str(T('%i %%{?one?or_more?zero[0]}', 0)),
                         '0 zero')
        self.assertEqual(str(T('%i %%{?one?hands?[0]}', 1)),
                         '1 one')
        self.assertEqual(str(T('%s %%{?one?hands?[0]}', 2)),
                         '2 hands')
        self.assertEqual(str(T('%i %%{?one?hands?[0]}', 0)),
                         '0 ')
        self.assertEqual(str(T('%s %%{??or_more?zero[0]}', 1)),
                         '1 ')
        self.assertEqual(str(T('%i %%{??or_more?zero[0]}', 2)),
                         '2 or_more')
        self.assertEqual(str(T('%s %%{??or_more?zero[0]}', 0)),
                         '0 zero')
        self.assertEqual(str(T('%i%%{??nd?[0]}', 1)),
                         '1')
        self.assertEqual(str(T('%i%%{??nd?[0]}', 2)),
                         '2nd')
        self.assertEqual(str(T('%i%%{??nd?[0]}', 0)),
                         '0')
        self.assertEqual(str(T('%i%%{?st?[0]}', 1)),
                         '1st')
        self.assertEqual(str(T('%i%%{?st?[0]}', 2)),
                         '2')
        self.assertEqual(str(T('%i%%{?st?[0]}', 0)),
                         '0')
		# sub_dict testing
        self.assertEqual(str(T('%(key)s %%{is(key)}', dict(key=1))),
                         '1 is')
        self.assertEqual(str(T('%(key)i %%{is(key)}', dict(key=2))),
                         '2 are')
        self.assertEqual(str(T('%%{!!!is(%(key)s)}', dict(key=2))),
                         'ARE')
        self.assertEqual(str(T('%(key)i %%{?not_one(key)}', dict(key=1))),
                         '1 ')
        self.assertEqual(str(T('%(key)s %%{?not_one(key)}', dict(key=2))),
                         '2 not_one')
        self.assertEqual(str(T('%(key)i %%{?not_one(key)}', dict(key=0))),
                         '0 not_one')
        self.assertEqual(str(T('%(key)s %%{?one?not_one(key)}', dict(key=1))),
                         '1 one')
        self.assertEqual(str(T('%(key)i %%{?one?not_one(key)}', dict(key=2))),
                         '2 not_one')
        self.assertEqual(str(T('%(key)s %%{?one?not_one(key)}', dict(key=0))),
                         '0 not_one')
        self.assertEqual(str(T('%(key)i %%{?one?(key)}', dict(key=1))),
                         '1 one')
        self.assertEqual(str(T('%(key)s %%{?one?(key)}', dict(key=2))),
                         '2 ')
        self.assertEqual(str(T('%(key)i %%{?one?(key)}', dict(key=0))),
                         '0 ')
        self.assertEqual(str(T('%(key)s %%{??not_one(key)}', dict(key=1))),
                         '1 ')
        self.assertEqual(str(T('%(key)i %%{??not_one(key)}', dict(key=2))),
                         '2 not_one')
        self.assertEqual(str(T('%(key)s %%{?not_one(key)}', dict(key=1))),
                         '1 ')
        self.assertEqual(str(T('%(key)i %%{?not_one(key)}', dict(key=0))),
                         '0 not_one')
        self.assertEqual(str(T('%(key)s %%{?one?other?zero(key)}', dict(key=1))),
                         '1 one')
        self.assertEqual(str(T('%(key)i %%{?one?other?zero(key)}', dict(key=4))),
                         '4 other')
        self.assertEqual(str(T('%(key)s %%{?one?other?zero(key)}', dict(key=0))),
                         '0 zero')
        self.assertEqual(str(T('%(key)i %%{?one?two_or_more?(key)}', dict(key=1))),
                         '1 one')
        self.assertEqual(str(T('%(key)s %%{?one?two_or_more?(key)}', dict(key=2))),
                         '2 two_or_more')
        self.assertEqual(str(T('%(key)i %%{?one?two_or_more?(key)}', dict(key=0))),
                         '0 ')
        self.assertEqual(str(T('%(key)s %%{??two_or_more?zero(key)}', dict(key=1))),
                         '1 ')
        self.assertEqual(str(T('%(key)i %%{??two_or_more?zero(key)}', dict(key=2))),
                         '2 two_or_more')
        self.assertEqual(str(T('%(key)s %%{??two_or_more?zero(key)}', dict(key=0))),
                         '0 zero')
        self.assertEqual(str(T('%(key)i %%{??two_or_more?(key)}', dict(key=1))),
                         '1 ')
        self.assertEqual(str(T('%(key)s %%{??two_or_more?(key)}', dict(key=0))),
                         '0 ')
        self.assertEqual(str(T('%(key)i %%{??two_or_more?(key)}', dict(key=2))),
                         '2 two_or_more')
        T.force('it')
        self.assertEqual(str(T('Hello World')),
                         'Salve Mondo')
        self.assertEqual(to_unicode(T('Hello World')),
                         'Salve Mondo')