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 __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_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 setup_database(self): self.database = Database.SQLiteDatabase("%s/databases/database.db" % self.working_dir) self.database.open_database() self.database.create_table( util.create_table_name(self.name), "ID INT, Title TEXT, Season INT, Episode INT, Date TEXT", True) self.database.close_database()
def database_connection(config): if config['db_engine'] in ('postgresql', 'postgres'): return PostgresqlDatabase(config['database'], config['host'], config['port'], config['user'], config['password'], config['require_ssl'] if 'require_ssl' in config else True) elif config['db_engine'] in ('sqlite', 'sqlite3'): return SQLiteDatabase(config['database']) raise Exception("Unsupported database type '{}'".format(db_engine))
def _db(self, db_engine): if db_engine in ('postgresql', 'postgres'): return PostgresqlDatabase( self.config['database'], self.config['host'], self.config['port'], self.config['user'], self.config['password'], ) elif db_engine in ('sqlite', 'sqlite3'): return SQLiteDatabase(self.config['database']) else: raise Exception("Unsupported database type '{}'".format(db_engine))
def database_connection(config): if config['db_engine'] in ('postgresql', 'postgres'): return PostgresqlDatabase( config['database'], config['host'], config['port'], config['user'], config['password'], config['require_ssl'] if 'require_ssl' in config else True) elif config['db_engine'] in ('sqlite', 'sqlite3'): if config.get('host', None) or config.get('user', None): raise Exception( "--host or --user options should not be used with default sqlite3 database engine" ) return SQLiteDatabase(config['database']) raise Exception("Unsupported database type '{}'".format( config['db_engine']))
def parse(self): ''' Parse the file. :return: a tuple of a :class:`.landscape.landscape` object and its name (a string) ''' # Get database object. fpath = self.file if not os.path.isfile(fpath): raise IOError('Landscape file not found.') o = SQLiteDatabase(fpath) self.database = o # Get metadata. self.metadata = self._getLandscapeMetadata() # Get the alignment. self._makeAlignment() # Create an empty landscape structure. self.landscape = landscape(self.alignment, root=False) # Add all of the trees. self._getTrees() # Set landscape operator. if len(self.landscape) > 0: index = self.landscape.getNodeNames()[-1] self.landscape.setOperator( self.landscape.getTree(index).getOrigin()) # Ensure all edges are established. self._getGraph() # Apply locks. self._applyLocks() return (self.landscape, self.getName())
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)
res += string[i] i += 1 return res with open(XML_file) as f: tree = parse(f) currencies = [] for child in tree.iter(): if child.tag == "targetCurrency": currencies.append(child.text) cols = {"currency": "TEXT", "exchange_rate": "REAL", "inverse_rate": "REAL"} db = SQLiteDatabase("currencies") db.execute_query("DROP TABLE IF EXISTS usd", commit=True) db.create_table("usd", cols) for curr in currencies: cols["currency"] = curr in_curr = False for child in tree.iter(): if child.tag == "targetCurrency": if child.text == curr: in_curr = True elif child.tag == "exchangeRate" and in_curr: # ex_rate = float(child.text) cols["exchange_rate"] = to_float(child.text) elif child.tag == "inverseRate" and in_curr: # inv_rate = float(child.text)
def _dump(self,path='.'): # Open the file. fpath = os.path.join(path,self.cleansuff) # Generate file path. if os.path.isfile(fpath): os.unlink(fpath) # Remove file if already exists. o = SQLiteDatabase(fpath) # Open an SQLite database at that location. self.database = o # Assign this object to field. # Construct the schema for the landscape. self._schema() # Include metadata about the landscape. Required for parsing. o.insertRecord('metadata',['name',self.name]) o.insertRecord('metadata',['version',VERSION]) # Add the alignment as a set of sequence records labelled by taxa. index = 0 if self.landscape.alignment != None: for s in self.landscape.alignment: o.insertRecord('alignment',[index,s.name,s.sequence]) index += 1 # Add all of the trees (most memory intensive elements in the DB). for i in self.landscape.iterNodes(): t = self.landscape.getTree(i) s = t.getStructure() find = self.landscape.findTreeTopologyByStructure(s) if (find == None): raise AssertionError('Tree topology search failed (%s).' % ( str(i))) elif (find == i): # Verify unique identity of this tree. # Insert this tree as a record. name = t.getName() newi = t.getNewick() ori = t.getOrigin() scs = [t.getScore()[x] for x in xrange(0,len(t.getScore()))] o.insertRecord('trees',[i,name,newi,ori,scs[0],scs[1], self.landscape.getNode(i)['explored'], s]) else: sys.stderr.write( 'Warning: Tree %s has identical structure to %s.\n' % ( str(find),str(i))) # Add the graph by copying its adjacency list. adj_list = self.graph.edges_iter() for tupl in adj_list: source,target = [int(x) for x in tupl] o.insertRecord('graph',[source,target]) # Add all of the locks. for l in self.landscape.getLocks(): tree = l.topology.toTree() treeIndex = self.landscape.indexOf(tree) o.insertRecord('locks',[treeIndex,l.getBranchIndex()]) # Close the file. o.close() # Return the path. return fpath
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 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
def _dump(self, path='.'): # Open the file. fpath = os.path.join(path, self.cleansuff) # Generate file path. if os.path.isfile(fpath): os.unlink(fpath) # Remove file if already exists. o = SQLiteDatabase(fpath) # Open an SQLite database at that location. self.database = o # Assign this object to field. # Construct the schema for the landscape. self._schema() # Include metadata about the landscape. Required for parsing. o.insertRecord('metadata', ['name', self.name]) o.insertRecord('metadata', ['version', VERSION]) # Add the alignment as a set of sequence records labelled by taxa. index = 0 if self.landscape.alignment != None: for s in self.landscape.alignment: o.insertRecord('alignment', [index, s.name, s.sequence]) index += 1 # Add all of the trees (most memory intensive elements in the DB). for i in self.landscape.iterNodes(): t = self.landscape.getTree(i) s = t.getStructure() find = self.landscape.findTreeTopologyByStructure(s) if (find == None): raise AssertionError('Tree topology search failed (%s).' % (str(i))) elif (find == i): # Verify unique identity of this tree. # Insert this tree as a record. name = t.getName() newi = t.getNewick() ori = t.getOrigin() scs = [t.getScore()[x] for x in xrange(0, len(t.getScore()))] o.insertRecord('trees', [ i, name, newi, ori, scs[0], scs[1], self.landscape.getNode(i)['explored'], s ]) else: sys.stderr.write( 'Warning: Tree %s has identical structure to %s.\n' % (str(find), str(i))) # Add the graph by copying its adjacency list. adj_list = self.graph.edges_iter() for tupl in adj_list: source, target = [int(x) for x in tupl] o.insertRecord('graph', [source, target]) # Add all of the locks. for l in self.landscape.getLocks(): tree = l.topology.toTree() treeIndex = self.landscape.indexOf(tree) o.insertRecord('locks', [treeIndex, l.getBranchIndex()]) # Close the file. o.close() # Return the path. return fpath