You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python登录系统中根据用户类型展示对应菜单?

完善MySQL Python登录系统的grantAccess函数

修正后的完整代码

import os
from mysql.connector import connect  # 需先安装mysql-connector-python:pip install mysql-connector-python

class Login():
    # 完善grantAccess函数,接收用户类型参数区分身份
    @classmethod
    def grantAccess(cls, user_type):
        if user_type == "user":
            print("欢迎用户!")
            print("这是用户菜单!")
        elif user_type == "admin":
            print("欢迎管理员!")
            print("这是管理员菜单!")

    # 检查MySQL中用户是否存在
    @classmethod
    def userExists(cls, user_id):
        # 替换为你的数据库实际配置
        con = connect(host="localhost", user="root", password="your_password", database="your_db")
        # 用参数化查询避免SQL注入
        sqlSelect = "SELECT user FROM users WHERE id = %s"
        cursor = con.cursor()
        cursor.execute(sqlSelect, (user_id,))
        cursor.fetchall()
        exists = cursor.rowcount == 1
        con.close()  # 关闭数据库连接,避免资源泄漏
        return exists

    # 普通用户登录验证
    @classmethod
    def correctUsLogin(cls, user, password):
        con = connect(host="localhost", user="root", password="your_password", database="your_db")
        sqlSelect = "SELECT user, password FROM users WHERE user = %s AND BINARY password = %s"
        cursor = con.cursor()
        cursor.execute(sqlSelect, (user, password))
        cursor.fetchall()
        valid = cursor.rowcount == 1
        con.close()
        return valid

    # 管理员登录验证 - 修正拼写错误:corrrectAdLogin → correctAdLogin
    @classmethod
    def correctAdLogin(cls, user, password):
        con = connect(host="localhost", user="root", password="your_password", database="your_db")
        sqlSelect = "SELECT user, password FROM admins WHERE user = %s AND BINARY password = %s"
        cursor = con.cursor()
        cursor.execute(sqlSelect, (user, password))
        cursor.fetchall()
        valid = cursor.rowcount == 1
        con.close()
        return valid

    # 普通用户登录处理
    @classmethod
    def userLogin(cls, user, password):
        if cls.correctUsLogin(user, password):
            # 传入用户类型调用grantAccess
            cls.grantAccess("user")
        else:
            print("错误:用户名或密码不正确")
            input("按任意键继续...")
            os.system("cls")
            cls.start()

    # 管理员登录处理
    @classmethod
    def adminLogin(cls, user, password):
        if cls.correctAdLogin(user, password):
            # 传入管理员类型调用grantAccess
            cls.grantAccess("admin")
        else:
            print("错误:用户名或密码不正确")
            input("按任意键继续...")
            os.system("cls")
            cls.start()

    # 根据用户输入执行对应操作
    @classmethod
    def access(cls, opcion):
        if opcion == "1": # 普通用户登录
            print("---登录---")
            user_id = input("请输入ID:")
            password = input("请输入密码:")
            cls.userLogin(user_id, password)
        elif opcion == "3": # 管理员登录
            print("---登录---")
            user_id = input("请输入ID:")
            password = input("请输入密码:")
            cls.adminLogin(user_id, password)
        elif opcion == "2": # 注册功能预留
            print("注册功能待实现")
            input("按任意键继续...")
            os.system("cls")
            cls.start()

    # 系统启动入口
    @classmethod
    def start(cls):
        print('---麦哲伦“化石”博物馆---')
        opcion = input("用户登录(1) / 注册(2) / 管理员登录(3): ")
        if opcion not in ["1", "2", "3"]:
            print("错误:请输入正确选项")
            input("按任意键继续...")
            os.system("cls")
            cls.start()
        else:
            cls.access(opcion)

# 启动登录系统
if __name__ == "__main__":
    Login.start()

关键修改说明

  • grantAccess函数完善:新增user_type参数区分普通用户和管理员,根据参数输出对应欢迎语和菜单提示;将所有类方法改为@classmethod,统一用cls调用类内方法。
  • 修复安全隐患:替换原f-string拼接SQL的方式,使用参数化查询(%s占位符),彻底避免SQL注入风险。
  • 修正代码错误:
    • 管理员登录验证方法拼写错误corrrectAdLogin改为correctAdLogin
    • userExists方法中表名错误table改为users
    • 补充数据库连接必填参数(需替换为你的实际数据库配置)
    • 新增数据库连接关闭操作,避免资源泄漏
  • 优化调用逻辑:在userLogin和adminLogin中调用grantAccess时,传入对应的身份类型参数,确保函数能正确匹配身份输出内容。

内容的提问来源于stack exchange,提问作者ftft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:46:14