· 5 years ago · Nov 03, 2020, 03:06 AM
1"""Welcome. This is a basic Air Ticket Reservation system implemented
2using python and MySQL using the third party library mysql-connector:
3https://dev.mysql.com/doc/connector-python/en/ . This program is
4compatible with all versions of python above python 3.6"""
5
6# This program can manipulate up to 2147473647 tickets in it
7import sys
8import time
9import datetime
10import sqlite3 as msc
11
12request_queue = [] # list containing deletion requests that have been made by the user
13
14
15# function declarations
16# the functions that have been declared below are:
17# add_flights(cur, database)
18# admin_menu()
19# administrator_mode(cur, con)
20# confirm_create_tables(cur)
21# connect_to_mysql()
22# consumer_menu()
23# consumer_mode(cur, con)
24# create_airline_tickets(cur)
25# create_flight_details(cur)
26# create_login_table(cur, database)
27# display_flight(cur)
28# display_ticket(cur)
29# flight_deletion(cur, database)
30# flight_modification(cur, database)
31# get_request()
32# login(cur)
33# make_request()
34# reserve_ticket(cur, database)
35# see_flights(cur)
36# sign_in_and_up
37# ticket_deletion(cur, database)
38# ticket_modification(cur, database)
39# validity_checker(cur, flight_no, start, stop, date
40
41
42def sign_in_and_up(cur, con):
43 """
44 Function for Sign In and Sign Up by Julien Jessmon
45 """
46
47 while True:
48 cur.execute('SELECT Username, Password FROM Login WHERE Mode="Consumer"')
49 user_and_pass = cur.fetchall()
50 user_ = []
51 for u, p in user_and_pass:
52 user_.append(u)
53
54 print(' Login Details')
55 print('---------------\n')
56 print('1. Sign In\n')
57 print('2. Sign Up\n')
58 print('3. Back\n')
59
60 try:
61 opt1 = int(input('Select an option: '))
62 except ValueError:
63 print('Invalid Option')
64 continue
65
66 if opt1 == 1:
67
68 user = input('Enter User ID: ')
69 password = input("Enter Password: ")
70 acc = (user, password)
71
72 if acc in user_and_pass:
73 print('Username and Password accepted')
74 print('Welcome', user, '!\n')
75 time.sleep(2)
76 return True
77
78 else:
79 print('Invalid Username or Password. Try Again')
80 time.sleep(2)
81 return False
82
83 elif opt1 == 2:
84 user = input('Enter User ID: ')
85
86 if user not in user_:
87 print('User ID accepted')
88
89 elif user in user_:
90 print('Used ID is already in use')
91 time.sleep(2)
92 return False
93
94 password = input('Enter Your Password (>6 chrs): ')
95
96 if len(password) > 6:
97 print('Password Accepted')
98 time.sleep(2)
99 cur.execute(f'INSERT INTO Login VALUES("{user}", "{password}", "Consumer")')
100 con.commit()
101
102 user_and_pass.append((user, password))
103 user_.append(user)
104
105 else:
106 print('Password less than 7 Characters are invalid, type again.')
107 time.sleep(2)
108 return False
109
110 elif opt1 == 3:
111 return False
112
113 else:
114 print('Please choose from the options given.')
115 time.sleep(2)
116 continue
117
118 print('''\n\nDo you want to continue to go to sign in menu or go back?
119 1. Sign In Menu
120 2. Back''')
121 try:
122 cont = int(input("Type Option 1 or 2: "))
123 except ValueError:
124 print('Invalid Option, try again')
125 continue
126
127 if cont == 1:
128 print()
129
130 elif cont == 2:
131 return False
132
133
134def create_login_table(cur, database):
135 """
136 Function for creating a Login Table and setting the admins,
137 if it does not exist.
138 """
139 cur.execute(
140 'CREATE TABLE Login ('
141 'Username VARCHAR(30) NOT NULL UNIQUE, '
142 'Password VARCHAR(30), '
143 'Mode Varchar(15) '
144 ')'
145 ) # creating the table
146
147 cur.execute('INSERT INTO Login VALUES("Admin", "123", "Administrator")') # setting the admin
148
149 database.commit()
150
151
152def create_flight_details(cur):
153 """
154 Function for creating Flight_Details Table, if it does not exist.
155 """
156
157 cur.execute(
158 'CREATE TABLE Flight_Details ('
159 'Flight_Name VARCHAR(30),'
160 'Flight_Number VARCHAR(7),'
161 'Number_Of_Seats SMALLINT,'
162 'Date DATE,'
163 'Start VARCHAR(20),'
164 'Boarding_Time TIME, '
165 'Route VARCHAR(100) DEFAULT "",'
166 'Destination VARCHAR(20)'
167 ')') # creating the table
168
169
170def create_airline_tickets(cur):
171 """
172 Function to create a table with the valid columns for the program.
173 Made by Adarsh Dileep
174 """
175 cur.execute(
176 'CREATE TABLE Airline_Tickets (' +
177 'Ticket_No INT PRIMARY KEY NOT NULL,' +
178 'Name VARCHAR(20),' +
179 'Departure_Date DATE,' +
180 'Start VARCHAR(20),' +
181 'Destination VARCHAR(20),' +
182 'Flight_Number VARCHAR(10),' +
183 'Flight_Class VARCHAR(15)' +
184 ')') # creates the table airline_tickets with the given columns
185
186
187def confirm_create_tables(cur):
188 """
189 Function for Confirming Permission for creating invalid tables,
190 if they do not exist in the given database
191 """
192
193 # cur.execute('SHOW TABLES')
194 cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
195 yes_list = ['Yes', 'YES', 'yes', 'Y', 'y']
196 no_list = ['No', 'NO', 'no', 'n', 'N']
197 table_list = cur.fetchall() # to see if the table exists
198
199 while ('Flight_Details',) not in table_list or ('Airline_Tickets',) not in table_list or \
200 ('Login',) not in table_list:
201 create = input('''It is detected that there are no valid Table(s) in your database for running this program.
202
203 Enter "yes" to allow the program to create a valid empty table
204 Enter "no" to Exit the program\n(yes/no) ''') # for confirming if the code has permission to create a table
205
206 if create in yes_list:
207
208 if ('Airline_Tickets',) not in table_list: # creating table: Airline_Tickets
209 create_airline_tickets(cur)
210
211 if ('Flight_Details',) not in table_list: # creating table: Flight_Details
212 create_flight_details(cur)
213
214 if ('Login',) not in table_list: # creating table: Login
215 create_login_table(cur, connection)
216
217 print('Table(s) have been created successfully!')
218 break
219
220 elif create in no_list:
221 print('Thank you for using this program!') # creating table
222 sys.exit()
223
224 else:
225 print('Please choose from the options given. \n')
226
227
228def reserve_ticket(cur, database):
229 """
230 Function to add the data of a new ticket into the table.
231 Made by Julien Jessmon
232 """
233
234 b = input("Enter Departure Date (in yyyy-mm-dd format): ") # b=departure date
235 print('The Flight(s) Available on this day are: ')
236 time.sleep(1)
237 check_if_flight_available = see_flights(cur, b) # to see if True or False, ie there is no flight available on Date
238
239 if not check_if_flight_available:
240 return
241
242 time.sleep(3)
243 a = input("Enter Name of the Passenger: ") # a=name
244 c = input("From Where: ") # c=starting point
245 d = input("To Where: ") # d=destination
246 e = input("Enter Flight Number: ") # e=flight number
247 f = input("Enter Travel Class: ") # f=class
248
249 cur.execute('SELECT MAX(Ticket_No) FROM airline_tickets') # for generating ticket numbers in an ordered manner
250 h = cur.fetchone()
251
252 if h[0]: # if there are 1 or more rows
253 h = h[0] + 1 # since h[0] would be the max ticket number, h+1 would be the new ticket number
254
255 else: # if there are no rows
256 h = 10000
257
258 if validity_checker(cur, e, c, d):
259 cur.execute(
260 "INSERT INTO airline_tickets VALUES("
261 f"{h}," +
262 f"'{a}' ," + # Name
263 f"'{b}' ," + # Departure Date
264 f"'{c}' ," + # Starting Point
265 f"'{d}' ," + # Destination
266 f"'{e}' ," + # Flight Number
267 f"'{f}' " + # Travel Class
268 ")")
269 print(f'\nticket with ticket number {h} has been reserved')
270
271 database.commit()
272
273
274def payment():
275 print('Choose the form of payment:')
276 print('1. Credit/Debit Card')
277 print('2. Cash')
278
279 # fixme: this.
280
281
282def add_flights(cur, database):
283 """
284 Function to Add Flights
285 """
286 flight_name = input("Enter Name of the Flight: ") # flight name
287 flight_number = input("Enter Flight Number: ") # flight number
288 seats = int(input('Enter total number of seats: ')) # number of empty seats in the flight
289 date = input("Enter Departure Date (in yyyy-mm-dd format): ") # date of the flight
290 start = input("From Where: ") # Start
291 boarding_time = input('Enter Boarding Time(hh:mm:ss): ') # boarding time
292 route_number = int(input('Enter number of intermediate stops: ')) # number of stops btw the first and final stop
293 route = ''
294 for _ in range(route_number):
295 route += input('Enter name of intermediate airport: ') + ',' # name of all intermediate stops
296 destination = input("To Where: ") # destination
297
298 datetime.datetime.strptime(date, "%Y-%m-%d") # this would raise a ValueError if the entered date is invalid
299
300 query = "INSERT INTO flight_details VALUES(" \
301 f'"{flight_name}", ' \
302 f'"{flight_number}", ' \
303 f'"{seats}", ' \
304 f'"{date}", ' \
305 f'"{start}", ' \
306 f'"{boarding_time}", ' \
307 f'"{route}", ' \
308 f'"{destination}")' # query to insert the values to the table
309
310 cur.execute(query)
311
312 database.commit()
313
314
315def ticket_modification(cur, database):
316 """
317 Function to update Ticket Information.
318 Made by Libin Louis
319 """
320
321 n = input("Enter Departure Date (in yyyy-mm-dd format): ") # n=departure date
322 print('The Flight(s) Available on this day are: ')
323 time.sleep(1)
324 check_if_flight_available = see_flights(cur, n) # to see if True or False, ie there is no flight available on Date
325
326 if not check_if_flight_available:
327 return
328
329 time.sleep(3)
330 k = int(input('Enter ticket number of ticket to be changed: ')) # ticket number
331
332 r = input("Enter New Name of the Passenger: ") # r=name
333 f = input("From Where: ") # f=starting point
334 g = input("To Where: ") # g=destination
335 d = input("Enter Flight Number: ") # d=flight number
336 x = input("Enter Travel Class: ") # x=class
337
338 val = r, n, f, g, d, x, k # tuple of values to be formatted into the query
339
340 qry = '''update airline_tickets set
341 Name = "%s",
342 Departure_Date = "%s",
343 Start = "%s",
344 Destination = "%s",
345 Flight_Number = "%s",
346 Flight_Class = "%s"
347 Where Ticket_No = %s''' # MySQL query for UPDATE command
348
349 if validity_checker(cur, d, f, g, cre_or_mod=0):
350 cur.execute(qry % val)
351 database.commit()
352 print('Ticket Successfully updated.')
353
354
355def flight_modification(cur, database):
356 """
357 Function to Modify Flights
358 """
359
360 flight_number = input("Enter Flight Number of the flight to be modified: ") # flight number
361
362 flight_name = input("Enter New Name of the Flight: ") # flight name
363 seats = int(input('Enter New total number of seats: ')) # number of empty seats in the flight
364 date = input("Enter New Departure Date (in yyyy-mm-dd format): ") # date of the flight
365 start = input("From Where: ") # starting airport
366 boarding_time = input('Enter Boarding Time(hh:mm:ss): ') # boarding time
367 route_number = int(input('Enter number of intermediate stops: ')) # number of stops btw the first and final stop
368 route = ''
369 for _ in range(route_number):
370 route += input('Enter name of intermediate airport: ') + ',' # name of stops btw the first and final stop
371 destination = input("To Where: ") # destination
372
373 cur.execute(
374 "UPDATE flight_details SET "
375 f'Flight_Name = "{flight_name}", '
376 f'Number_Of_Seats = {seats}, '
377 f'Date = "{date}",'
378 f'Start = "{start}", '
379 f'Boarding_Time = "{boarding_time}", '
380 f'Route = "{route}", '
381 f'Destination = "{destination}" '
382 f'WHERE Flight_Number = "{flight_number}"'
383 ) # Updating the table
384
385 print('Flight Has Been Updated')
386 database.commit()
387
388
389def display_ticket(cur):
390 """
391 Function to display information about tickets
392 """
393 ticket_no = int(input('Enter Ticket number: '))
394
395 cur.execute(f'SELECT * FROM airline_tickets Where Ticket_No = {ticket_no}')
396
397 details = cur.fetchone()
398 if details is not None:
399 print(*details, sep=' ') # displays all the values in the row
400 else:
401 print('The Data You Have Entered is Wrong. Try Again.')
402
403
404def display_flight(cur):
405 """
406 Function to display information about Flights
407 """
408 flight_no = input('Enter Flight number: ')
409
410 cur.execute(f'SELECT * FROM Flight_Details WHERE Flight_Number = "{flight_no}"')
411
412 details = cur.fetchone()
413 if details is not None:
414 print(*details, sep=' ') # displays all the values in the row
415 else:
416 print('The data you eave entered is incorrect. Verify and try again.')
417
418
419def ticket_deletion(cur, database):
420 """
421 function to delete tickets from the database
422 """
423
424 sure = input('''Are you sure you want to delete the details of this ticket?'
425 A ticket, once deleted, cannot be restored easily.
426 Enter "yes" to confirm your choice
427 Enter "no" to cancel \n''') # for confirming if the user wishes to delete a ticket
428
429 if sure in ('yes', 'YES', 'Yes', 'Y', 'y'):
430 ticket_no = input('Enter ticket number of the ticket to be deleted: ')
431
432 cur.execute(f'SELECT Flight_Number FROM Airline_Tickets WHERE Ticket_No={ticket_no}')
433 flight_no = cur.fetchone()[0]
434
435 cur.execute(f'DELETE FROM airline_tickets where Ticket_no = {ticket_no}') # deleting tickets
436 cur.execute('UPDATE Flight_Details SET Number_Of_Seats=Number_Of_Seats+1 '
437 f'WHERE Flight_Number = "{flight_no}"')
438 database.commit()
439
440 print('Ticket Deleted Succesfully.')
441
442 elif sure not in ('No', 'NO', 'no', 'n', 'N'):
443 print('Invalid option, please enter a valid option \n')
444
445
446def flight_deletion(cur, database):
447 """
448 function to delete flights from the table
449 """
450
451 sure = input('''Are you sure you want to delete the details of this Flight?'
452 Once deleted, This data cannot be restored easily.
453 Enter "yes" to confirm your choice
454 Enter "no" to cancel \n''') # for confirming if the user wishes to delete a ticket
455
456 if sure in ('yes', 'YES', 'Yes', 'Y', 'y'):
457 flight_no = input('Enter flight number of the flight to be deleted: ')
458
459 cur.execute(f'DELETE FROM flight_details where Flight_Number = "{flight_no}"') # deleting tickets
460 database.commit()
461
462 print('Flight Details Deleted Succesfully.')
463
464 elif sure not in ('No', 'NO', 'no', 'n', 'N'):
465 print('Invalid option, please enter a valid option \n')
466
467
468def make_request():
469 """
470 Function that stored all requests for ticket deletion in request_queue
471 """
472
473 global request_queue
474
475 print('\nAre You Sure You Wish To Send A Request To The Admin '
476 'Requesting the Cancellation of Your Ticket?')
477 choice = input('\nEnter Yes to confirm and proceed\n'
478 'Enter no to cancel\n') # confirming request
479
480 if choice in ('yes', 'YES', 'Yes', 'y', 'Y'):
481 name = input('Enter your name: ')
482 tckt_no = input('Enter ticket number: ')
483 request_queue.append(f'{time.asctime()}: the user "{name}" has requested the deletion of the ticket '
484 f'with ticket number="{tckt_no}"')
485 print('The request has been sent. It shall be processed at the earliest')
486
487 elif choice in ('No', 'NO', 'no', 'n', 'N'):
488 ...
489 else:
490 print('invalid choice, please try again')
491
492
493def get_request():
494 """
495 Function to get all pending requests
496 """
497 global request_queue
498 request_queue = request_queue[::-1] # reversing queue so that the requests are sent in order of its creation
499
500 with open('request queue.txt', 'r+') as req:
501
502 content = req.readlines() + request_queue
503 req.truncate(0)
504 req.flush()
505 req.seek(0)
506
507 request_queue = [] # clearing the queue and file
508 content = content[::-1] # reversing content for correct order
509
510 print()
511 if not content:
512 print('Queue Empty!')
513 while content:
514 print(content.pop())
515 print()
516
517
518def login(cur):
519 """
520 function to log in for using the admin mode
521 """
522
523 usr_name = input('Enter Administrator Username: ')
524 passwrd = input('Enter Password: ')
525
526 cur.execute(f'SELECT * FROM login WHERE USERNAME = "{usr_name}"')
527 result = cur.fetchone()
528
529 if result and passwrd == result[1]:
530 return True
531 else:
532 return False
533
534
535def admin_menu():
536 """
537 function for admin menu
538 """
539 print(' MENU')
540 print(' ------ \n')
541 print('1: See All Flights\n')
542 print('2: Reserve a Ticket\n')
543 print('3: Change the Ticket Details\n')
544 print('4: Display Ticket Information Information\n')
545 print('5: Delete Ticket\n')
546 print('6: View Pending Requests\n')
547 print('7: Add a New Flight\n')
548 print('8: Change Flight Details\n')
549 print('9: Display Details of One Flight\n')
550 print('10: Delete Flight\n')
551 print('11: Display Help\n')
552 print('12: Move To User List\n')
553 print('-' * 50)
554
555
556def administrator_mode(cur, con):
557 """
558 admin mode
559 """
560 running = True
561 while running:
562
563 admin_menu()
564 print()
565
566 try:
567 option = int(input('Choose an option: '))
568 except ValueError:
569 print('Invalid Type of Option. Please Enter a Valid Option (integers between 1 & 12)\n')
570 time.sleep(3)
571 continue
572
573 if option == 1:
574 see_flights(cur)
575 time.sleep(5)
576
577 elif option == 2: # for creating a ticket
578 try:
579 reserve_ticket(cur, con)
580 except (msc.DataError, ValueError):
581 print('The data you have entered is invalid. Try again or type 11 for help\n')
582 time.sleep(5)
583
584 elif option == 3: # for modifying ticket information
585 try:
586 ticket_modification(cur, con)
587 except (msc.DataError, ValueError):
588 print('The data you have entered is invalid. Try again or type 11 for help\n')
589 time.sleep(3)
590
591 elif option == 4: # for displaying ticket details
592 try:
593 display_ticket(cur)
594 except (msc.DataError, ValueError):
595 print('The data you have entered is invalid. Try again or type 11 for help\n')
596 time.sleep(5)
597
598 elif option == 5: # for deleting ticket
599 try:
600 ticket_deletion(cur, con)
601 except (msc.DataError, ValueError):
602 print('The data you have entered is invalid. Try again or type 11 for help\n')
603 time.sleep(3)
604
605 elif option == 6: # for viewing any pending requests
606 get_request()
607 time.sleep(5)
608
609 elif option == 7: # for adding flights
610 try:
611 add_flights(cur, con)
612 print('flight added successfully')
613 except (msc.DataError, ValueError):
614 print('The data you have entered is invalid. Try again or type 11 for help\n')
615 time.sleep(3)
616
617 elif option == 8: # for changing details of flights
618 try:
619 flight_modification(cur, con)
620 except (msc.DataError, ValueError):
621 print('The data you have entered is invalid. Try again or type 11 for help\n')
622 time.sleep(3)
623
624 elif option == 9: # for displaying the details of one flight
625 try:
626 display_flight(cur)
627 except (msc.DataError, ValueError):
628 print('The data you have entered is invalid. Try again or type 11 for help\n')
629 time.sleep(5)
630
631 elif option == 10: # for deleting flights
632 try:
633 flight_deletion(cur, con)
634 except (msc.DataError, ValueError):
635 print('The data you have entered is invalid. Try again or type 11 for help\n')
636 time.sleep(3)
637
638 elif option == 11: # for displaying help
639
640 print(' Welcome!')
641 print(' ---------- \n')
642
643 print('Option 1: See all available flight')
644 print('Option 2: Reserve a ticket')
645 print('Option 3: Change ticket details')
646 print('Option 4: Display a ticket')
647 print('Option 5: Delete a ticket')
648 print('Option 6: View pending requests')
649 print('Option 7: Enter flight details')
650 print('Option 8: Modify flight details')
651 print('Option 9: Show a flights details')
652 print('Option 10: Delete a flight')
653 print('Option 11: Help')
654 print('Option 12: Move to User List\n\n')
655
656 print(' Details about the Table')
657 print(' ------------------------ \n\n')
658
659 print(' Table: Airline_Tickets')
660 print('------------------------\n')
661
662 print('Ticket_No --> INT (PRIMARY KEY), \n'
663 'Name --> VARCHAR(20)\n'
664 'Departure_Date --> DATE\n'
665 'Start --> VARCHAR(20)\n'
666 'Destination --> VARCHAR(20)\n'
667 'Flight_Number --> VARCHAR(10)\n'
668 'Flight_Class --> VARCHAR(15)\n')
669
670 print(' Table: Flight_Details')
671 print('-----------------------\n')
672
673 print('Flight_Name -> VARCHAR(30)\n'
674 'Flight_Number -> VARCHAR(7)\n'
675 'Number_Of_Seats -> SMALLINT\n'
676 'Date -> DATE\n'
677 'Start -> VARCHAR(20)\n'
678 'Boarding_Time --> TIME\n'
679 'Route -> VARCHAR(100) DEFAULT ""\n'
680 'Destination -> VARCHAR(20)\n')
681 time.sleep(5)
682
683 elif option == 12: # exit
684 running = False
685
686 else:
687 print('Invalid option, please enter a valid option')
688 time.sleep(3)
689
690
691def consumer_menu():
692 """
693 Function to display Consumer Menu
694 """
695
696 print(' MENU')
697 print(' ------ \n')
698 print('1: See Available Flights\n')
699 print('2: Reserve a Ticket\n')
700 print('3. Show Ticket Information\n')
701 print('4: Request Ticket Deletion\n')
702 print('5: Display Help\n')
703 print('6: Back to Main Menu\n')
704 print('-' * 50)
705
706
707def consumer_mode(cur, con):
708 """
709 Function for Consumer Mode
710 """
711 global request_queue
712 running = True
713 while running:
714
715 consumer_menu()
716 print()
717
718 try:
719 option = int(input('Choose an option: '))
720 except ValueError:
721 print('Invalid Type of Option. Please Enter a Valid Option (integers between 1 & 6)\n')
722 time.sleep(3)
723 continue
724
725 if option == 1: # for seeing flights
726 see_flights(cur)
727 time.sleep(5)
728
729 elif option == 2: # for creating a ticket
730 try:
731 reserve_ticket(cur, con)
732 except (msc.DataError, ValueError):
733 print('The data you have entered is invalid. Try again or type 5 for help\n')
734 time.sleep(5)
735
736 elif option == 3: # for displaying ticket details
737 try:
738 display_ticket(cur)
739 except (msc.DataError, ValueError):
740 print('The data you have entered is invalid. Try again or type 5 for help\n')
741 time.sleep(5)
742
743 elif option == 4: # for making a request for deletion
744 make_request()
745 time.sleep(2)
746
747 elif option == 5: # for displaying help
748
749 print(' Welcome!')
750 print(' ---------- \n')
751
752 print('Option 1: See available flights')
753 print('Option 2: Reserve a ticket')
754 print('Option 3: Request deletion of your ticket')
755 print('Option 4: Display your ticket info')
756 print('Option 5: Help')
757 print('Option 6: Close\n\n')
758 time.sleep(5)
759
760 elif option == 6: # for exiting consumer mode
761 with open('request queue.txt', 'a') as req:
762 req.write('\n'.join(request_queue + ['\n']))
763 request_queue = []
764
765 running = False # closing the program
766
767 else:
768 print('Invalid option, please enter a valid option')
769 time.sleep(3)
770
771
772# noinspection PyGlobalUndefined
773def connect_to_mysql():
774 """
775 Function to connect to MySQL
776 """
777 # user = input('enter username: ')
778 # passwrd = input('enter password: ')
779
780 # try:
781 # connection_ = msc.connect(user=user,
782 # password=passwrd,
783 # database=databse,
784 # host='localhost') # for mysql version
785
786 try:
787 connection_ = msc.connect(database='employees.db')
788
789 except msc.ProgrammingError: # in case there are any errors in connecting to the MySQL server
790 print('Error, Could not connect. Please check your details and try again')
791 connection_ = None
792
793 return connection_
794
795
796def validity_checker(cur, flight_no, start, stop, cre_or_mod=1): # cre_or_mod checks if modifying or creating, for seat
797 """
798 Function to check wether the details entered to create/change a ticket
799 are valid when compared to the avaliable flight details
800 """
801
802 cur.execute(f'SELECT * FROM flight_details WHERE Flight_Number="{flight_no}"')
803 flight_info = cur.fetchone()
804
805 if flight_info:
806 airport_list = [flight_info[4]] + flight_info[6].split(',') + [flight_info[7]]
807 if start in airport_list and stop in airport_list:
808 if flight_info[2] or not cre_or_mod:
809 cur.execute(f'UPDATE Flight_Details SET Number_Of_Seats = {flight_info[2] - cre_or_mod}'
810 f' WHERE Flight_Number = "{flight_no}"')
811 return True
812 else:
813 print('\nAll seats in this flight was booked, please try another flight\n')
814 else:
815 print('\nThis flight does not go to your destination. Try Again\n')
816 else:
817 print('\nFlight number is invalid, verify and please try again\n')
818 return False
819
820
821def see_flights(cur, date=None):
822 """
823 User Friendly Table to see all available flights and its details
824 """
825 if date is None:
826 cur.execute('SELECT * FROM flight_details')
827 else:
828 try:
829 cur.execute(f'SELECT * FROM flight_details WHERE Date="{date}"')
830 except (msc.DataError, msc.DatabaseError):
831 print('The date you have entered is incorrect, verify and try again')
832 return False
833
834 info = cur.fetchall()
835
836 if not info:
837 if date is None:
838 print('Sorry, but no flights are currently available.')
839 else:
840 print('No flights are available on for this date, please try another date')
841 return False
842
843 print()
844
845 print('Flight No', end=' |')
846 print('Flight Name' + ' ' * 19, end=' |')
847 print('Seat ', end='|')
848 print('Date' + ' ' * 7, end='|')
849 print('Start' + ' ' * 16, end='|')
850 print('Time' + ' ' * 4, end=' |')
851 print('Stops In BTW', end=' |')
852 print('Stop ')
853
854 h = '-'
855 print(h * 11, h * 31, h * 6, h * 11, h * 21, h * 9, h * 13, h * 21, sep='|')
856
857 for record in info:
858 print(f'{record[1] : <10}', end=' |')
859 print(f'{record[0] : <30}', end=' |')
860 print(f'{record[2] : <4}', end=' |')
861 print(record[3], end=' |')
862 print(f'{record[4] : <20}', end=' |')
863 print(f'{record[5]}', end=' |')
864 print(f'{str(len(record[6].split(",")) - 1): <13}', end='|')
865 print(record[7])
866
867 print()
868 return True
869
870
871if __name__ == '__main__':
872 connection = None
873 while connection is None:
874 connection = connect_to_mysql()
875
876 cursor = connection.cursor()
877
878 print()
879 print(__doc__) # prints the doc string
880 print()
881
882 confirm_create_tables(cursor)
883
884 while True:
885
886 print()
887 print('\t Choose User')
888 print('\t-------------\n')
889 print('1. Administrator')
890 print('2. Consumer')
891 print('3. Exit\n') # menu for choosing mode
892
893 try:
894 user_type = int(input('What kind of user are you: '))
895 except ValueError:
896 print('Please choose from the options given. Use a number from 1-3.')
897 continue
898
899 print('_' * 50)
900
901 if user_type == 1: # access administrator mode
902 if login(cursor):
903 administrator_mode(cursor, connection)
904 else:
905 print('Invalid Username or Password.')
906
907 elif user_type == 2: # access consumer mode
908 logged_in = sign_in_and_up(cursor, connection)
909 if logged_in:
910 consumer_mode(cursor, connection)
911
912 elif user_type == 3: # quit the program safely
913 print('Thank you for using this program')
914 cursor.close()
915 connection.close()
916 break
917
918 else:
919 print('Please choose from the options given.')
920 time.sleep(3)
921