|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
《零基础入门学习Python》前50课视频看完至今差不多有个把月了,这个周末想起来做一个<密码生成器工具程序>来将目前学到的东西运用一下,采用函数式编程,并且使用了pickle、time、os.path和random四个模块来实现密码和用户数据的读取、保存(标记时间戳),纯粹是按照自己的一点念头打发时间而已,估计很多不足的地方,连同注释有200多行,也是学习小甲鱼视频为止编写的最长的程序了。代码如下,有高手可以指点一下,目前没有详细调试,约摸运行了一下,没发现错误就发出来了,也是为了完成第38课课后作业,提交一个自己的作品,请指教。
- # -*- coding: utf-8 -*-
- #
- # 程序CipherFactory.py
- """
- # |----- CipherFactory小程序用于生成 "多位数无规律密码字符串 -----|"
- #
- # 注明:分别导入了pickle模块、os.path模块、random模块和time模块
- #
- # 1. pickle模块用于将用户数据以二进制格式存储到本地文件系统
- #
- # 2. os.path模块用于创建、读取和搜索本地文件
- #
- # 3. time模块用来生成密码的时间戳
- # |----- 各函数组件用途说明 -----|"
- #
- # 1. password_generate()函数用于生成并返回特定位数的无规则密码字符串
- #
- # 2. user_ui()函数用于描述注册用户的使用界面的功能选项
- #
- # 3. new_user_ui()函数用于描述新用户在初次使用的程序接口
- #
- # 4. read_register()函数用于读取本地注册信息,验证注册用户
- #
- # 5. whether_read_cipher()函数用于显示用户操作生成过的所有密码字符串
- #
- # 6. get_localtime()函数用于标记密码字符串生成时的时间戳
- #
- # 7. whether_save_cipher()函数用于为新用户保存密码
- #
- # 8. save_user_information()函数用于为新用户创建本地注册信息并写入注册文件
- """
- import pickle
- import os.path
- import random as r
- import time as tm
- def password_generate():
- """按照指定位数生成字母、数字混合而成的密码(不分大小写)"""
-
- while True:
- cipher_bit = input("请输入密码位数 [In]:")
- if cipher_bit.isdigit():
- cipher_bit = int(cipher_bit)
- break
- else:
- print("Input Error.请重新输入!")
- continue
- # 密码所用原始字符集合
- pwd_str = "0123456789abcdefghijklmnopqrstuvwxyz"
- # 待重组的密码字符集
- new_str = ""
- # 最后生成的用户密码
- user_cipher = ""
-
- # 采用类似费雪耶茨算法打乱原始密码字符串
- #
- # 每次循环产生一个随机的索引值,然后以索引值为断点切片重组psw_str原始字符集;
- #
- # 原始字符集有多少个字符就循环多少次,以此打乱全部字符的相对位置
- #
- # 以重组后的新字符串作为密码生成器,生成指定位数的密码;
- #
- # 生成完毕,返回指定位数的用户密码的字符串
- loop = len(pwd_str)
- while loop:
- point = r.randint(0, len(pwd_str)-1)
- new_str = pwd_str[point:] + pwd_str[0:point]
- loop -= 1
-
- while cipher_bit:
- user_cipher += r.choice(new_str)
- cipher_bit -= 1
- return user_cipher
- def user_ui():
- """注册用户登陆选项界面"""
- ui_describe = "\n\n==== * 欢迎使用CipherFactory小程序 * ====\n"
- ui_describe += "\n-- 1.用户登陆(Enter:'u')"
- ui_describe += "\n-- 2.用户注册(Enter:'r')"
- ui_describe += "\n-- 3.密码生成(Enter:'p')"
- ui_describe += "\n-- 4.退出程序(Enter:'q')"
- ui_describe += "\n请选择 >>> "
- print(ui_describe, end="")
- register_user_choice = input()
- return register_user_choice
- def new_user_ui():
- """新用户登陆选项界面"""
- new_ui_describe = "\n\n==== * 欢迎使用CipherFactory小程序 * ====\n"
- new_ui_describe += "\n-- 密码生成(Enter:'p')"
- new_ui_describe += "\n-- 退出程序(Enter:'q')"
- new_ui_describe += "\n请选择 >>> "
- print(new_ui_describe, end="")
- new_user_choice = input()
- return new_user_choice
- def get_localtime():
- """为生成的密码标记时间戳"""
-
- # 首先调用time.time()生成1970年至今的时间间隔秒数
- time_interval = tm.time()
-
- # 然后用time.localtime()方法将时间间隔转换成本地时间
- local_time = tm.localtime(time_interval)
-
- # 最后用time.strftime()方法格式化本地时间,形成格式化时间戳
- time_stamp = tm.strftime("%Y-%m-%d <%H:%M:%S>", local_time)
-
- # 返回时间戳
- return time_stamp
-
- def whether_save_cipher(user_pwd, time_stamp):
- """将生成的密码通过pickle模块保存到本地usercipher.plk文件"""
-
- # 用于存储用户密码的.pkl文件
- file_name = "usercipher.pkl"
-
- # 将密码字符串和时间戳存储为字典格式
- pwd_information = {}
- pwd_information["密码Cipher"] = user_pwd
- pwd_information["时间Time"] = time_stamp
-
- # 创建本地pkl文件并保存密码和生成时间两项信息
- try:
- with open(file_name, "ab") as pickle_file_object:
- pickle.dump(pwd_information, pickle_file_object)
- except OSError:
- print(" ---> 内容未能写入指定文件 <--- ")
- def whether_read_cipher():
- """读取本地usercipher.pkl文件,显示所有已保存的历史密码字符串"""
-
- file_name = "usercipher.pkl"
- with open(file_name, "rb") as file_object:
- try:
- while True:
- pwd_information = pickle.load(file_object)
- if pwd_information:
- print("% 23s" % pwd_information["密码Cipher"], end="")
- print("% 23s" % pwd_information["时间Time"])
- continue
- else:
- break
- except EOFError:
- print("=================== End ===================")
- def save_user_information(user_name):
- """
- # 根据新用户输入的用户名创建本地注册文件,实现登陆操作
- # 以字典格式保存注册用户信息;
- """
-
- user_information = {}
- user_information["用户名"] = user_name
- user_access = input("请输入今后的访问密码[In]:")
- user_information["访问密码"] = user_access
- try:
- with open("register_user_list.pkl", "ab") as rfile:
- pickle.dump(user_information, rfile)
- print("您的信息已保存完毕 >>> ")
- except OSError:
- print("未知原因,注册失败......")
- def read_register():
- """读取本地注册文件,获得注册用户数据"""
- try:
- with open("register_user_list.pkl", "rb") as rfile:
- user_information = pickle.load(rfile)
-
- except FileNotFoundError:
- print("用户文件被破坏,无法读取用户信息...")
- user_name = user_information["用户名"]
- user_pwd = user_information["访问密码"]
- # 返回读取到的文件内容
- return user_name, user_pwd
-
-
- """以下为主程序部分,调用函数实现既定功能"""
- while True:
- # 调用generate_function模块中的user_ui函数,显示用户界面
- if os.path.isfile("register_user_list.pkl"):
- register_user_choice = user_ui()
- # 根据用户的输入完成指定任务
- if register_user_choice == "q":
- break
- # 生成随机密码,并询问用户是否保存
- elif register_user_choice == "p":
- user_pwd = password_generate()
- print("\n-- 密码已生成 >>> " + "[ " + user_pwd + " ]\n")
- save_choice = input("是否保存密码序列?(Y / N):")
- if save_choice == "Y" or save_choice == "y":
- time_stamp = get_localtime()
- whether_save_cipher(user_pwd, time_stamp)
- continue
- else:
- print("密码未保存,请继续......")
- continue
-
- # 进入用户登陆验证操作,读取本地注册文件,以便验证用户真伪
- elif register_user_choice == "u":
- register_user_information = read_register()
- while True:
- input_user_name = input("请输入您的用户名:")
- # 验证输入的用户名和本地注册用户名是否相同
- if input_user_name != register_user_information[0]:
- print("警告!>>> 用户名错误,请重新输入......")
- continue
- else:
- # 如果用户名正确,则验证用户密码
- while True:
- input_user_pwd = input("请输入您的密码:")
- if input_user_pwd != register_user_information[1]:
- print("密码错误,请重新输入:")
- continue
- else:
- print("验证通过,进入程序......")
- print("==================< 历史纪录 >==================")
- whether_read_cipher()
- break
- break
- elif register_user_choice == "r":
- print("come soon.\n")
- continue
- # 如果是首次运行本程序,则调用new_user_ui()函数显示新用户界面
- else:
- new_user_choice = new_user_ui()
- if new_user_choice == "q":
- break
- elif new_user_choice == "p":
- user_pwd = password_generate()
- print("\n-- 密码已生成 >>> " + "[ " + user_pwd + " ]\n")
- save_choice = input("是否保存密码序列?(Y / N):")
- if save_choice == "N" or save_choice == "n":
- continue
- elif save_choice == "Y" or save_choice == "y":
- message = "请输入一个您喜欢的用户名[键入Q或q退出,将不保存]:"
- user_name = input(message)
- if user_name == "Q" or user_name == "q":
- break
- else:
- save_user_information(user_name)
- time_stamp = get_localtime()
- whether_save_cipher(user_pwd, time_stamp)
复制代码 |
|