访问python类实例变量时出错

时间:2018-10-04 18:11:30

标签: python python-3.x google-app-engine google-cloud-platform

访问类实例变量并分配它们时出现错误。当我使用格式函数转换实例变量值时,它运行良好。

抛出错误的代码:

task.update({
    'email': self.email,

错误

raise ValueError('Unknown protobuf attr type', type(val))
ValueError: ('Unknown protobuf attr type', <class 'tuple'>)

使用格式功能时有效的代码:

logger.log_text('email {}'.format(self.email))

创建类实例

user = User(post_data)
user.create()

班级

class User(object):
""" User Model for storing user related details """
__tablename__ = 'Users'

def __init__(self, data, admin=False):
    bcrypt = Bcrypt()
    self.email = data.get('email'),
    self.password = bcrypt.generate_password_hash(
        data.get('email'), 12
    ).decode()
    self.is_admin = admin
    self.firstname = "firstname"
    self.middlename = "middlename"
    self.lastname = "lastname"
    self.address = "address"
    self.is_active = True
    self.ds = datastore.Client()

def create(self):
    """
    Create User
    :return: string
    """
    logger.log_text("create user")
    with self.ds.transaction():
        incomplete_key = self.ds.key(self.__tablename__)
        task = datastore.Entity(key=incomplete_key)
        task.update({
            'email': self.email,
            'password': '{}'.format(self.password)
        })
        self.ds.put(task)

1 个答案:

答案 0 :(得分:2)

这是一个很容易犯的错误:在此行上有一个逗号逗号:

self.email = data.get('email'),

self.email变成一个元组。例如:

>>> a = 'hi'
>>> type(a)
<class 'str'>
>>> b = 'hi',
>>> type(b)
<class 'tuple'>