Example #1
0
def test_get_person_by_creation_date(web2py):
    '''Is my filter working?
    '''

    from gluon.contrib.populate import populate
    populate(web2py.db.people, 3)  # insert 3 persons with random data
    assert web2py.db(web2py.db.people).count() == 3

    data = dict(
        name='John Smith',
        phone='3322-4455',
        created_at='1999-04-03 18:00:00')

    web2py.db.people.insert(**data)  # insert my controlled person
    web2py.db.commit()

    from gluon.compileapp import run_controller_in

    web2py.request.args.append(data['created_at'].split()[0])

    result = run_controller_in('people', 'get_by_creation_date', web2py)

    # test controller result
    assert result['name'] == data['name']

    # test controller result rendered as json by a view
    web2py.request.extension = 'json'
    html = web2py.response.render('people/get_by_creation_date.json', result)
    import json
    person = json.loads(html)
    assert person['name'] == data['name']
    assert person['created_at'] == data['created_at']
Example #2
0
def serve_controller(request, response, session):
    """
    This function is used to generate a dynamic page.
    It first runs all models, then runs the function in the controller,
    and then tries to render the output using a view/template.
    this function must run from the [application] folder.
    A typical example would be the call to the url
    /[application]/[controller]/[function] that would result in a call
    to [function]() in applications/[application]/[controller].py
    rendered by applications/[application]/views/[controller]/[function].html
    """

    # ##################################################
    # build environment for controller and view
    # ##################################################

    environment = build_environment(request, response, session)

    # set default view, controller can override it

    response.view = '%s/%s.%s' % (request.controller,
                                  request.function,
                                  request.extension)

    # also, make sure the flash is passed through
    # ##################################################
    # process models, controller and view (if required)
    # ##################################################

    run_models_in(environment)
    response._view_environment = copy.copy(environment)
    page = run_controller_in(request.controller, request.function, environment)
    if isinstance(page, dict):
        response._vars = page
        response._view_environment.update(page)
        page = run_view_in(response._view_environment)

    if not request.env.web2py_disable_garbage_collect:
        # logic to garbage collect after exec, not always, once every 100 requests
        global requests
        requests = ('requests' in globals()) and (requests + 1) % 100 or 0
        if not requests:
            gc.collect()
        # end garbage collection logic

    # ##################################################
    # set default headers it not set
    # ##################################################

    default_headers = [
        ('Content-Type', contenttype('.' + request.extension)),
        ('Cache-Control',
         'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'),
        ('Expires', time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                  time.gmtime())),
        ('Pragma', 'no-cache')]
    for key, value in default_headers:
        response.headers.setdefault(key, value)

    raise HTTP(response.status, page, **response.headers)
Example #3
0
def serve_controller(request, response, session):
    """
    This function is used to generate a dynamic page.
    It first runs all models, then runs the function in the controller,
    and then tries to render the output using a view/template.
    this function must run from the [application] folder.
    A typical example would be the call to the url
    /[application]/[controller]/[function] that would result in a call
    to [function]() in applications/[application]/[controller].py
    rendered by applications/[application]/views/[controller]/[function].html
    """

    # ##################################################
    # build environment for controller and view
    # ##################################################

    environment = build_environment(request, response, session)

    # set default view, controller can override it

    response.view = '%s/%s.%s' % (request.controller, request.function,
                                  request.extension)

    # also, make sure the flash is passed through
    # ##################################################
    # process models, controller and view (if required)
    # ##################################################

    run_models_in(environment)
    response._view_environment = copy.copy(environment)
    page = run_controller_in(request.controller, request.function, environment)
    if isinstance(page, dict):
        response._vars = page
        response._view_environment.update(page)
        page = run_view_in(response._view_environment)

    if not request.env.web2py_disable_garbage_collect:
        # logic to garbage collect after exec, not always, once every 100 requests
        global requests
        requests = ('requests' in globals()) and (requests + 1) % 100 or 0
        if not requests:
            gc.collect()
        # end garbage collection logic

    # ##################################################
    # set default headers it not set
    # ##################################################

    default_headers = [
        ('Content-Type', contenttype('.' + request.extension)),
        ('Cache-Control',
         'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'),
        ('Expires', unlocalised_http_header_date(time.gmtime())),
        ('Pragma', 'no-cache')
    ]
    for key, value in default_headers:
        response.headers.setdefault(key, value)

    raise HTTP(response.status, page, **response.headers)
