class ToysApp(Tk): def __init__(self, toy_db_name): Tk.__init__(self) self.__init_DB(toy_db_name) self.__init_UI() def __init_DB(self, toy_db_name): self.toy_DB = SQLiteDatabase(toy_db_name) structure = { "name": "TEXT", "price": "NUMERIC", "min_age": "NUMERIC", "max_age": "NUMERIC" } self.table_name = "toys_catalogue" self.toy_DB.create_table(self.table_name, structure) def __init_UI(self): self.title("Toy Search") self.addMenu = Menu(self, tearoff=0) self.addMenu.add_command(label="Add a toy", command=self.add_toy_handler) self.config(menu=self.addMenu) Label(self, text="Search for toys").grid(row=0, column=0) Label(self, text="Kid age:").grid(row=1, column=0) self.kid_age_inp = Entry(self) self.kid_age_inp.grid(row=1, column=1) Label(self, text="Max price:").grid(row=2, column=0) self.toy_price_inp = Entry(self) self.toy_price_inp.grid(row=2, column=1) Button( self, text="Search", command=self.search_toys_handler ).grid(row=3, column=1) def add_toy_handler(self): self.addWindow = Toplevel(self) self.addWindow.title("Add a toy to database") Label(self.addWindow, text="Toy name:").grid(row=0, column=0) self.toy_name_inp = Entry(self.addWindow) self.toy_name_inp.grid(row=0, column=1) Label(self.addWindow, text="Toy price:").grid(row=1, column=0) self.toy_price_inp = Entry(self.addWindow) self.toy_price_inp.grid(row=1, column=1) Label(self.addWindow, text="Min age:").grid(row=2, column=0) self.min_age_inp = Entry(self.addWindow) self.min_age_inp.grid(row=2, column=1) Label(self.addWindow, text="Max age:").grid(row=3, column=0) self.max_age_inp = Entry(self.addWindow) self.max_age_inp.grid(row=3, column=1) Button( self.addWindow, text="Add", command=self.save_toy_handler ).grid(row=4, column=1) def search_toys_handler(self): self.resultsWindow = Toplevel(self) self.resultsWindow.title("Toys found") # self.resultsWindow.propagate(0) toys = self._toy_search() for i in range(len(toys)): Label( self.resultsWindow, text="{}".format(toys[i][0]) ).grid(row=i, column=0) Label( self.resultsWindow, text="{}".format(toys[i][1]) ).grid(row=i, column=1) # print(self.resultsWindow.winfo_height()) self.resultsWindow.geometry("{w}x{h}".format( w=250, h=len(toys)*20 )) def _toy_search(self): query = """max_age>={age} AND min_age<={age} AND price<={price}""".format( age=int(self.kid_age_inp.get()), price=int(self.toy_price_inp.get()) ) return self.toy_DB.fetchall( self.table_name, query, fetch_fields=["name", "price"] ) def save_toy_handler(self): values = { "name": self.toy_name_inp.get(), "price": int(self.toy_price_inp.get()), "min_age": int(self.min_age_inp.get()), "max_age": int(self.max_age_inp.get()) } self.addWindow.destroy() self.toy_DB.join(self.table_name, values)
class CurrencyConverterApp: def __init__(self, currency_db, tablename): # DB currencies stuff self.DB = SQLiteDatabase(currency_db) # table: currency, exchange_rate, inverse_rate self.table = tablename self.currencies = self._get_currencies_list() # server stuff self.commands = {"": self.start, "calculate": self.calculate} def __call__(self, environ, start_response): command = environ.get('PATH_INFO', '').lstrip('/') form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ) error = False if command in self.commands: body = self.commands[command](form) if body: start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')]) else: error = True else: error = True if error: start_response('404 NOT FOUND', [('Content-type', 'text/plain')]) body = 'Daaafaaaquuu! 404 is here, dude.' return [bytes(body, encoding='utf-8')] def start(self, form=None): return self._format_resp(START_PAGE, [("currencies", self._curr_opt_), ("value", "")]) def convert(self, sell, buy, qnt): cond = 'currency="{}"' ex_rate = float( self.DB.fetchall(self.table, cond.format(buy), ["exchange_rate"])[0][0]) # print(ex_rate) inv_rate = float( self.DB.fetchall(self.table, cond.format(sell), ["inverse_rate"])[0][0]) return qnt * ex_rate * inv_rate def calculate(self, form): tags = ["curr_sell", "curr_buy", "sell_quantity"] if all([tag in form for tag in tags]): curr_sell = form["curr_sell"].value curr_buy = form["curr_buy"].value qnt = float(form["sell_quantity"].value) converted = self.convert(curr_sell, curr_buy, qnt) converted = str(qnt) + " " + curr_sell + " = " + str( converted) + " " + curr_buy else: return "error" return self._format_resp(START_PAGE, [("currencies", self._curr_opt_), ("value", converted)]) def _get_currencies_list(self): currencies = self.DB.show_table(self.table, fields=["currency"]) currencies = [c[0] for c in currencies] return sorted(currencies) @property def _curr_opt_(self): res = '<option value="Select currency" disabled>Select currency</option>' opt_pattern = '<option value="{v}">{v}</option>\n' for curr in self.currencies: res += opt_pattern.format(v=curr) return res def _format_resp(self, resp_file, arg_list): """ потому что ?)$#@$0 css со своими четырежды ?)$#@$0 фигурными скобками не может ?)$#@$0 не помешать :param resp_file: html file with response :param arg_list: list of tuples like this: ("param_name", value) :return: formatted response without any errors! """ with open(resp_file) as f: lines = f.readlines() for (key, value) in arg_list: for j, line in enumerate(lines): keyword = "{" + key + "}" if keyword in line: i = line.find(keyword) lines[j] = line[:i] + str(value) + line[i + len(keyword):] return ''.join(lines)
class VisavisApp(Tk): def __init__(self, db_name): Tk.__init__(self) self.months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] self.__init_DB(db_name) self.__init_UI() def __init_DB(self, db_name): self.DB = SQLiteDatabase(db_name) structure = { "name": "TEXT", "day": "NUMERIC", "month": "TEXT", "year": "NUMERIC" } self.table_name = "birthdays" self.DB.create_table(self.table_name, structure) def __init_UI(self): self.title("Almost Calendar") self.addMenu = Menu(self, tearoff=0) self.addMenu.add_command(label="Add person", command=self.add_person_handler) self.addMenu.add_command(label="Find birthday", command=self.find_bday_handler) self.config(menu=self.addMenu) birthdays = self._fetch_week_bdays() if len(birthdays) == 0: Label(self, text="This week birthdays").grid(row=0, column=0) self.widgets = [] for i in range(len(birthdays)): self.widgets.append(Label(self, text="{}".format(birthdays[i][0]))) self.widgets[len(self.widgets) - 1].grid(row=i, column=0) date = "{dd} {mm} {yy}".format( dd=birthdays[i][1], mm=birthdays[i][2], yy=birthdays[i][3], ) self.widgets.append(Label(self, text=date)) self.widgets[len(self.widgets) - 1].grid(row=i, column=1) # print(self.resultsWindow.winfo_height()) # self.geometry("{w}x{h}".format( # w=250, h=len(birthdays)*20 # )) def _fetch_week_bdays(self): buf = (monthrange(date.today().year, date.today().month)[1] - date.today().day ) # проверка, выскакиваем ли мы за рамки месяца if buf < 7: c = """OR (day<={dd} AND month="{mm}")""".format( dd=buf, mm=self.months[ date.today().month]) # если да, докидываем еще условие else: c = "" # ну нет так нет condition = """(day>={dd} AND day<={dd}+7 AND month="{mm}") {c2}""".format(dd=date.today().day, mm=self.months[date.today().month - 1], c2=c) return self.DB.fetchall(self.table_name, condition, fetch_fields=["name", "day", "month", "year"]) def find_bday_handler(self): names = [ n[0] for n in self.DB.show_table(self.table_name, fields=["name"]) ] self.findWindow = Toplevel(self) self.findWindow.title("Find birthday") self.search_name_inp = Spinbox(self.findWindow, values=names) self.search_name_inp.grid(row=0, column=0) Button(self.findWindow, text="Find", command=self.find_handler).grid(row=1, column=0) self.show_res_label = Label(self.findWindow, text="") self.show_res_label.grid(row=2, column=0) def find_handler(self): name = '"{}"'.format(self.search_name_inp.get()) # print(name) bday = ' '.join( map( str, self.DB.fetchall(self.table_name, condition={"name": name}, fetch_fields=["day", "month", "year"])[0])) self.show_res_label.config(text=bday) self.show_res_label.update_idletasks() def add_person_handler(self): self.addWindow = Toplevel(self) self.addWindow.title("Add person to database") Label(self.addWindow, text="Name:").grid(row=0, column=0) self.name_inp = Entry(self.addWindow) self.name_inp.grid(row=0, column=1) Label(self.addWindow, text="Birth day:").grid(row=1, column=0) self.b_day_inp = Entry(self.addWindow) self.b_day_inp.grid(row=1, column=1) Label(self.addWindow, text="Birth month:").grid(row=2, column=0) self.b_month_inp = Spinbox(self.addWindow, values=self.months) self.b_month_inp.grid(row=2, column=1) Label(self.addWindow, text="Birth year:").grid(row=3, column=0) self.b_year_inp = Entry(self.addWindow) self.b_year_inp.grid(row=3, column=1) Button(self.addWindow, text="Add", command=self.save_person_handler).grid(row=4, column=1) def save_person_handler(self): values = { "name": self.name_inp.get(), "day": int(self.b_day_inp.get()), "month": self.b_month_inp.get(), "year": int(self.b_year_inp.get()) } self.addWindow.destroy() self.DB.join(self.table_name, values) self._clear_screen() self.__init_UI() def _clear_screen(self): for widget in self.widgets: widget.destroy() del widget