def _add_message(self, data): database = DatabaseManager() security = Security() user = security.user password = security.password database.connect(dialect=self.dialect, user=user, passwd=password, database=self.db) database.add_messages(data)
from database import DatabaseManager from security import Security sec = Security() user = sec.user passwd = sec.password dialect = sec.dialect db = sec.database database = DatabaseManager() database.connect(dialect=dialect, user=user, passwd=passwd, database=db) print database.get_messages() #print database.add_payee("BRITAM") # database.add_cheque_type("Type") #database.add_bank("Equity") # database.delete_cheque_type("Standard") # database.delete_bank("Equity") # database.delete_cheque("BRITAM") # database.delete_payee("BRITAM") print database.get_bank() print database.get_payee() print database.get_chequetype()
class Controller(object, Initializer): def __init__(self): self.now = datetime.datetime.today() self.latter = datetime.timedelta(hours=24) + self.now self.db = DatabaseManager() self.sec = Security() self.user = self.sec.user self.password = self.sec.password self.dialect = self.sec.dialect self.database = self.sec.database self.db.connect(dialect=self.dialect, user=self.user, passwd=self.password, database=self.database) self.waiting_messages = list() Initializer.__init__(self) def daily_messenger(self): """ Manages the application clock """ seconds = 30 while True: time.sleep(seconds) if self.now.hour < 8: hour = (8 - self.now.hour) + 24 elif self.now.hour > 8: hour = (24 - self.now.hour) else: hour = 24 self.latter = datetime.timedelta(hours=hour) + self.now seconds = hour * 60 * 60 self.now = datetime.datetime.now() msg = "Daily Thread initiating messenger" log.info(msg) print >>sys.stdout, msg if self.time_checker(): log.debug("Daily Thread system update") message_controller = MessageController(self.db) message_controller.central_command() self.message_sender() with closing(open("bin/details.txt", "w")) as fl: fl.write(time.ctime()) def hourly_messenger(self): while True: time.sleep(3600) collect_data() self.message_collector() msg = "Hourly Thread initiating messenger" log.info(msg) print >>sys.stdout , msg self.message_sender() def hustler(self): daily_thread = Thread(target=self.daily_messenger, name="Daily Thread") hourly_thread = Thread(target=self.hourly_messenger, name="Hourly Thread") daily_thread.start() hourly_thread.start() def message_collector(self): self.waiting_messages = list() messages = self.db.get_outbox("waiting") if isinstance(messages, list) and messages: for message in messages: inst = PhoneNumber(message["phone"]) phn = inst.list_of_numbers() if phn: message_tuple = (message["phone"], message["message"]) else: continue self.waiting_messages.append(message_tuple) def time_checker(self): if not os.path.exists("bin/details.txt"): return True with closing(open("bin/details.txt", "rb")) as fl: start_date = fl.readline() if start_date[:10] == time.ctime()[:10]: print False, start_date[:10], time.ctime()[:10] return False else: print True, start_date[:10], time.ctime()[:10] return True def message_sender(self): self.message_collector() msg = "%d messages waiting to be sent" % len(self.waiting_messages) log.info(msg) print >>sys.stdout, msg sent_list = [] for message in self.waiting_messages: sender = Messenger([message]) sender.check_config("smsleopard") sent_msg = sender.send_sms()[0] sent_list.extend(sent_msg) msg = "%d sent messages" % len(sent_list) log.info(msg) for sent in sent_list: self.db.update_outbox(sent)
class FileManager(object): """ Contains methods responsible for managing the crucial file components of the application This files include: allclients.dat balance.dat extensions.dat expiry.dat config.conf etc. """ def __init__(self): self.files = { "clients": "allclients.dat", "balance": "balance.dat", "renewal": "expiry.dat", "newinvoice": "renewal.dat", "extension": "extensions.dat", "birthday": "allclients.dat" } self.database = DatabaseManager() self.report_file = "bin/report" self.message_file = "bin/messages" self.config_file = "bin/config.conf" self.folders = ["bin"] self.initializer() self.configarations() self.security = Security() self.user = self.security.user self.password = self.security.password self.dialect = self.security.dialect self.db = self.security.database self.database.connect(dialect=self.dialect, user=self.user, passwd=self.password, database=self.db) def initializer(self): for name in self.folders: if not os.path.exists(name): os.mkdir(name) for key, name in self.files.items(): name = "bin/" + name if not os.path.exists(name): msg = key + " file missing" self.reporter((False, msg)) log.warning(msg) else: msg = key + " file found" self.reporter(("server", msg)) def configarations(self): """ interval is the date differences that the messages should be sent. status determines if the messages are to be sent or not next means the next date general messages have to be sent """ config_types = { 'clients': {"interval": False, "status": False, "next": False}, 'balance': {"interval": False, "status": False, "amount": 500}, 'renewal': {"interval": [15, 5], "status": True}, 'newinvoice': {"interval": [15, 5], "status": False}, 'extension': {"interval": [15, 5], "status": False}, 'birthday': {"status": True}, 'cheque': {"interval": [15, 5], "status": True}, 'connection': {'dialect': "mysql", 'database': "bima"}, } if not os.path.exists(self.config_file): with closing(open(self.config_file, "wb")) as fl: Pickle.dump(config_types, fl) log.info("Setting up system configurations") if not os.path.exists(self.message_file): self.initialize_messages() def reporter(self, details): """ Manages a report file that has details on errors and ho the application executes the most important steps. The details parameter is either a Tuple or a list of Tuples. The tuple has a type of message and the message itself. Error messages are represented by a False object while the rest have there specific names written out. """ if not os.path.exists(self.report_file): with open(self.report_file, "wb") as fl: Pickle.dump([], fl) with closing(open(self.report_file, "rb")) as fl: data = Pickle.load(fl) with closing(open(self.report_file, "wb")) as fl: if isinstance(details, tuple): now = time.ctime() type_ = details[0] message = details[1] data.append((now, type_, message)) elif isinstance(details, list): for detail in details: now = time.ctime() type_ = detail[0] message = detail data.append((now, type_, message)) Pickle.dump(data, fl) def report_reader(self): """Returns the content of the report file which can then be written in a logfile""" if not os.path.exists(self.report_file): return "File does not exist" else: with closing(open(self.report_file, "rb")) as fl: data = Pickle.load(fl) return data def initialize_messages(self): """Creates the message file and initializes the default messages in it""" balance = """Dear client,your outstanding insurance premium balance is Ksh $AMOUNT.Kindly send your payments.For enquiries call 0714046604.Thanks for your support.""" renewal = """Dear client your $POLICY policy expires on $DATE. Kindly send us the renewal instructions.For enquiries call 0714046604.Thank you""" newinvoice = """Dear client. We have renewed your $POLICY policy. Kindly let us have your payment of Ksh:$AMOUNT.For enquiries call 0714046604. Thank you.""" cheque = """Dear client kindly note that your $TYPE cheque no: $NUMBER ( &BANK ) of Ksh $AMOUNT id due for banking on $DUE""" general = "" quick = "" birthday = """Wishing you the very best as you celebrate your big day. Happy Birthday to you from K-BIMA""" default = { "balance": balance, "renewal": renewal, "newinvoice": newinvoice, "general": general, "quicktxt": quick, "birthday": birthday, "cheque": cheque, } with closing(open(self.message_file, "wb")) as fl: Pickle.dump(default, fl) log.info("Setting up default message files and details") log.debug("Setting up message database configurations") for key, value in default.items(): data = (key, "server2", False, value, datetime.datetime.today()) self._add_message(data) def _add_message(self, data): database = DatabaseManager() security = Security() user = security.user password = security.password database.connect(dialect=self.dialect, user=user, passwd=password, database=self.db) database.add_messages(data) def read_message(self, type_): """Returns the message of the type given in the parameter""" if not os.path.exists(self.message_file): messages = self.initialize_messages() else: with closing(open(self.message_file)) as fl: messages = Pickle.load(fl) try: message = messages[type_] except KeyError: return False return message def change_message(self, type_, message): """Changes the message specified in by the type parameter""" with closing(open(self.message_file, "rb")) as fl: data = Pickle.load(fl) with closing(open(self.message_file, "wb")) as fl: data[type_] = message Pickle.dump(data, fl) def read_file(self, name): """Returns the contents of the data files containing the client details eg the balance file""" try: file_name = "bin/" + self.files[name] except KeyError: return False, "Invalid file name request" try: with closing(open(file_name, "rb")) as fl: data = Pickle.load(fl) if isinstance(data, list): return True, data else: print file_name, type(data) return False, "The %s file has been corrupted" % name except EOFError: return False, "The %s file has been corrupted or cannot be found" % name except IOError: return False, "The %s file does not exists" % name
return pb.IPerspective, avatar, lambda: None class LoginProtocol(basic.LineReceiver): pass class LoginFactory(protocol.ServerFactory): protocol = LoginProtocol def __init__(self, portal): self.portal = portal db_access = DatabaseManager() db_access.connect(dialect="mysql", user="******", passwd="creawib", database="bima") users = db_access.get_user_details("users") passwords = db_access.get_user_details("passwords") p = portal.Portal(ClassRealm(ServerFunctions(users, passwords, db_access), users)) p.registerChecker(PasswordDictChecker(passwords)) checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() def register(name, passwd): checker.addUser(name, passwd) p.registerChecker(checker) def main(): c2 = AllowAnonymousAccess() p.registerChecker(c2) if not os.path.exists('tmp'): os.mkdir('tmp')
ioloop = tornado.ioloop.IOLoop.instance() ioloop.start() def ping(self): print("pong!") # ============================================================================================================= _main = None _db = None #_menu = None if __name__ == "__main__": print("main") _main = main() #Menu.Instance().number = 10 print("creating menu") _menu = Menu() print("created menu") _menu.number = 10 _db = DatabaseManager() _db.connect() _main.launch_server() _main.show_index()