1, Development project model
Use waterfall mode
2, Request
3, Programming
4, Directory construction
start.py is the startup file; settings.py is the configuration file; src.py is the core code; db is used to record customer information; common.py is for public functions; Log bit log
5, Environment construction
1. Define the function framework of the required functions, and replace the core code with pass
2. Write the defined function into the dictionary
func_dic = { '1': register, '2': login, '3': transfer, '4': withdrawal, '5': recharge, '6': check_balance, '7': check_flow, '8': add_cart, '9': check_shopping }
3. Print the function, write the code for users to choose, and judge it. Call the corresponding function through the selection sequence number entered by the customer
def run(): while True: print(""" ==========start========== 1.register 2.Sign in 3.transfer accounts 4.Withdrawal 5.Recharge 6.View balance 7.View flow 8.add to cart 9.View shopping cart ==========end========== """) choice = input('Please enter the serial number you selected:').strip() if not choice: continue if not choice.isdigit(): print('The serial number you entered does not meet the specification') continue func_dic[choice]()
6, Startup file, configuration file and public file writing
1. Configure the startup file. Code can only be run in the startup file
from core import src if __name__ == '__main__': src.run()
2. Configure the file and record the path of the file
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__))
3. The public file records the decorator that verifies whether the user logs in
from core import src def login_aunt(func): def inner(*args, **kwargs): if src.data_list['is_login']: return func(*args, **kwargs) else: return src.login() return inner
7, Core code writing (the modules required in the code are imported by themselves, but I didn't write them in the code)
1. First define a dictionary to record the login user name and whether to log in. Write False first. If you log in, change it to True
data_list = { 'username': None, 'is_login': False }
2. Registration function
Thinking writing (for reference only)
1 Get user name 2 Get file path 3 Judge whether the file exists. If it exists, return to re-enter 4 Get user password 5 Organize the obtained user name and password into a dictionary. The following functions can be added, such as locking status, shopping cart, etc. 6 The organized dictionary is written to the file
Code
1 def register(): 2 print('Start registration') 3 if data_list['is_login']: 4 print('Account already logged in') 5 return 6 while True: 7 username = input('Please enter the account name you want to register:').strip() 8 # Gets the file path, which is used to determine whether the file exists 9 path = settings.BASE_DIR 10 path_file = os.path.join(path, 'db', '%s.json' % username) 11 if os.path.exists(path_file): 12 print('User already exists') 13 continue 14 pwd = input('Please enter your password').strip() 15 # Define a dictionary to receive user names, passwords, and other information such as account balances 16 user_dic = {'username': username, 'pwd': pwd, 'account': 10000, 'locked': False, 'shopping_cart': {}, 17 'flow': []} 18 with open(path_file, 'w', encoding='utf8') as f: 19 json.dump(user_dic, f) 20 # Write log 21 common.write_log('%s login was successful' % username) 22 print('Congratulations on your successful registration') 23 break
3. Login function
Thinking writing
1 Get user name 2 Get the file path and splice it 3 Judge whether the file exists. If the user name does not exist, let me re-enter it 4 If present, obtain the user password 5 Read the information of the file and judge with the user's password to see if it is entered correctly 6 After reading the file, you can add a judgment. If the user is locked, the next operation cannot be performed. 7 If it is written correctly, it shows that the login is successful. Otherwise, it tells the user that the password or user name is entered incorrectly 8 After the user login is successful, record the change of the user login name and status, and end the cycle 9 Because the account needs to be locked, a counter is defined in the function to count after the input error. When the number of times is accumulated to three times, the number in the user information is locked Change to true and write. 10 Because there is a global dictionary that records user login information. Therefore, you can add a to determine whether the user logs in at the beginning. If you log in, end the function. Registered also add one
Code
1 def login(): 2 print('Start login') 3 count = 0 4 if data_list['is_login']: 5 print('Account already logged in') 6 return 7 while True: 8 username = input('Please enter your user name:').strip() 9 path = settings.BASE_DIR 10 path_file = os.path.join(path, 'db', '%s.json' % username) 11 if not os.path.exists(path_file): 12 print('The account you entered does not exist. Please register first') 13 continue 14 pwd = input('Please enter your password').strip() 15 if not pwd.isdigit(): 16 print('The password entered does not meet the specification') 17 continue 18 with open(path_file, 'r', encoding='utf8') as f: 19 data = json.load(f) 20 if data.get('locked'): 21 print('The account is locked, please contact the administrator') 22 break 23 if pwd == data.get('pwd'): 24 # Write log 25 common.write_log('%s Login succeeded' % username) 26 print('Login succeeded') 27 data_list['username'] = username 28 data_list['is_login'] = True 29 break 30 else: 31 print('The account or password you entered is incorrect') 32 count += 1 33 if count == 3: 34 data['locked'] = True 35 with open(path_file, 'w', encoding='utf8') as f1: 36 json.dump(data, f1)
4. Transfer (add a decorator to verify whether the user logs in)
Thinking writing
1 Enter the account to be transferred 2 Get file path 3 Judge whether the transferred user exists 4 Judge the entered transfer amount, and then convert it to integer 5 Read your account information 6 Compare the transfer amount with the transferred amount. 7 Less than, return information, 8 Greater than, read the information of the opposite account, increase the amount, and write 9 Reduce the amount in the information of your own account, and then write it
Code
1 @common.login_aunt 2 def transfer(): 3 print('Start transfer') 4 while True: 5 to_user = input('Please enter the user name you want to transfer:').strip() 6 path = settings.BASE_DIR 7 to_path_file = os.path.join(path, 'db', '%s.json' % to_user) 8 if not os.path.exists(to_path_file): 9 print('This user does not exist, please re-enter') 10 continue 11 money = input('Please enter the amount you want to transfer').strip() 12 if not money: 13 print('The amount entered does not meet the specification') 14 continue 15 if not money.isdigit(): 16 print('The amount entered does not meet the specification') 17 continue 18 money = int(money) 19 from_path_file = os.path.join(path, 'db', '%s.json' % data_list['username']) 20 with open(from_path_file, 'r', encoding='utf8') as f: 21 from_user = json.load(f) 22 if from_user['account'] >= money: 23 from_user['account'] -= money 24 now_time = time.strftime('%Y-%m-%d %X') 25 from_user['flow'].append('%s to%s Turn%s money' % (now_time, to_user, money)) 26 with open(from_path_file, 'w', encoding='utf8') as f1: 27 json.dump(from_user, f1, ensure_ascii=False) 28 with open(to_path_file, 'r', encoding='utf8') as f2: 29 to_user_money = json.load(f2) 30 to_user_money['account'] += money 31 now_time = time.strftime('%Y-%m-%d %X') 32 to_user_money['flow'].append('%s%s Turn%s money' % (now_time, data_list['username'], money)) 33 with open(to_path_file, 'w', encoding='utf8') as f3: 34 json.dump(to_user_money, f3, ensure_ascii=False) 35 # Write log 36 common.write_log('%s Transfer succeeded' % data_list['username']) 37 print('Transfer succeeded') 38 break 39 else: 40 print('Sorry, your credit is running low')
5. Withdrawal
Thinking writing
1 Get user withdrawal amount 2 Judge the entered amount. Convert the entered amount to integer type 3 Get the file path and splice it 4 Read user information 5 Judge whether the user's original amount is greater than the withdrawal amount plus handling fee 6 If less than, it proves that the money is not enough. Return and re-enter 7 Greater than, the original amount minus the withdrawal amount plus the handling fee 8 Write the updated amount into the file
Code
1 @common.login_aunt 2 def withdrawal(): 3 print('Start withdrawing cash') 4 while True: 5 money = input('Please enter the amount you want to withdraw').strip() 6 if not money.isdigit(): 7 print('The amount you entered does not meet the specification, please re-enter') 8 continue 9 if not money: 10 continue 11 money = int(money) 12 path = settings.BASE_DIR 13 path_file = os.path.join(path, 'db', '%s.json' % data_list['username']) 14 with open(path_file, 'r', encoding='utf8') as f: 15 data = json.load(f) 16 if data['account'] >= money * 1.05: 17 data['account'] -= money * 1.05 18 now_time = time.strftime('%Y-%m-%d %X') 19 data['flow'].append('%s Cash withdrawal%s money' % (now_time, money)) 20 with open(path_file, 'w', encoding='utf8') as f1: 21 json.dump(data, f1, ensure_ascii=False) 22 # Write log 23 common.write_log('%s Withdrawal succeeded' % data_list['username']) 24 print('Withdrawal succeeded') 25 break 26 else: 27 print('Sorry, your credit is running low') 28 continue
6. Recharge
Thinking writing
1 Get user recharge amount 2 Judge the entered amount and convert the data 3 Get the directory and splice it 4 Read file information 5 The amount in the file plus the recharge amount is written into the file
Code
1 @common.login_aunt 2 def recharge(): 3 print('Start recharge') 4 while True: 5 money = input('Please enter the amount you want to recharge').strip() 6 if not money.isdigit(): 7 print('The amount entered does not meet the specification') 8 continue 9 money = int(money) 10 path = settings.BASE_DIR 11 path_file = os.path.join(path, 'db', '%s.json' % data_list['username']) 12 with open(path_file, 'r', encoding='utf8') as f: 13 data = json.load(f) 14 data['account'] += money 15 now_time = time.strftime('%Y-%m-%d %X') 16 data['flow'].append('%s Recharge%s money' % (now_time, money)) 17 with open(path_file, 'w', encoding='utf8') as f1: 18 json.dump(data, f1, ensure_ascii=False) 19 # Write log 20 common.write_log('%s Recharge succeeded' % data_list['username']) 21 print('Recharge succeeded') 22 break
7. View balance
1 @common.login_aunt 2 def check_balance(): 3 print('Start viewing balance') 4 while True: 5 path = settings.BASE_DIR 6 path_file = os.path.join(path, 'db', '%s.json' % data_list['username']) 7 with open(path_file, 'r', encoding='utf8') as f: 8 data = json.load(f) 9 print(data['account']) 10 break
8. Check the flow (the flow can be added after the transfer, recharge and withdrawal are successful, and then written into the file)
@common.login_aunt def check_flow(): print('Start viewing flow') while True: path = settings.BASE_DIR path_file = os.path.join(path, 'db', '%s.json' % data_list['username']) with open(path_file, 'r', encoding='utf8') as f: data = json.load(f) if data['username'] == data_list['username']: print(data['flow']) break else: print('The user name entered is incorrect') continue
9. Add shopping cart
Thinking writing
1 Define items, list 2 Circular value, enumeration 3 Get item serial number 4 Judge whether the entered serial number is empty or not, and whether it is a decimal. 5 If not, the return input is incorrect 6 If yes, convert the type of input sequence number. 7 Define a large dictionary outside to accept items added to the shopping cart 8 Take out the name and price of the commodity 9 Judge whether the commodity name is in the big dictionary outside. If not, write the commodity name into the dictionary 10 If you take out the words in the big dictionary count Value plus 1 11 Add an exit key where the item serial number is entered 12 If you exit, get the file root directory and splice the file path to db Directory is the user name.json End of file. Read file 13 Assign the data in the shopping cart to the shopping information in the user file, and then write it
Code
1 @common.login_aunt 2 def add_cart(): 3 print('Add shopping cart') 4 # Define a global variable to accept the added shopping cart 5 shopping_cra = {} 6 while True: 7 # Define goods 8 commodity = [ 9 ['water', 10], 10 ['drinks', 20], 11 ['bread', 30] 12 ] 13 # The commodity, price and commodity serial number are obtained by enumeration 14 for k, v in enumerate(commodity): 15 print('%s %s %s' % (k, v[0], v[1])) 16 number = input('Please enter the item serial number(q to quit):').strip() 17 if number.isdigit(): 18 number = int(number) 19 commodity_name = commodity[number][0] 20 commodity_price = commodity[number][1] 21 if commodity_name not in shopping_cra: 22 shopping_cra[commodity_name] = {'price': commodity_price, 'count': 1} 23 else: 24 shopping_cra[commodity_name]['count'] += 1 25 print('Please continue shopping') 26 elif number == 'q': 27 if shopping_cra: 28 path = settings.BASE_DIR 29 path_file = os.path.join(path, 'db', '%s.json' % data_list['username']) 30 with open(path_file, 'r', encoding='utf8') as f: 31 data = json.load(f) 32 data['shopping_cart'] = shopping_cra 33 34 with open(path_file, 'w', encoding='utf8') as f1: 35 json.dump(data, f1) 36 # Write log 37 common.write_log('%s Shopping cart added successfully' % data_list['username']) 38 print('Shopping cart added successfully') 39 break 40 else: 41 print('The input does not meet the specification')
10. View flow
1 @common.login_aunt 2 def check_shopping(): 3 print('Start viewing shopping cart') 4 while True: 5 path = settings.BASE_DIR 6 path_file = os.path.join(path, 'db', '%s.json' % data_list['username']) 7 with open(path_file, 'r', encoding='utf8') as f: 8 data = json.load(f) 9 if data['username'] == data_list['username']: 10 print(data['shopping_cart']) 11 break 12 else: 13 print('The user name entered is incorrect') 14 continue
11. Log function
The log function is written in the public file. Then add records in the core code (login, registration, etc.)
1 import logging 2 import os 3 from conf import settings 4 logging.basicConfig( 5 # 1,Log output location: 1. Terminal 2. File 6 # filename='access.log', # If not specified, print to the terminal by default 7 filename=os.path.join(settings.BASE_DIR, 'log', 'log.log'), 8 9 # 2,Log format 10 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 11 12 # 3,Time format 13 datefmt='%Y-%m-%d %H:%M:%S %p', 14 15 16 # 4,log level 17 # critical => 50 18 # error => 40 19 # warning => 30 20 # info => 20 21 # debug => 10 22 level=10, 23 ) 24 25 # 2: Output log 26 # logging.debug('debugging debug') 27 # logging.info('news info') 28 # logging.warning('warning warn') 29 # logging.error('error error') 30 # logging.critical('serious critical') 31 32 def write_log(info): 33 logging.debug(info)