实现用户注册与校验+Python文件读写操作

一、基础功能需求

版本一:

版本二

二、功能代码实现

1.结构设计

 

 

 2.代码实现

# from exercise.common import check_username, check_password, check_phone
from exercise.common import *   # 可以一口气全部引用,但是不推荐

# username = ''
# password = ''
# phone = ''

def input_username():
    # global username
    username = input("请输入用户名:")
    if check_username(username):
        print("用户名正确.")
        return username
    else:
        print("用户名错误.")
        input_username()    # 递归调用函数自身,完成循环的功能

def input_password():
    # global password
    password = input("请输入密码:")
    if check_password(password):
        print("密码正确.")
        return password
    else:
        print("密码错误.")
        input_password()

def input_phone():
    # global phone
    phone = input("请输入手机号:")
    if check_phone(phone):
        print("手机号正确.")
        return phone
    else:
        print("手机号错误.")
        input_phone()


def do_reg():
    username = input_username()
    password = input_password()
    phone = input_phone()

    user_list = []
    user = {'username': username, 'password': password, 'phone': phone}
    user_list.append(user)

    print(user_list)


if __name__ == '__main__':
    do_reg()

三、Python文件读写操作

1.common.py

import re, pymysql
from pymysql.cursors import DictCursor

'''
长度的判断5-12位,使用len函数进行判断
不能以数字开头:username[0]不能是0-9的范围
如何判断只能是大小写或数字:
返回值:True: 用户名正确, False: 用户名错误
'''
def check_username(username):
    if len(username) < 5 or len(username) > 12:
        return False

    if username[0] >= '0' and username[0] <= '9':
    # if not (username[0] < '0' or username[0] > '9'):
        return False

    for char in username:
        if not (ord(char) in range(65, 91) or ord(char) in range(97, 123) or ord(char) in range (48, 58)):
            return False

    return True


'''
检查密码:由大写、小写和数字构成,且必须是6~15位
只要确保密码中至少有1位是大写,至少有1位是小写,至少有1位是数字
'''
def check_password(password):
    if len(password) < 6 or len(password) > 12:
        return False

    lower = 0
    upper = 0
    digit = 0
    other = 0

    for char in password:
        if char >= 'A' and char <= 'Z':
            upper += 1
        elif char >= 'a' and char <= 'z':
            lower += 1
        elif char >= '0' and char <= '9':
            digit += 1
        else:
            other += 1

    if upper < 1 or lower < 1 or digit < 1 or other > 0:
        return False

    return True

# 检查电话号码
def check_phone(phone):
    pattern = "^1[3-9]\d{9}$"
    if re.match(pattern, phone):
        return True
    else:
        return False



# 读取CSV,并动态将第一行处理为字典的Key,返回[{},{}]的格式
def read_csv(csvfile, has_column=True):
    with open(csvfile) as f:
        line_list = f.readlines()

    if not has_column:
        raise Exception('CSV文件必须要使用第一行作为列名')
        # return None

    key_list = line_list[0].strip().split(',')

    list = []
    for i in range(1, len(line_list)):
        temp_list = line_list[i].strip().split(',')

        dict = {}
        for j in range(len(temp_list)):
            dict[key_list[j]] = temp_list[j]

        list.append(dict)

    return list


# 读取csv文件,并检查用户名是否存在
def check_user_exists(username):
    user_list = read_csv('./userpass.csv')
    for user in user_list:
        if user['username'] == username:
            return True

    return False

# 根据用户名取得CSV文件中对应的一行用户数据,以字典的形式返回
def check_get_user(username):
    user_list = read_csv('./userpass.csv')
    for user in user_list:
        if user['username'] == username:
            return user

    return None


# 修改用户的密码,修改一个CSV文件中的某一行中的某一列,不能直接修改(Python中不存在文件内容部分修改的操作)
# 将CSV整体读入到内存中,形成列表+字典,然后修改字典的某一项,再整体写入到CSV(覆盖写入)
def change_password(username, newpass):
    csv_list = read_csv('./userpass.csv')
    for user in csv_list:
        if user['username'] == username:
            index = csv_list.index(user)
            break
    csv_list[index]['password'] = newpass
    # 将列表+字典还原成行+逗号分隔数据
    with open('./userpass.csv', mode='w') as f:
        f.write("username,password,phone\n")
        for user in csv_list:
            line = f"{user['username']},{user['password']},{user['phone']}\n"
            # print(line)
            # line = line.replace("'","")
            f.write(line)


# 针对数据库连接进行封装操作
def query_mysql(sql):
    conn = pymysql.connect(host='localhost', user='root', password='', database='learn', charset='utf8')
    cursor = conn.cursor(DictCursor)
    cursor.execute(sql)
    result =cursor.fetchall()
    conn.close()
    return result

def update_mysql(sql):
    conn = pymysql.connect(host='localhost', user='root', password='', database='learn', charset='utf8')
    cursor = conn.cursor(DictCursor)
    cursor.execute(sql)
    conn.commit()
    conn.close()

# 利用异常处理改造查询函数
def query_mysql_2(sql):
    try:
        conn = pymysql.connect(host='localhost', user='root', password='123456', database='learn', charset='utf8')
        cursor = conn.cursor(DictCursor)
        cursor.execute(sql)
        result =cursor.fetchall()
        return result
    except:
        # print("数据库处理出错.")
        raise Exception("数据库处理出错.")     # 主动抛出异常,让程序停止
        # pass
    finally:
        conn.close()