Example #4
0
def test_index_exists(web2py):
    '''Page index exists?
    '''

    from gluon.compileapp import run_controller_in

    # run the controller, without view
    result = run_controller_in('people', 'index', web2py)

    # now, render the view with context received from controller
    html = web2py.response.render('people/index.html', result)
    assert "Hi. I'm the people index" in html
Example #5
0
def test_new_person_with_form(web2py):
    '''Is this function showing the right form?
    '''

    from gluon.compileapp import run_controller_in

    result = run_controller_in('people', 'new_person', web2py)

    html = web2py.response.render('people/new_person.html', result)

    assert 'new_person_form' in html
    assert 'name="name"' in html
    assert 'name="phone"' in html
    assert 'name="created_at"' not in html  # just ones listed in SQLFORM
Example #6
0
def run_web2py_controller(url):
    """
    run Controller using Model
    """
    # get data from function, and add to output
    # TODO: caching
    url_list = url.split('/')
    data = run_controller_in(url_list[0], url_list[1].replace('.json', ''), current.globalenv)
    view_data = XML(response.json(data['data']))

    model_data = '[]'
    if 'model' in data:
        model_data = XML(response.json(data['model']))
    pre_js_str = """var viewData = %(view_data)s;
var modelData = %(model)s;
    """ % dict(view_data=view_data, model=model_data)   

    return pre_js_str          
Example #7
0
def test_save_new_person(web2py):
    '''Created a new person?
    '''

    from gluon.compileapp import run_controller_in

    data = dict(
        name='Homer Simpson',
        phone='9988-7766',
        _formname='new_person_form')

    web2py.request.post_vars.update(data)
    result = run_controller_in('people', 'new_person', web2py)

    html = web2py.response.render('people/new_person.html', result)

    assert 'New person saved' in html

    assert web2py.db(web2py.db.people).count() == 1
    assert web2py.db(web2py.db.people.name == data['name']).count() == 1
Example #8
0
    def run(controller, function, env):
        """Injects request.controller and request.function into
        web2py environment.
        """

        from gluon.compileapp import run_controller_in

        env.request.controller = controller
        env.request.function = function
        r = None
        try:
            r =  run_controller_in(controller, function, env)
        except HTTP as e:
            if str(e.status).startswith("2") or str(e.status).startswith("3"):
                env.db.commit()
            raise
        else:
            env.db.commit()
        finally:
            env.db.rollback()
        return r
Example #9
0
    def run(controller, function, env):
        """Injects request.controller and request.function into
        web2py environment.
        """

        from gluon.compileapp import run_controller_in

        env.request.controller = controller
        env.request.function = function
        r = None
        try:
            r =  run_controller_in(controller, function, env)
        except HTTP as e:
            if str(e.status).startswith("2") or str(e.status).startswith("3"):
                env.db.commit()
            raise
        else:
            env.db.commit()
        finally:
            env.db.rollback()
        return r
Example #10
0
def test_validate_new_person(web2py):
    '''Is the form validating?
    '''

    from gluon.compileapp import run_controller_in

    data = dict(
        name='',
        phone='',
        _formname='new_person_form',
    )

    web2py.request.post_vars.update(data)
    result = run_controller_in('people', 'new_person', web2py)

    assert result['form'].errors

    html = web2py.response.render('people/new_person.html', result)

    assert 'name__error' in html
    assert 'phone__error' in html

    assert web2py.db(web2py.db.people).count() == 0
Example #11
0
 def run_function(self):
     return run_controller_in(self.env['request'].controller,
                              self.env['request'].function, self.env)
