AttributeError:'int'对象没有属性'encode'

时间:2011-11-14 19:34:37

标签: python django mechanize

我继承了一个抛出以下错误的python脚本:

root        : ERROR    Unexpected exception encountered in application 'ImagesForWeb'
Traceback (most recent call last):
  File "build/bdist.linux-i686/egg/columbiancommon/scaffolding/consoleapp.py", line 169, in run_safe
    self.run(**kwargs)
  File "/var/scripts/ImagesForWeb/imagesforweb.py", line 102, in run
    gallery = columbiancommon.EllingtonPhotoGallery(configobj = self.cmgr)
  File "build/bdist.linux-i686/egg/columbiancommon/ellington/photogallery.py", line 51, in __init__
    self.Reload()
  File "build/bdist.linux-i686/egg/columbiancommon/ellington/photogallery.py", line 128, in Reload
    self.SetStatus(self.status)
  File "build/bdist.linux-i686/egg/columbiancommon/ellington/photogallery.py", line 68, in SetStatus
    self.SetControl("status", [self.status.encode('utf-8', 'replace')])
AttributeError: 'int' object has no attribute 'encode'

我对Python很陌生,并且还没有完全掌握调试技巧,知道如何解决这个问题。

以下是上述错误中引用photogallery.py的代码段:

def SetStatus(self, status):
    """
    Sets the publication status of this photo gallery.

    Expects to be set to an integer constant, shortcuts include::

        EllingtonPhotoGallery.LIVE
        EllingtonPhotoGallery.DRAFT
        EllingtonPhotoGallery.DELETED
        EllingtonPhotoGallery.UNREVIEWED

    """
    if(not isinstance(status, int)):
        raise EllingtonMechanizeException("Unexpected status value.  Please use a status constant.")
    self.status = status
    self.SetControl("status", [self.status.encode('utf-8', 'replace')])

这是在scaffolding.py

中的SetControl方法
def SetControl(self, control_name, control_value_unclean):
    """
    Raw access to the mechanize method of setting controls to specific values.

    **WARNING** Do not use this unless you have a really good reason to do so-- `EllingtonMechanizeScaffolding.SetControlToValue`
    and `EllingtonMechanizeScaffolding.SetControlToValueSafe` are much more elegant solutions.

    :Parameters:
        - `control_name`: The name of the control you're trying to assign a value to.
        - `control_value_unclean`: The value to assign to said control.  Either a boolean value, 

    """
    self.browser[control_name] = control_value_unclean
    return True

我认为这是说self.SetControl("status", [self.status.encode('utf-8', 'replace')]) 抛出错误的行,但是我不知道为什么错误正在发生。自从我6个月前继承它以来,代码一直在运行,并且我的结果并未改变。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:8)

您首先声明statusint的一个实例,然后您尝试使用它没有的encode方法,因为它是unicode方法。如果要将整数转换为字符串,请使用unicode(self.status)。然后你就可以使用encode,尽管你很可能不会这样做。

答案 1 :(得分:0)

使用repr()功能。该函数可以处理unicode,utf,null和int。这个函数的很好的部分是,当将unicode(如encode('utf-8'))或ascii转换为字符串时,此函数不会丢失任何值。此函数还为表示提供了大小限制,因此您可以更灵活地使用对象。