web2py:在 shell 中正常运行的模块函数在浏览器模式下失败

web2py: module function that behaves normally in shell fails browser mode

我有一个非常简单的辅助函数,可以帮助我为我正在使用的 javascript 框架创建列定义。

def tocol(fields,title=None,width=None,attributes=None):
    cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
    cols["field"] = fields
    return cols

当我在 web2py 中尝试此操作时 shell 结果如我所料:

In [15]: col = tocol(attr.columns.tolist())
In [16]: col
Out[16]: {'field': ['l1', 'pw', 'bw', 'tilt']}

但是当我在一个视图中尝试同样的事情时,我得到以下回溯:

Traceback (most recent call last):
  File "/home/tahnoon/web2py/gluon/restricted.py", line 224, in restricted
    exec ccode in environment
  File "/home/tahnoon/web2py/applications/apollo/controllers/performance.py", line 788, in <module>
  File "/home/tahnoon/web2py/gluon/globals.py", line 392, in <lambda>
    self._caller = lambda f: f()
  File "/home/tahnoon/web2py/applications/apollo/controllers/performance.py", line 561, in pa_equity
    cols = tocol(attr.columns.tolist())
  File "applications/apollo/modules/helpers.py", line 33, in tocol
    cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
  File "applications/apollo/modules/helpers.py", line 33, in <genexpr>
    cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
  File "<string>", line 1, in <module>
NameError: name 'title' is not defined

可能有人知道这里出了什么问题吗?很迷惑。

谢谢

看起来您只是想从字典中删除 None 值,所以为什么不创建一个函数来执行此操作:

def remove_none(d):
    [d.pop(key) for key in d.keys() if d[key] is None]

那么你可以这样做:

col = remove_none(dict(field=attr.columns.tolist(),
                       title=None, width=None, attributes=None))

或者如果您想直接输入参数::

def remove_none_dict(**d):
    [d.pop(key) for key in d.keys() if d[key] is None]
    return d

col = remove_none_dict(field=attr.columns.tolist(),
                       title=None, width=None, attributes=None))