Example #12
0
def cms_index(module, alt_function=None):
    """
        Return a module index page retrieved from CMS
        - or run an alternate function if not found
    """

    response = current.response
    settings = current.deployment_settings

    module_name = settings.modules[module].name_nice
    response.title = module_name

    item = None
    if settings.has_module("cms"):
        db = current.db
        table = current.s3db.cms_post
        ltable = db.cms_post_module
        query = (ltable.module == module) & \
                (ltable.post_id == table.id) & \
                (table.deleted != True)
        _item = db(query).select(table.id,
                                 table.body,
                                 limitby=(0, 1)).first()
        auth = current.auth
        ADMIN = auth.get_system_roles().ADMIN
        ADMIN = auth.s3_has_role(ADMIN)
        if _item:
            if ADMIN:
                item = DIV(XML(_item.body),
                           BR(),
                           A(current.T("Edit"),
                             _href=URL(c="cms", f="post",
                                       args=[_item.id, "update"],
                                       vars={"module":module}),
                             _class="action-btn"))
            else:
                item = XML(_item.body)
        elif ADMIN:
            item = DIV(H2(module_name),
                       A(current.T("Edit"),
                         _href=URL(c="cms", f="post", args="create",
                                   vars={"module":module}),
                         _class="action-btn"))

    if not item:
        if alt_function:
            # Serve the alternate controller function
            # Copied from gluon.main serve_controller()
            # (We don't want to re-run models)
            from gluon.compileapp import build_environment, run_controller_in, run_view_in
            request = current.request
            environment = build_environment(request, response, current.session)
            environment["settings"] = settings
            page = run_controller_in(request.controller, alt_function, environment)
            if isinstance(page, dict):
                response._vars = page
                response._view_environment.update(page)
                run_view_in(response._view_environment)
                page = response.body.getvalue()
            # Set default headers if not set
            default_headers = [
                ("Content-Type", contenttype("." + request.extension)),
                ("Cache-Control",
                 "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"),
                ("Expires", time.strftime("%a, %d %b %Y %H:%M:%S GMT",
                                          time.gmtime())),
                ("Pragma", "no-cache")]
            for key, value in default_headers:
                response.headers.setdefault(key, value)
            raise HTTP(response.status, page, **response.headers)

        else:
            item = H2(module_name)

    # tbc
    report = ""

    response.view = "index.html"
    return dict(item=item, report=report)
    
    return None
Example #13
0
 def run_function(self):
     return run_controller_in(self.env['request'].controller, self.env['request'].function, self.env)
Example #14
0
def cms_index(module, alt_function=None):
    """
        Return a module index page retrieved from CMS
        - or run an alternate function if not found
    """

    response = current.response
    settings = current.deployment_settings

    module_name = settings.modules[module].name_nice
    response.title = module_name

    item = None
    if settings.has_module("cms"):
        db = current.db
        table = current.s3db.cms_post
        ltable = db.cms_post_module
        query = (ltable.module == module) & \
                (ltable.post_id == table.id) & \
                (table.deleted != True) & \
                ((ltable.resource == None) | \
                 (ltable.resource == "index"))
        _item = db(query).select(table.id,
                                 table.body,
                                 table.title,
                                 limitby=(0, 1)).first()
        # @ToDo: Replace this crude check with?
        #if current.auth.s3_has_permission("update", table, record_id=_item.id):
        auth = current.auth
        ADMIN = auth.get_system_roles().ADMIN
        ADMIN = auth.s3_has_role(ADMIN)
        if _item:
            if _item.title:
                response.title = _item.title
            if ADMIN:
                item = DIV(
                    XML(_item.body), BR(),
                    A(current.T("Edit"),
                      _href=URL(c="cms",
                                f="post",
                                args=[_item.id, "update"],
                                vars={"module": module}),
                      _class="action-btn"))
            else:
                item = XML(_item.body)
        elif ADMIN:
            item = DIV(
                H2(module_name),
                A(current.T("Edit"),
                  _href=URL(c="cms",
                            f="post",
                            args="create",
                            vars={"module": module}),
                  _class="action-btn"))

    if not item:
        if alt_function:
            # Serve the alternate controller function
            # Copied from gluon.main serve_controller()
            # (We don't want to re-run models)
            from gluon.compileapp import build_environment, run_controller_in, run_view_in
            request = current.request
            environment = build_environment(request, response, current.session)
            environment["settings"] = settings
            environment["s3db"] = current.s3db
            page = run_controller_in(request.controller, alt_function,
                                     environment)
            if isinstance(page, dict):
                response._vars = page
                response._view_environment.update(page)
                run_view_in(response._view_environment)
                page = response.body.getvalue()
            # Set default headers if not set
            default_headers = [
                ("Content-Type", contenttype("." + request.extension)),
                ("Cache-Control",
                 "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
                 ),
                ("Expires",
                 time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())),
                ("Pragma", "no-cache")
            ]
            for key, value in default_headers:
                response.headers.setdefault(key, value)
            raise HTTP(response.status, page, **response.headers)

        else:
            item = H2(module_name)

    # tbc
    report = ""

    response.view = "index.html"
    return dict(item=item, report=report)

    return None