【问题标题】:Comparing tuples to strings比较元组和字符串
【发布时间】:2015-07-16 03:11:22
【问题描述】:

我正在尝试从数据库中的会话表中检索用户。在我的单元测试中,我得到一个错误:

line 138, in test_session_user
    self.assertEqual(nick_from_cookie, nick)
AssertionError: ('Bobalooba',) != 'Bobalooba'

我知道这是因为当测试将我的返回值与字符串进行比较时,我的代码返回了一个元组,因此它不匹配。

有没有办法让我使用元组进行比较,或者他们是查询我需要的结果的更好方法。下面是我使用的表格以及我的功能:

def session_user(db):
    """try to
    retrieve the user from the sessions table
    return usernick or None if no valid session is present
    """
    cursor = db.cursor()
    sessionid = bottle.request.get_cookie(COOKIE_NAME)
    usernick = None
    if sessionid:
        cursor.execute("SELECT usernick FROM sessions WHERE sessionid=?", (sessionid,))
        usernick = cursor.fetchone()
    return usernick

【问题讨论】:

    标签: python sqlite python-3.4 bottle


    【解决方案1】:

    使用

    row = cursor.fetchone()
    if row:
        usernick, = row
    

    注意元组的解包。

    【讨论】:

    • 当我尝试这个时,我得到一个错误'第 66 行,在 session_user usernick,= cursor.fetchone() TypeError: 'NoneType' object is not iterable'
    • 那么你的查询结果为空。在解压元组之前先检查一下。
    • 我该怎么做呢?抱歉,python 绝对不是我的强项。我是新手。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 2020-08-07
    • 2021-12-06
    相关资源
    最近更新 更多