开发者

web2py: using function in LOAD (ajax)

Is it possible to use =LOAD(...) with a function rather then controller/function string

e.g:

Controll开发者_运维百科er:
def test():
    print "test"

def index():
    return dict(test=test)

View:

{{=LOAD(test, ajax=True)}}

rather then:

View:

{{=LOAD('controller', 'test', ajax=True)}}

The main reason being, I want to use lambda/generated functions which cannot be accessed this way.


No. But not because the syntax is not supported, because it is logically impossible: the LOAD() is executed in a different http request than the one in which the lambda would be executed and therefore the latter would be undefined. Moreover to perform the ajax callback, the called function must have a name, cannot be a lambda. We could come up with a creative use of cache so that LOAD stores the lambda in cache:

def callback():
    """ a generic callback """
    return cache.ram(request.args(0),lambda:None,None)(**request.vars)

def LOAD2(f,vars={}):
    """ a new load function """
    import uuid
    u = str(uuid.uuid4())
    cache.ram(u,lambda f=f:f,0)
    return LOAD(request.controller,'callback',args=u,vars=vars,ajax=True)

def index():
    """ example of usage """
    a = LOAD2(lambda:'hello world')
    return dict(a=a)

But this would only work with cache.ram and would require periodic cache cleanup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