發布時間: 2019-09-16 14:28:28
對于Python基礎語法和高級語法部分的綜合應用,實現一個功能簡單的資金管理系統。
2. 實驗代碼
2.1. 實驗思路
使用PyMySql連接操作數據庫,根據數據庫內的信息進行登錄判斷。成功登陸后進入系統歡迎界面,同時為成功登錄的用戶創建一個用戶對象,根據用戶作出的操作執行相應的方法,并同步到數據庫中。在操作結束后將此次操作打印出來(寫入本地文件)。
2.2. 實驗實現
步驟 1、創建數據庫和數據表
創建數據庫:
create database money;
創建數據表:
CREATE TABLE user(
username varchar(30) PRIMARY KEY,
pwd VARCHAR(100) NOT NULL,
start_time DATETIME NOT NULL,
end_time DATETIME NOT NULL,
balance FLOAT NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
**數據:
INSERT INTO user (username, pwd, start_time, end_time, balance)
VALUES ('admin','123456','2019.04.23', '2019.04.23',100.0);
INSERT INTO user (username, pwd, start_time, end_time, balance)
VALUES ('root','admin','2019.01.01', '2019.02.02',100.0);
步驟 2導入所需的庫,定義操作字典
安裝pymysql:pip install pymysql
import time
import sys
import pymysql
import getpass
action_dict = {1:"存款", 2:"取款", 3:"轉賬", 4:"修改密碼", 5:'退出'}
步驟 3、數據庫連接
考慮到系統中多次連接數據庫,而連接數據庫的語句相似性較高,所以將其封裝成為一個方法。
# 定義連接數據庫方法,sql為每次需要執行的數據庫操作語句,
def con_mysql(sql):
try:
db = pymysql.connect("localhost", "root", "root", "money", charset='utf8' )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# 使用execute方法執行SQL語句
cursor.execute(sql)
results = cursor.fetchone()# 查詢一條數據
print(results)
db.commit() # 提交至數據庫
except Exception as e:
db.rollback()
print("系統異常")
sys.exit()
db.close() # 關閉數據庫
return results
# 測試方法:
sql = "select * from user"
con_mysql(sql)
輸出結果:
圖3-1數據庫連接測試結果
步驟 4、定義用戶類
class Account(object):
def __init__(self, username, money, number=0):
self.money = money # 賬戶金額
self.username = username # 用戶名
# 上次登錄時間
self.start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.number = number
# 存款
def save(self):
self.money += self.number
print("已存入%f元" % (self.number))
# 取錢
def take(self):
if self.number > self.money:
print("余額不足")
self.money -= self.number
print("以取出%f元" % (self.number))
# 修改密碼
def update(self):
pwd = getpass.getpass("請輸入新密碼:")
sql = "update user set pwd=%s where username=%s" % (pwd, self.username)
return sql
# 轉賬
def transfer(self):
user = input("請輸入轉賬用戶:")
if self.number > self.money:
print("余額不足")
return
else:
sql = "select username from user where username='%s'" % (user)
result = con_mysql(sql)
if result == None:
print("轉賬用戶不存在")
self.number = 0
else:
return user
# 執行用戶所選的操作
def implement(self, action):
if action == 5:
sys.exit()
elif action == 1:
try:
self.number = float(input("請輸入存入得金額:"))
except Exception as e:
print("請輸入正確的金額")
self.save()
elif action == 2:
try:
self.number = float(input("請輸入取出的金額:"))
except Exception as e:
print("請輸入正確的金額")
self.take()
sql = "update user set balance=%f where username=%s" % (self.number, self.username)
con_mysql(sql)
elif action == 3:
try:
self.number = float(input("請輸入轉賬的金額:"))
except Exception as e:
print("請輸入正確的金額")
User = self.transfer()
if User:
sql = "update user set balance=%f where username=%s" % (self.number, User)
con_mysql(sql)
else:
self.update()
# 打印操作后的憑證
def voucher(self, end_time, action):
str_action = """用戶:%s \n操作:%s\n操作金額:%s\n登錄時間:
%s\n結束時間:%s""" % (self.username, action_dict[action], self.number, self.start_time, end_time)
with open("%s.txt" % (self.username), 'w') as f:
try:
f.write(str_action)
except Exception as e:
print("憑證打印失敗,請聯系管理員")
print("打印成功,請收好您的憑證")
步驟5、登陸功能
def login():
"""
用戶登錄檢測
:param username: 用戶賬號
:param pwd: 用戶密碼
:return:
"""
username = input("請輸入您的賬號:")
# pwd = getpass.getpass("請輸入您的密碼:")# 隱藏輸入的密碼
pwd = input("請輸入您的密碼:")
# 編寫SQL語句從數據庫獲取賬號信息
sql = "select * from user where username='%s'"%(username)
result = con_mysql(sql)
if result:
if result[1] == pwd:
user_account = Account(result[0], result[4])
return user_account
else:
print("賬號或密碼錯誤")
else:
print("賬號不存在")
# 測試登錄功能
user_account = login()
步驟6、歡迎界面
def welcome():
print(' *'*15)
print(" %s%30s"%("*","*"))
print(" %s 歡迎進入資金管理系統 %5s"%("*","*"))
print(" %s%30s"%("*","*"))
print(' *'*15)
try:
action = input("請選擇操作:1.存款 2.取款 3.轉賬 4.修改密碼 5.退出:\n")
action = int(action)
except Exception as e:
print("warn:請輸入正確的操作指令!")
return -1
if action not in action_dict:
print("warn:請執行正確的操作!")
return -1
return action
測試welcome方法:
action = welcome()
action
輸出結果:
圖3-3系統歡迎界面
步驟 7、定義系統啟動函數
設置啟動函數:
def run():
action = welcome()
user_account.implement(action)
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = """
update user set balance=%f,start_time='%s',end_time='%s' where username='%s'
"""%(user_account.money, user_account.start_time,end_time,user_account.username)
con_mysql(sql)
user_account.voucher(end_time, action)
步驟8、使用裝飾器為系統添加計時功能
#定義裝飾器:
def consume_time(func, *args, **kwargs):
def inner(*args, **kwargs):
start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("本次登錄時間%s" % (start_time))
func()
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("登出時間%s" % (end_time))
return (start_time, end_time)
return inner
#給系統啟動函數添加功能:
@consume_time
def run():
action = welcome()
user_account.implement(action)
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = """
update user set balance=%f,start_time='%s',end_time='%s' where username='%s'
""" % (user_account.money, user_account.start_time, end_time, user_account.username)
con_mysql(sql)
user_account.voucher(end_time, action)
步驟 9、啟動系統
if __name__ == "__main__":
while True:
if isinstance(user_account, Account):
break
while True:
run()
輸出結果:
上一篇: 大數據培訓_Hive 常用函數
下一篇: 9月底,華為將發布這個認證!