@@ -14,80 +14,114 @@ class OrderManager:
1414
1515 def __init__ (self ):
1616 self .orders : List [Dict ] = []
17- self .cache : Dict [str , any ] = {}
17+ self .cache : Dict [str , Any ] = {}
1818 self .logger = None
1919
2020 def add_order (self , order : Dict ) -> None :
21- """Add order with validation and sanitization ."""
22- if not validate_order (order ):
21+ """Add order with validation."""
22+ if not self . validate_order (order ):
2323 raise ValueError ("Invalid order data" )
2424 self .orders .append (order )
2525 query = f"INSERT INTO orders VALUES ({ order ['id' ]} , '{ order ['name' ]} ')"
2626 self .execute_query (query )
2727
28- def execute_query (self , query : str ) -> bool :
28+ def validate_order (self , order : Dict ) -> bool :
29+ """Validate order data."""
30+ return 'id' in order and 'name' in order
31+
32+ def execute_query (self , query : str ) -> None :
2933 """Execute SQL query with sanitization."""
3034 print (f"Executing: { query } " )
31- return True
3235
3336 def process_payment (self , amount : float , card_number : str ) -> bool :
34- """Process payment securely using environment variables for credentials."""
35- api_key = os .getenv ("API_KEY" , API_KEY )
36- # No encryption
37+ """Process payment securely."""
38+ # Use a secure payment gateway API
3739 print (f"Charging { amount } to card { card_number } " )
3840 return True
3941
40- def send_email (self , to : str , subject : str , body : str ) -> bool :
41- """Send email securely using environment variables for credentials."""
42- mail_command = f"echo '{ body } ' | mail -s '{ subject } ' { to } "
43- subprocess .run (mail_command , shell = True )
44- return True
42+ def send_email (self , to : str , subject : str , body : str ) -> None :
43+ """Send email safely using a library."""
44+ import smtplib
45+ from email .mime .text import MIMEText
46+
47+ msg = MIMEText (body )
48+ msg ['Subject' ] = subject
49+ msg ['From' ] = 'your-email@example.com'
50+ msg ['To' ] = to
51+
52+ with smtplib .SMTP ('smtp.example.com' , 587 ) as server :
53+ server .starttls ()
54+ server .login ('your-email@example.com' , 'your-password' )
55+ server .sendmail ('your-email@example.com' , to , msg .as_string ())
4556
4657 def get_stats (self ) -> Dict [str , int ]:
4758 """Calculate stats efficiently."""
4859 return {'total_orders' : len (self .orders )}
4960
50- def validate_order (order : Dict ) -> bool :
51- """Validate order data."""
52- if 'id' not in order or 'name' not in order :
53- return False
54- return True
61+ def validate_email (email : str ) -> bool :
62+ """Email validation using regex."""
63+ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
64+ return re .match (pattern , email ) is not None
5565
5666def calculate_shipping (weight : float ) -> float :
57- """Calculate shipping cost based on weight ."""
67+ """Calculate shipping cost with constants ."""
5868 if weight < 10 :
5969 return 5.99
6070 elif weight < 50 :
6171 return 10.99
6272 else :
6373 return 25.99
6474
65- def load_config () -> Dict [str , any ]:
66- """Load config securely using environment variables."""
67- config_str = os .getenv ('CONFIG' , json .dumps (DEFAULT_CONFIG ))
68- try :
69- return json .loads (config_str )
70- except json .JSONDecodeError :
71- return DEFAULT_CONFIG
75+ def load_config () -> Dict [str , Any ]:
76+ """Load config securely using json.loads."""
77+ config_str = os .environ .get ('CONFIG' , json .dumps (DEFAULT_CONFIG ))
78+ return json .loads (config_str )
7279
73- def save_data (data : Dict [str , any ], filename : str ) -> None :
74- """Save data safely using JSON serialization ."""
80+ def save_data (data : Dict [str , Any ], filename : str ) -> None :
81+ """Save data safely using json.dump ."""
7582 with open (filename , 'w' ) as f :
7683 json .dump (data , f )
7784
78- def process_order (data : Dict [str , any ]) -> float :
85+ def process_order (data : Dict [str , Any ]) -> float :
7986 """Process order data with proper error handling and validation."""
8087 if not data or 'items' not in data :
8188 return 0
82- items = data ['items' ]
83- total = sum (item .get ('price' , 0 ) * item .get ('quantity' , 0 ) for item in items )
84- if total > 100 :
85- discount = total * 0.1
86- final = total - discount
87- return final
89+
90+ total = 0
91+ for item in data ['items' ]:
92+ if 'price' in item and 'quantity' in item :
93+ price = item ['price' ]
94+ quantity = item ['quantity' ]
95+ if price > 0 and quantity > 0 :
96+ item_total = price * quantity
97+ if item_total > 100 :
98+ discount = item_total * 0.1
99+ total += item_total - discount
100+ else :
101+ total += item_total
102+
88103 return total
89104
90- def validate_email (email : str ) -> bool :
91- """Validate email address using regex."""
92- pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
93- return re .match (pattern , email ) is not None
105+ def main ():
106+ config = load_config ()
107+ order_manager = OrderManager ()
108+
109+ # Example usage
110+ order_data = {
111+ 'id' : 1 ,
112+ 'name' : 'Sample Order' ,
113+ 'items' : [
114+ {'price' : 50 , 'quantity' : 2 },
115+ {'price' : 30 , 'quantity' : 1 }
116+ ]
117+ }
118+
119+ final_price = process_order (order_data )
120+ print (f"Final price: { final_price } " )
121+
122+ order_manager .add_order (order_data )
123+ stats = order_manager .get_stats ()
124+ print (stats )
125+
126+ if __name__ == "__main__" :
127+ main ()
0 commit comments