【问题标题】:Username Password retrieval用户名密码找回
【发布时间】: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=?)。

标签: python mysql kivy


【解决方案1】:

根据docs

如果 x 是 s 的成员

x in s 计算结果为 True,否则计算结果为 False。

records = [
    {
        'username': 'sample_username', 
        'password': 'sample_password'
    },
    {
        'username': 'sample_username2', 
        'password': 'sample_password2'
    }
]

records成员 是两个字典,而 self.username 是一个字符串。因为records 没有属于成员 的str,所以self.username 不能是记录列表中的in

相反,您需要执行以下操作:

for record in records:
    if record["username"] == "sample_username":
       print("That username is stored")
    if record["password"] == "sample_password":
        print("That is a valid password")

输出:

That username is stored
That is a valid password

(但请注意:该密码对该用户名无效)

要检查有效的用户名和匹配的密码,您需要这样做:

for record in records:
    if (record["username"] == "sample_username" 
        and record["password"] == "sample_password"):

       print("Valid user!")

当你尝试这个时:

login_list = []
    for record in results:
           login_list.append(record)

您所做的只是将每个 dict 移动到另一个列表中,并且再一次找不到 str 类型 in dict 类型列表。

如果你有这样的事情:

records = [
    {
        'username': 'sample_username', 
        'password': 'sample_password'
    },
    {
        'username': 'sample_username2', 
        'password': 'sample_password2'
    },

    "some string"
]

然后你会看到输出'yes':

if "some string" in records:
       print("yes")

在这种情况下,记录的三个成员是两个dict和一个str。

文档继续说:

in 测试字典是否有给定的键。

这意味着你可以这样写:

for record in records:
    if 'username' in record:
        print('yes')

--output:--
yes
yes

但这对你没有帮助。

【讨论】:

  • 非常感谢您的帮助。这解决了这个问题,并且真的帮助我学会了以字典格式设置我的 for 循环,而不是仅仅调用字符串。这是一个很大的帮助。谢谢。
猜你喜欢
  • 2016-05-13
  • 2010-09-05
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 2011-05-02
相关资源
最近更新 更多