500尝试与SQLite3数据库值进行比较时出错

时间:2017-03-14 21:02:58

标签: python http flask sqlite

我正在尝试从SQLite数据库加载用户名和密码字段,并将它们与用户为基本HTTP身份验证(n cheack_auth函数)输入的值进行比较。我可以使用retriveUser函数来获取用户并将其显示在模板中,但我似乎无法在烧瓶应用程序中使用它来进行比较以查看用户是否确实存在。

根据this我应该能够以返回的方式访问返回的dbuser中的项目,但它似乎不起作用。我是python的新手,所以我可能会遗漏一些基本的东西,但我不确定它是什么。

q = """
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL,
    password TEXT NOT NULL,
    phone TEXT NOT NULL
);
"""

con = sql.connect("database.db")
cur = con.cursor()
cur.execute(q)

# original code from https://gist.github.com/PolBaladas/07bfcdefb5c1c57cdeb5


def insertUser(username, password, phone):
    con = sql.connect("database.db")
    cur = con.cursor()
    cur.execute("INSERT INTO users (username,password,phone) VALUES (?,?,?)", (username,password,phone))
    con.commit()
    con.close()

def retrieveUsers():
    con = sql.connect("database.db")
    cur = con.cursor()
    cur.execute("SELECT username, password, phone FROM users")
    users = cur.fetchall()
    con.close()
    return users

def retrieveUser(username):
    con = sql.connect("database.db")
    cur = con.cursor()
    cur.execute("SELECT username, password FROM users WHERE username = (?)", [username])
    user = cur.fetchone()
    con.close()
    return user

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    dbuser = retrieveUser(username)
    return username == dbuser[0] and password == dbuser[1]

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

1 个答案:

答案 0 :(得分:0)

好吧我好像已经解决了这个问题。我的浏览器缓存了我的旧密码条目,导致搜索返回null。从retrieve用户函数返回的项只会在找到对象时返回为数组,否则返回null。在以下代码中检查null就解决了这个问题。

感谢Allie Fitter帮助我弄清楚如何访问docket日志,这些日志指出了我的问题。

以下是check_auth方法的结果代码:

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    dbuser = retrieveUser(username)
    if dbuser is not None:
        return username == dbuser[0] and password == dbuser[1]
    return False
相关问题