【发布时间】:2018-07-27 09:46:30
【问题描述】:
我正在 Kivy 中创建一个应用程序。我正在创建一个登录页面,允许用户输入密码和用户名,以验证他们以前是否使用过我的应用程序。我将用户名和密码存储在名为“users”的 MySQL 数据库中,该表名为“login”,将用户名和密码信息存储在两列中。我正在使用 pymysql 库与我的 Python 代码和我的 MySQL 数据库进行交互。
在我的 Python 代码中,我使用 fetchall() 方法从 MySQL 获取所有用户名和密码列和行,并将这些数据存储在一个变量中。当我打印出该数据时,我会得到一个字典列表,其中显示以下内容:
[{'username': 'sample_username', 'password': 'sample_password'},
{'username': 'sample_username2', 'password': 'sample_password2'}]
正如您在 MySQL 中看到的,我创建了几个示例用户名和示例密码,当使用 fetchall() 方法时,它们存储在列表中的字典中。
接下来我在 Kivy 中为用户名创建了一个文本输入框,为用户名创建了一个文本输入框 密码。我将用户输入存储在用户名和密码的变量中,如下所示:
self.username = self.ids.textinput_username.text
self.password = self.ids.textinput_username.text
然后,在我使用 fetchall() 方法后,我会检查用户输入的用户名和密码是否与我的代码中已经存在的用户名或密码匹配。
if self.username in results:
print("That username is stored")
if self.password in results:
print("That is a valid password")
但是,该代码根本没有返回任何内容。好像Python不能 跟踪用户输入的用户名,并且无法检查它是否在我使用 fetchall 方法后得到的结果中。我什至尝试将结果存储在一个列表中,然后让 Python 检查用户名和密码字符串是否在列表中的任何位置。
login_list = []
for record in results:
login_list.append(record)
if self.username in login_list:
print("That username is valid")
if self.password in login_list:
print("That password is valid")
但是,当我输入它时,我遇到了同样的问题。 Python什么都不做,也不会执行条件语句。我连接到 pymysql 和我的 MySQL 数据库,并将我的所有登录信息存储在一个模块中并导入它。我知道我已正确连接,因为当我在列表中打印字典时,它会获取我存储在 MySQL 中的所有信息。这是我的完整代码,减去导入:
class WelcomeScreen(Screen):
#A basic welcome screen. All of the functionality is in the .kv file
pass
class LoginScreen(Screen):
'''
Model a screen for the user to enter a username
and password.
'''
def store_username_password(self):
'''
get the username and password from textinput.
Check to see if the username and password is
stored in mysql database. If not, give the
user an error message
'''
#Create a variable to store the username entered in textinput
self.username = str(self.ids.textinput_username.text)
#Create a variable to store the password entered in textinput
self.password = str(self.ids.textinput_password.text)
#select the login table from the patient_support database
cur.execute("""SELECT * FROM login""")
#Use the fetchall method of the cursor object to get the info
results = cur.fetchall()
#If username and password entered in results, print statements
if self.username in results:
print("That is a valid username")
if self.password in results:
print("That is a valid password")
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("patientsupport.kv")
class PatientSupport(App):
def build(self):
return presentation
if __name__=='__main__':
PatientSupport().run()
【问题讨论】:
-
你能不能把每一步都描述得一清二楚,只把问题限制在确切的问题上?事实上,它有点像 tl;dr。例如,如果获取了结果,那么我们就不会关心它,所以不需要专门为此设置一个完整的段落。太啰嗦了
-
为了让您指出正确的方向,请查看此 CR 线程:codereview.stackexchange.com/questions/124191/…。我怀疑您的问题与检查结果集中是否存在有关,并且该线程中的答案讨论了如何使用参数化查询来提高效率,以及执行类似的任务。
-
您不应在 Python 中获取所有记录并进行匹配。至少从数据库中仅获取匹配的用户名 (
SELECT * FROM users WHERE username=?)。