# 最基本最简单的单元测试代码:半自动化测试代码
print(check_username('qiang'))
print(check_username('132457'))
print(check_username('Q132457'))

# 全自动的单元测试代码,编写一个测试驱动程序
def test_driver(func, expect, *args):
    actual = func(*args)
    if actual == expect:
        print("测试 %s: 成功" % func.__name__)
    else:
        print("测试 %s: 失败" % func.__name__)

if __name__ == '__main__':
    pass
    #测试用户名的规则
    test_driver(check_username, False, 'hi')
    test_driver(check_username, False, 'welcomeToWoniu123')
    test_driver(check_username, True, 'qiang')
    test_driver(check_username, False, '132457')
    test_driver(check_username, True, 'Q132457abc')
    test_driver(check_username, False, 'Q13#@%$bc')

    # 测试密码的规则,TDD:Test-Driven Development
    test_driver(check_password, False, 'qiang')
    test_driver(check_password, False, 'welcomeToWoniu1231235')
    test_driver(check_password, False, 'WELCOME')
    test_driver(check_password, False, '12349234')
    test_driver(check_password, False, 'jojojoju1')
    test_driver(check_password, False, 'WILL12432')
    test_driver(check_password, True, 'Woniu123')
    test_driver(check_password, False, 'Woniu@#123')

    test_driver(check_phone, False, '1881234567')
    test_driver(check_phone, False, '188123456799')
    test_driver(check_phone, False, '988123456799')
    test_driver(check_phone, False, '128123456799')
    test_driver(check_phone, True, '13812345679')

2.verson1.py

# from exercise.common import check_username, check_password, check_phone
from exercise.common import *   # 可以一口气全部引用,但是不推荐

# username = ''
# password = ''
# phone = ''

def input_username():
    # global username
    username = input("请输入用户名:")
    if check_username(username):
        print("用户名正确.")
        return username
    else:
        print("用户名错误.")
        input_username()    # 递归调用函数自身,完成循环的功能

def input_password():
    # global password
    password = input("请输入密码:")
    if check_password(password):
        print("密码正确.")
        return password
    else:
        print("密码错误.")
        input_password()

def input_phone():
    # global phone
    phone = input("请输入手机号:")
    if check_phone(phone):
        print("手机号正确.")
        return phone
    else:
        print("手机号错误.")
        input_phone()


def do_reg():
    username = input_username()
    password = input_password()
    phone = input_phone()

    user_list = []
    user = {'username': username, 'password': password, 'phone': phone}
    user_list.append(user)

    print(user_list)


if __name__ == '__main__':
    do_reg()

3.verson2.py

from exercise.common import *   # 可以一口气全部引用,但是不推荐

def input_username():
    username = input("请输入用户名:")
    if check_username(username):
        if check_user_exists(username):
            print("用户名已存在.")
            return input_username()
        else:
            print("用户名正确.")
            return username
    else:
        print("用户名错误.")
        return input_username()    # 递归调用函数自身,完成循环的功能

def input_password():
    password = input("请输入密码:")
    if check_password(password):
        print("密码正确.")
        return password
    else:
        print("密码错误.")
        return input_password()

def input_phone():
    phone = input("请输入手机号:")
    if check_phone(phone):
        print("手机号正确.")
        return phone
    else:
        print("手机号错误.")
        return input_phone()

def do_reg():
    username = input_username()
    password = input_password()
    phone = input_phone()

    with open('./userpass.csv', mode='a') as f:
        f.write(f"\n{username},{password},{phone}")
        print("恭喜你,注册成功.")

    draw_menu()

def do_login():
    username = input("请输入用户名:")
    password = input("请输入密码:")
    user = check_get_user(username)
    if user is None:
        print("用户名不存在.")
        exit(0)
    elif user['password'] == password:
        print("用户名密码正确,登录成功.")
    else:
        print("登录失败.")

    draw_menu()

def do_change():
    username = input("请输入用户名:")
    password = input("请输入旧密码:")
    user = check_get_user(username)
    if user is None:
        print("用户名不存在.")
        draw_menu()
    elif user['password'] == password:
        newpass = input("请输入新密码:")
        change_password(username, newpass)
    else:
        print("旧密码验证不通过.")

def draw_menu():
    print("========= 欢迎使用用户管理系统 ===========")
    print("1、注册   2、登录   3、修改密码   4、退出")
    option = input("请选择菜单项:[1 2 3 4]:")
    if option == '1':
        do_reg()
    elif option == '2':
        do_login()
    elif option == '3':
        do_change()
    elif option == '4':
        exit(0)
    else:
        print("请输入正确的菜单编号.")
        draw_menu()

if __name__ == '__main__':
    # do_reg()
    # do_login()
    do_change()
    # draw_menu()

4.verson3.py

from exercise.common import *
def do_reg():
    username = input("请输入用户名:")
    result = query_mysql(f"select username from user where username='{username}'")
    if len(result) == 0:
        password = input("请输入密码:")
        phone = input("请输入手机号码:")
        update_mysql(f"insert into user(username, password, role, createtime) values('{username}', '{password}', 'user', now())")
    else:
        print("用户名已经存在,不允许注册.")

if __name__ == '__main__':
    do_reg()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值