You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级web2py至2.27.1后上传图片遇'Field'无__dir__属性异常求助

Web2py 2.27.1升级后上传字段报错:Field object has no attribute 'dir'

近期通过pythonanywhere.com后台的「Check for upgrades」按钮将web2py应用升级至2.27.1版本后,提交包含上传属性的表单(示例代码:Field('logo', 'upload', label=SPAN('Your company logo')))时,出现*AttributeError: 'Field' object has no attribute 'dir'*错误,图片上传功能失效,此前该功能正常。

回溯信息

Traceback (most recent call last):
  File "/home/myapp/web2py/gluon/restricted.py", line 219, in restricted
    exec(ccode, environment)
  File "/home/myapp/web2py/applications/init/controllers/default.py", line 920, in <module>
  File "/home/myapp/web2py/gluon/globals.py", line 463, in <lambda>
    self._caller = lambda f: f()
  File "/home/myapp/web2py/applications/init/controllers/default.py", line 315, in business_registration
    if form.process().accepted:
  File "/home/myapp/web2py/gluon/html.py", line 2410, in process
    self.validate(**kwargs)
  File "/home/myapp/web2py/gluon/html.py", line 2349, in validate
    if self.accepts(**kwargs):
  File "/home/myapp/web2py/gluon/sqlhtml.py", line 2132, in accepts
    source_file, original_filename, field.uploadfolder
  File "/home/myapp/web2py/gluon/packages/dal/pydal/objects.py", line 2075, in store
    self._tablename if '_tablename' in self.__dir__() and self._tablename else 'no_table',
AttributeError: 'Field' object has no attribute '__dir__'

函数参数列表

filename='Kivy Documentation.pdf', path='/home/myapp/web2py/applications/init/static/business_docs')

报错相关代码片段

m = re.search(REGEX_UPLOAD_EXTENSION, filename)
        extension = m and m.group(1) or "txt"
        uuid_key = self._db.uuid().replace("-", "")[-16:] if self._db else uuidstr()
        encoded_filename = to_native(base64.urlsafe_b64encode(to_bytes(filename)))
        newfilename = "%s.%s.%s.%s" % (
            self._tablename if '_tablename' in self.__dir__() and self._tablename else 'no_table',
            self.name,
            uuid_key,
            encoded_filename,
        )

涉及文件

"/home/myapp/web2py/applications/init/controllers/appadmin.py", line 7

修复方案

方案1:替换__dir__()调用为dir()

编辑/home/myapp/web2py/gluon/packages/dal/pydal/objects.py文件,找到报错的第2075行,将:

self._tablename if '_tablename' in self.__dir__() and self._tablename else 'no_table',

修改为:

self._tablename if '_tablename' in dir(self) and self._tablename else 'no_table',

dir(self)是Python内置函数,会返回对象的属性列表,兼容性比直接调用self.__dir__()更好,因为并非所有对象都实现了__dir__方法。

方案2:改用hasattr()判断属性存在

更可靠的方式是使用hasattr()来检测字段对象是否拥有_tablename属性,修改为:

self._tablename if hasattr(self, '_tablename') and self._tablename else 'no_table',

这种方式更符合Python的最佳实践,避免依赖对象的__dir__实现。

修改后保存文件,重启web2py应用即可恢复上传功能。

内容的提问来源于stack exchange,提问作者Percy Godiraone Leburu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:10:55