显示UnicodeWarning的SQLAlchemy:Unicode等于比较失败

时间:2017-02-07 20:37:36

标签: python sqlalchemy

我从Google AppEngine收到以下错误,但我没有任何堆栈跟踪也没有更多详细信息可以找到问题的根源,我希望有人能够了解更多有关情况的信息来帮助我:< / p>

  

/base/data/home/apps/s~myproject-prod/20170207t172637.399025232647613201/lib/sqlalchemy/sql/type_api.py:359:   UnicodeWarning:Unicode等同比较无法转换两者   Unicode的参数 - 将它们解释为不相等

     

返回x == y

这里是代码的来源:

data = request.get_json()
client_email = clean_str(data.get('email', None))
client = Client.query.filter(Client.email == client_email)
if client is None:
    client = Client(data)
else:
    client.update(data)

client.save()  # ERROR IS THROWN HERE
# I was able to trace it here by logging some text before/after the error.

模特:

class Client(db.Model):
    __tablename__  = 'clients'

    id             = db.Column(db.Integer, primary_key=True)
    name           = db.Column(db.String(250), nullable=True, default=None)
    email          = db.Column(db.String(250), nullable=False, index=True)

    details        = db.Column(types.JSON(none_as_null=True), default=None)

    def __init__(self, client_infos):
        self.email = client_infos['email'].lower()
        del(client_infos['email'])
        self.details = json.dumps(client_infos)

    def update(self, data):
        # Some treatment of the data, removing some fields, etc
        self.details = json.dumps(data)

    def save(self, commit=True):
        db.session.add(self)
        if commit:
            db.session.commit()
        return self

clean_str函数:

def clean_str(value):
    if not isinstance(value, (str, unicode)):
        return value

    try:
        value = unicode(value, 'utf-8', errors='ignore')
    except:
        pass

    try:
        value = value.encode('utf-8')
    except:
        pass

    return value

有人知道为什么我会收到这个错误吗?是因为types.JSON

1 个答案:

答案 0 :(得分:1)

我还没有对此进行过测试,但似乎问题是您正在尝试将 Client.email (这是一个字符串)与您在 clean_str 功能。

一种可能的解决方案是将用户输入转换为Python字符串而不是unicode。但是如果由于某种原因你需要输入unicode,这可能会导致问题。

我推荐的另一个解决方案是使用SQLAlchemy将String类型转换为unicode。您需要将模型修改为:

email = db.Column(db.String(250), nullable=False, index=True, convert_unicode=True)

这基本上会告诉SQLAlchemy将数据库返回的值转换为unicode。你可以在这里读更多关于它的内容: http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.String.params.convert_unicode