2个元组在打印时相同,并且处于unicode但是在比较时它们与Python 2.7不匹配

时间:2014-12-07 02:12:28

标签: python python-2.7 sqlite tuples cgi-bin

我试图从sqlite3数据库中获取数据,我知道这个数据库使用cursor.fetchone()返回一个元组但是由于某种原因,当另一个程序上的用户是CGI脚本时提交数据并且我接受了并在密码中打印2匹配,所以当我尝试比较它们时,它们永远不匹配:

#!/usr/bin/python

import sqlite3 as lite
import cgi

db = lite.connect('qwerty0987654321.db')
usrnme = "none"
passwd = "none"
passver = "none"

def main():
    global usrnme
    global passwd
    print "Content-type:text/html\r\n\r\n"
    print "<html>"
    print "<head><title>Profile</title></head>"
    print "<body>"

    form = cgi.FieldStorage()
    if form.getvalue('username'):
        usrnme = form.getvalue('username')
        if form.getvalue('passwd'):
            passwd = form.getvalue('passwd')
            if isauth() is True:
                print "Welcome %s" % usrnme
            elif isauth() is False:
                print "Wrong username or password!"
        else:
            print "No Password!"
    else:
        print "No Username!"
    print '</body>'
    print '</html>'

def isauth():
    global usrnme, passwd, passver
    c = db.cursor()
    c.execute("SELECT password FROM Users WHERE username = ?",(usrnme,))
    passver = c.fetchone()[0]
    passver = tuple(passver,)
    passwd = tuple(passwd[0],)
    if cmp(passwd,passver) == 0:
        return True
    else:
        print(passver,passwd)
        return False


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

您的错误似乎在此处:passwd[0]。因为str可以被索引,所以它将引用str中第一个位置的字符。那将是'n'

passver = c.fetchone()[0]  # get the first field in the first item in the result set
passver = tuple(passver,)  # add it to a tuple.
passwd = tuple(passwd[0],) # add passwd[0] (n) to a tuple

那不会奏效。请尝试改为:

passver = c.fetchone()[0]  # get the first field in the first item in the result set
passver = tuple(passver,)  # add it to a tuple.
passwd = tuple(passwd,)    # add all of passwd to a tuple
# comparrison should succeed depending on contents of Users