def update_db(self): confpath = os.path.join(self.conf.home, 'data', 'youmoney.conf') if self.status == self.UPDATE: req = {'act': 'getdata', 'id': self.conf['id']} header, data = self.reqconn.docmd(req) logfile.info('getdata header:', header, 'data len:', len(data)) if data and header.has_key('crc32'): v1 = binascii.crc32(data) if v1 != header['crc32']: logfile.info('crc32 error! local:', v1, 'server:', header['crc32']) header['ret'] = -1 header['error'] = 'crc32 error' return header real = zlib.decompress(data) lastdb = self.conf['lastdb'] bakdb = lastdb + '.bak' tmpdb = lastdb + '.tmp' f = open(tmpdb, 'wb') f.write(real) f.close() if os.path.isfile(bakdb): os.remove(bakdb) if os.path.isfile(lastdb): os.rename(lastdb, bakdb) os.rename(tmpdb, lastdb) return header return {'ret': -2, 'error': 'update status error:' + str(self.status)}
def OnFileSaveAs(self, event): dlg = wx.FileDialog(self, message=_("Account save as..."), defaultDir=os.getcwd(), defaultFile="", wildcard=_("EasyAccout Database (*.db)|*.db"), style=wx.SAVE) dlg.SetFilterIndex(2) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() logfile.info("save file:", path) if not path.endswith('.db'): path += ".db" if os.path.isfile(path): wx.MessageBox(_('File exist'), _('Can not save account file'), wx.OK | wx.ICON_INFORMATION) return try: shutil.copyfile(self.conf['lastdb'], path) except Exception, e: wx.MessageBox( _('Save account failture:') + str(e), _('Can not save account file'), wx.OK | wx.ICON_INFORMATION) return
def OnFileImportData(self, event): dlg = dialogs.ImportDataDialog(self) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() if not path: dlg.Destroy() return exp = export.DataImport(self.db, 'gbk') try: idlg = wx.ProgressDialog(_('Importing...'), _('Waiting for importing.'), maximum=100, parent=self, style=wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME) exp.itemdata(path, idlg) idlg.Destroy() except Exception, e: logfile.info(traceback.format_exc()) wx.MessageBox(str(e), _('Import Error:'), wx.OK | wx.ICON_INFORMATION) else: wx.MessageBox(_('Import complete!'), _('Information'), wx.OK | wx.ICON_INFORMATION) self.reload()
def load(self): self.list.ClearAll() self.init() sql = "select * from recycle order by id" logfile.info(sql) rets = self.parent.parent.db.query(sql) if rets: for row in rets: try: cate = self.parent.parent.category.catemap( row['type'], row['category']) typestr = storage.catetypes[row['type']] except: sql = "delete from recycle where id=" + str(row['id']) self.parent.parent.db.execute(sql) continue item = self.list.InsertStringItem(0, typestr) #self.list.SetStringItem(item, 0, storage.catetypes[row['type']]) self.list.SetStringItem(item, 1, cate) self.list.SetStringItem(item, 2, str(row['num'])) self.list.SetStringItem(item, 3, storage.payways[row['payway']]) self.list.SetStringItem(item, 4, storage.cycles[row['addtime']]) self.list.SetStringItem(item, 5, row['explain']) self.list.SetItemData(item, row['id'])
def OnFileImportData(self, event): dlg = dialogs.ImportDataDialog(self) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() if not path: dlg.Destroy() return exp = export.DataImport(self.db, "gbk") try: idlg = wx.ProgressDialog( _("Importing..."), _("Waiting for importing."), maximum=100, parent=self, style=wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME, ) exp.itemdata(path, idlg) idlg.Destroy() except Exception, e: logfile.info(traceback.format_exc()) wx.MessageBox(str(e), _("Import Error:"), wx.OK | wx.ICON_INFORMATION) else: wx.MessageBox(_("Import complete!"), _("Information"), wx.OK | wx.ICON_INFORMATION) self.reload()
def OnFileChange(self, event): dlg = wx.FileDialog( self, message=_("Change account path..."), defaultDir=os.getcwd(), defaultFile="", wildcard=_("YouMoney Database (*.db)|*.db"), style=wx.SAVE) dlg.SetFilterIndex(2) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() logfile.info("save file:", path) if not path.endswith('.db'): path += ".db" self.conf.dump() oldfile = self.conf['lastdb'] if os.path.isfile(path): wx.MessageBox(_('File exist'), _('Can not save account file'), wx.OK|wx.ICON_INFORMATION) return try: shutil.copyfile(self.conf['lastdb'], path) except Exception, e: wx.MessageBox(_('Change account path failture:') + str(e), _('Can not save account file'), wx.OK|wx.ICON_INFORMATION) return self.db.close() if os.path.isfile(oldfile): os.remove(oldfile) self.initdb(path) #self.db = storage.DBStorage(path) self.reload() self.conf['lastdb'] = path self.conf.dump() self.SetStatusText(_('Database file: ') + self.conf['lastdb'], 0)
def OnCategoryDel(self, event): data = self.tree.GetPyData(self.currentItem) if not data or data['id'] <= 0: logfile.info("category data invalid.") return #frame = self.parent.parent ret = self.dbx.get(data['id']) if not ret: logfile.info('not found del category:', data['id']) return mytype = ret[0]['type'] name = ret[0]['name'] if name == _('No Category'): dlg = wx.MessageDialog(self, _('Can not delete this category!'), _('Notice:'), wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() return else: dlg = wx.MessageDialog(self, _('To delete category') + '"' + name + '"' \ + _(', all child categories will move to "No Category"'), _('Notice:'),wx.OK | wx.ICON_INFORMATION | wx.CANCEL) if dlg.ShowModal() == wx.ID_OK: try: self.dbx.delete(mytype, data['id']) except Exception, e: wx.MessageBox( _('Delete category failure!') + str(e), _('Delete category information'), wx.OK | wx.ICON_INFORMATION) self.frame.reload() dlg.Destroy()
def OnFileNew(self, event): dlg = wx.FileDialog( self, message=_("New account file save..."), defaultDir=os.getcwd(), defaultFile="", wildcard=_("YouMoney Database (*.db)|*.db"), style=wx.SAVE, ) dlg.SetFilterIndex(2) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() logfile.info("save file:", path) if not path.endswith(".db"): path += ".db" if os.path.isfile(path): wx.MessageBox(_("File exist"), _("Can not save account file"), wx.OK | wx.ICON_INFORMATION) return self.db.close() self.initdb(path) self.reload() self.conf["lastdb"] = path self.conf.dump() self.conf.iscreate = True self.initcate() self.SetStatusText(_("Database file: ") + self.conf["lastdb"], 0) dlg.Destroy()
def OnFileNew(self, event): dlg = wx.FileDialog( self, message=_("New account file save..."), defaultDir=os.getcwd(), defaultFile="", wildcard=_("YouMoney Database (*.db)|*.db"), style=wx.SAVE) dlg.SetFilterIndex(2) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() logfile.info("save file:", path) if not path.endswith('.db'): path += ".db" if os.path.isfile(path): wx.MessageBox(_('File exist'), _('Can not save account file'), wx.OK|wx.ICON_INFORMATION) return self.db.close() self.initdb(path) self.reload() self.conf['lastdb'] = path self.conf.dump() self.conf.iscreate = True self.initcate() self.SetStatusText(_('Database file: ') + self.conf['lastdb'], 0) dlg.Destroy()
def get_ready(self, cid): cyclelist = [] for k in storage.cycles: if type(k) != types.IntType: cyclelist.append(k) cyclelist.reverse() sql = "select * from recycle where id=" + str(cid) ret = self.db.query(sql) if ret: row = ret[0] typestr = storage.catetypes[row['type']] if typestr == _('Payout'): payout_cate = category.catestr_by_id('payout', row['category']) income_cate = category.income_catelist[0] else: payout_cate = category.payout_catelist[0] income_cate = category.catestr_by_id('income', row['category']) ready = {'payout_cates':category.payout_catelist, 'payout_cate':payout_cate, 'income_cates':category.income_catelist, 'income_cate':income_cate, 'num':row['num'], 'types':[_('Payout'), _('Income')], 'type':typestr, 'cycles':cyclelist, 'cycle':storage.cycles[row['addtime']], 'explain':row['explain'], 'pay':storage.payways[row['payway']], 'mode':'update', 'id':row['id']} logfile.info('ready:', ready) #print 'update data:', ready return ready return None
def OnItemActivated(self, event): try: currentItem = event.m_itemIndex except: currentItem = self.currentItem id = self.list.GetItemData(currentItem) category = self.parent.parent.category sql = "select * from capital where id=" + str(id) ret = self.parent.parent.db.query(sql) if ret: row = ret[0] payway = storage.payways[row['payway']] ready = { 'cates': category.catelist(self.type), 'cate': category.catestr_by_id(self.type, row['category']), 'num': row['num'], 'explain': row['explain'], 'year': row['year'], 'month': row['month'], 'day': row['day'], 'pay': payway, 'mode': 'update', 'id': row['id'] } logfile.info('ready:', ready) #print 'update data:', ready if self.type == 'payout': self.parent.parent.payout_dialog(ready) else: self.parent.parent.income_dialog(ready)
def getall(self): sql = "select * from recycle order by id" logfile.info(sql) rets = self.db.query(sql) if rets: #for row in rets: delx = [] for i in range(0, len(rets)): row = rets[i] try: catestr = category.catemap(row['type'], row['category']) typestr = storage.catetypes[row['type']] row['catestr'] = catestr row['typestr'] = typestr row['paywaystr'] = storage.payways[row['payway']] row['addtimestr'] = storage.cycles[row['addtime']] except: sql = "delete from recycle where id=" + str(row['id']) self.db.execute(sql) delx.append(i) continue if delx: delx.reverse() for i in delx: del self.rets[i] return rets
def table_diff_one(self, table, fields): logfile.info('table:', table) fieldslist = fields.split(',') sql = "select %s from %s" % (fields, table) logfile.info('sql:', sql) newret = self.query(self.newdb, sql) oldret = self.query(self.olddb, sql) # newstr, oldstr retstr = ['', ''] #for res in [newret, oldret]: rets = [newret, oldret] for i in range(0, len(rets)): res = rets[i] if res: row = res[0] xs = [] for ii in range(0, len(row)): f = row[ii] if type(f) == types.UnicodeType: f = f.encode('utf-8') xs.append(str(f)) #print 'xs:', xs, fsep.join(xs), retstr, retstr[0], retstr[1], i, type(i) retstr[i] = self.fsep.join(xs) #if rets[0] != rets[1]: # logfile.info('diff:', rets) if rets[0] != rets[1]: return rets[0], rets[1] return '', ''
def update(self): newver = None try: info = system_version() logfile.info('local system:', info) req = { 'act': 'checklog', 'sys': sys.platform, 'ver': version.VERSION, 'info': info, 'name': storage.name } reqconn = netreq.Request(5) header, data = reqconn.docmd(req) logfile.info('update header:', header) reqconn.close() newver = header.get('version', '') if not self.version_diff(newver): logfile.info('not need update:', newver) return None logfile.info('found new version:', newver) return newver except: logfile.info(traceback.format_exc()) return newver
def update_db(self): confpath = os.path.join(self.conf.home, 'data', 'youmoney.conf') if self.status == self.UPDATE: req = {'act':'getdata', 'id':self.conf['id']} header, data = self.reqconn.docmd(req) logfile.info('getdata header:', header, 'data len:', len(data)) if data and header.has_key('crc32'): v1 = binascii.crc32(data) if v1 != header['crc32']: logfile.info('crc32 error! local:', v1, 'server:', header['crc32']) header['ret'] = -1 header['error'] = 'crc32 error' return header real = zlib.decompress(data) lastdb = self.conf['lastdb'] bakdb = lastdb + '.bak' tmpdb = lastdb + '.tmp' f = open(tmpdb, 'wb') f.write(real) f.close() if os.path.isfile(bakdb): os.remove(bakdb) if os.path.isfile(lastdb): os.rename(lastdb, bakdb) os.rename(tmpdb, lastdb) return header return {'ret':-2, 'error':'update status error:' + str(self.status)}
def OnFileSaveAs(self, event): dlg = wx.FileDialog( self, message=_("Account save as..."), defaultDir=os.getcwd(), defaultFile="", wildcard=_("YouMoney Database (*.db)|*.db"), style=wx.SAVE, ) dlg.SetFilterIndex(2) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() logfile.info("save file:", path) if not path.endswith(".db"): path += ".db" if os.path.isfile(path): wx.MessageBox(_("File exist"), _("Can not save account file"), wx.OK | wx.ICON_INFORMATION) return try: shutil.copyfile(self.conf["lastdb"], path) except Exception, e: wx.MessageBox( _("Save account failture:") + str(e), _("Can not save account file"), wx.OK | wx.ICON_INFORMATION ) return
def cateedit_dialog(self, ready): cates = copy.deepcopy(self.category.catelist_parent()) cates[_('Income')].insert(0, _('No Higher Category')) cates[_('Payout')].insert(0, _('No Higher Category')) ready['cates'] = cates if not ready['upcate']: ready['upcate'] = _('No Higher Category') dlg = dialogs.CategoryDialog(self, ready) dlg.CenterOnScreen() if dlg.ShowModal() == wx.ID_OK: item = dlg.values() logfile.info('cateedit:', item) dbx = datamodel.CategoryData(self.db) if item['mode'] == 'insert': try: dbx.insert_item(item) except Exception, e: wx.MessageBox(_('Add category failture:') + str(e), _('Add category information'), wx.OK|wx.ICON_INFORMATION) else: self.reload() elif item['mode'] == 'update': try: dbx.update_item(item) except Exception, e: wx.MessageBox(_('Change category failture:') + str(e), _('Change category information'), wx.OK|wx.ICON_INFORMATION) else: self.reload()
def OnCategoryDel(self, event): data = self.tree.GetPyData(self.currentItem) if not data or data['id'] <= 0: logfile.info("category data invalid.") return #frame = self.parent.parent ret = self.dbx.get(data['id']) if not ret: logfile.info('not found del category:', data['id']) return mytype = ret[0]['type'] name = ret[0]['name'] if name == _('No Category'): dlg = wx.MessageDialog(self, _('Can not delete this category!'), _('Notice:'),wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() return else: dlg = wx.MessageDialog(self, _('To delete category') + '"' + name + '"' \ + _(', all child categories will move to "No Category"'), _('Notice:'),wx.OK | wx.ICON_INFORMATION | wx.CANCEL) if dlg.ShowModal() == wx.ID_OK: try: self.dbx.delete(mytype, data['id']) except Exception, e: wx.MessageBox(_('Delete category failure!') + str(e), _('Delete category information'), wx.OK|wx.ICON_INFORMATION) self.frame.reload() dlg.Destroy()
def load(self): self.list.ClearAll() self.init() sql = "select * from recycle order by id" logfile.info(sql) rets = self.parent.parent.db.query(sql) if rets: for row in rets: try: cate = self.parent.parent.category.catemap(row['type'], row['category']) typestr = storage.catetypes[row['type']] except: sql = "delete from recycle where id=" + str(row['id']) self.parent.parent.db.execute(sql) continue item = self.list.InsertStringItem(0, typestr) #self.list.SetStringItem(item, 0, storage.catetypes[row['type']]) self.list.SetStringItem(item, 1, cate) self.list.SetStringItem(item, 2, str(row['num'])) self.list.SetStringItem(item, 3, storage.payways[row['payway']]) self.list.SetStringItem(item, 4, storage.cycles[row['addtime']]) self.list.SetStringItem(item, 5, row['explain']) self.list.SetItemData(item, row['id'])
def OnCheckItem(self, index, flag): data = self.GetItemData(index) #title = musicdata[data][1] if flag: what = "checked" else: what = "unchecked" logfile.info('click at index %d was %s\n' % (index, what))
def insert(self, typeint, parent, cate): sql = "insert into category (name,parent,type) values (?,?,?)" logfile.info('insert category:', sql) self.db.execute_param(sql, ( cate, parent, typeint, ))
def check(frame): try: up = Update() ver = up.update() if ver: evt = event.UpdateNotifyEvent(version=ver) wx.PostEvent(frame, evt) except Exception, e: logfile.info(e)
def __init__(self, parent, readydata): if readydata['mode'] == 'insert': title = _('Add income item') else: title = _('Edit income item') MySizedDialog.__init__(self, None, -1, title, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.parent = parent self.data = readydata panel = self.GetContentsPane() panel.SetSizerType("form") wx.StaticText(panel, -1, _('Date:')) #self.date = wx.DatePickerCtrl(panel, size=(120, -1), style=wx.DP_DROPDOWN| # wx.DP_SHOWCENTURY|wx.DP_ALLOWNONE) logfile.info('year:', readydata['year'], ' month:', readydata['month']) tm = wx.DateTime() tm.Set(readydata['day'], readydata['month'] - 1, readydata['year']) self.date = wx.GenericDatePickerCtrl( panel, dt=tm, size=(120, -1), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY | wx.DP_ALLOWNONE) wx.StaticText(panel, -1, _('Category:')) items = readydata['cates'] self.cate = wx.ComboBox(panel, -1, readydata['cate'], (90, 50), (160, -1), items, wx.CB_DROPDOWN | wx.CB_READONLY) wx.StaticText(panel, -1, _('Money:')) self.num = wx.TextCtrl(panel, -1, str(readydata['num']), size=(125, -1)) wx.StaticText(panel, -1, _('Explain:')) self.explain = wx.TextCtrl(panel, -1, readydata['explain'], size=(220, 100), style=wx.TE_MULTILINE) wx.StaticText(panel, -1, '') self.reuse = wx.CheckBox(panel, -1, _("Not close dialog, continue.")) self.SetButtonSizer(self.CreateStdDialogButtonSizer(wx.OK | wx.CANCEL)) self.SetMinSize(wx.Size(300, 250)) self.Fit()
def cycle_dialog(self, ready): dlg = dialogs.CycleDialog(self, ready) #dlg.CenterOnParent() while dlg.ShowModal() == wx.ID_OK: data = dlg.values() logfile.info('cycle dialog:', data) cate = data['cate'].split('->')[-1] if data['mode'] == 'insert': sql = "insert into recycle (category,num,ctime,payway,type,addtime,explain) values (?,?,?,?,?,?,?)" try: typeid = catetypes[data['type']] if data['type'] == _('Payout'): #cateid = self.category.payout_catemap[cate] cateid = self.category.payout_catemap[data['cate']] else: #cateid = self.category.income_catemap[cate] cateid = self.category.income_catemap[data['cate']] tnow = int(time.time()) num = float(data['num']) payway = payways[data['pay']] addtime = cycles[data['addtime']] logfile.info('insert cycle:', sql) self.db.execute_param(sql, (cateid, num, tnow, payway, typeid, addtime, data['explain'],)) except Exception, e: wx.MessageBox(_('Add cycle failture:') + str(e), _('Add cycle information'), wx.OK|wx.ICON_INFORMATION) logfile.info('insert cycle error:', traceback.format_exc()) else: cid = self.db.last_insert_id() rc = recycle.RecordCycle(self.db) rc.cycle(cid) rc = None self.reload() dlg.ClearForReinput() elif data['mode'] == 'update': sql = "update recycle set category=?,num=?,payway=?,type=?,addtime=?,explain=? where id=?" try: typeid = catetypes[data['type']] if data['type'] == _('Payout'): #cateid = self.category.payout_catemap[cate] cateid = self.category.payout_catemap[data['cate']] else: #cateid = self.category.income_catemap[cate] cateid = self.category.income_catemap[data['cate']] num = float(data['num']) payway = payways[data['pay']] addtime = cycles[data['addtime']] logfile.info('update cycle:', sql) self.db.execute_param(sql, (cateid, num, payway, typeid, addtime, data['explain'], data['id'],)) except Exception, e: wx.MessageBox(_('Change cycle failture:') + str(e), _('Change cycle information'), wx.OK|wx.ICON_INFORMATION) logfile.info('update error:', traceback.format_exc())
def update(self, cid, typeint, parent, cate): sql = "update category set name=?,parent=?,type=? where id=?" logfile.info('update category:', sql) self.db.execute_param(sql, ( cate, parent, typeint, cid, ))
def income_dialog(self, ready): dlg = dialogs.IncomeDialog(self, ready) dlg.CenterOnScreen() while dlg.ShowModal() == wx.ID_OK: data = dlg.values() logfile.info("income dialog:", data) # sql = "insert into capital (category,num,ctime,year,month,day,payway,explain,type) values (%d,%f,%d,%d,%d,%d,%d,'%s',1)" sql = ( "insert into capital (category,num,ctime,year,month,day,payway,explain,type) values (?,?,?,?,?,?,?,?,1)" ) cate = data["cate"].split("->")[-1] if data["mode"] == "insert": try: # cateid = self.category.income_catemap[cate] cateid = self.category.income_catemap[data["cate"]] tnow = int(time.time()) num = float(data["num"]) # payway = payways[data['pay']] payway = 0 year = data["date"].GetYear() month = data["date"].GetMonth() + 1 day = data["date"].GetDay() # sql = sql % (cateid, num, tnow, year, month, day, payway, data['explain']) logfile.info("insert capital:", sql) self.db.execute_param(sql, (cateid, num, tnow, year, month, day, payway, data["explain"])) except Exception, e: wx.MessageBox( _("Add income failture:") + str(e), _("Add income information"), wx.OK | wx.ICON_INFORMATION ) logfile.info("insert income error:", traceback.format_exc()) else: self.reload() dlg.ClearForReinput() elif data["mode"] == "update": # sql = "update capital set category=%d,num=%d,year=%d,month=%d,day=%d,explain='%s' where id=%d" sql = "update capital set category=?,num=?,year=?,month=?,day=?,explain=? where id=?" try: # cateid = self.category.income_catemap[cate] cateid = self.category.income_catemap[data["cate"]] num = float(data["num"]) year = data["date"].GetYear() month = data["date"].GetMonth() + 1 day = data["date"].GetDay() # sql = sql % (cateid, num, year, month, day, data['explain'], data['id']) logfile.info("update capital:", sql) self.db.execute_param(sql, (cateid, num, year, month, day, data["explain"], data["id"])) except Exception, e: wx.MessageBox( _("Change income failture:") + str(e), _("Change income information"), wx.OK | wx.ICON_INFORMATION, ) logfile.info("update error:", traceback.format_exc())
def table_diff_by_id(self, table, fields): logfile.info('table:', table) fieldslist = fields.split(',') newdb_lastid = 0 olddb_lastid = 0 length = 1000 sql = "select %s from %s order by id limit %d,%d" newset = set() oldset = set() while True: newsql = sql % (fields, table, newdb_lastid, length) oldsql = sql % (fields, table, olddb_lastid, length) newret = self.query(self.newdb, newsql) if newret: for row in newret: xs = [] for i in range(0, len(row)): f = row[i] if type(f) == types.UnicodeType: f = f.encode('utf-8') xs.append(str(f)) newset.add(self.fsep.join(xs)) newdb_lastid = newret[-1][0] oldret = self.query(self.olddb, oldsql) if oldret: for row in oldret: xs = [] for i in range(0, len(row)): f = row[i] if type(f) == types.UnicodeType: f = f.encode('utf-8') xs.append(str(f)) oldset.add(self.fsep.join(xs)) olddb_lastid = oldret[-1][0] if not newret and not oldret: break #logfile.info('new:', len(newset), 'old:', len(oldset)) newdiff = newset.difference(oldset) #logfile.info('newdiff:', newdiff) olddiff = oldset.difference(newset) #logfile.info('olddiff:', olddiff) newset = newdiff oldset = olddiff #logfile.info('new:', newset, 'old:', oldset) return newdiff, olddiff
def query(self): req = {'act':'query', 'id':self.conf['id'], 'ver':self.conf['sync_ver'], 'md5':self.md5val} header, data = self.reqconn.docmd(req) logfile.info('query resp:', header, data) self.status = header['status'] return header
def main(): home = os.path.dirname(os.path.abspath(sys.argv[0])) filename = os.path.join(home, "update.log") logfile.install(filename) try: up = Update() up.update() except Exception, e: logfile.info(e)
def update_income(self, data): sql = "update capital set category=?,num=?,year=?,month=?,day=?,explain=? where id=?" cateid = category.income_catemap[data['cate']] num = float(data['num']) year = data['date'].GetYear() month = data['date'].GetMonth() + 1 day = data['date'].GetDay() #sql = sql % (cateid, num, year, month, day, data['explain'], data['id']) logfile.info('update capital:', sql) self.db.execute_param(sql, (cateid, num, year, month, day, data['explain'], data['id'],))
def OnChangePassword(self, event): if not self.conf['user']: wx.MessageBox( _('Not found user setting, please login or registe first.'), _('Information'), wx.OK | wx.ICON_INFORMATION) return dlg = UserPassDialog(self, self.conf, 'modify') dlg.CenterOnScreen() while True: ret = dlg.ShowModal() if ret != wx.ID_OK: return vals = dlg.values() if vals['password1'] != vals['password2']: dlg.set_warn(_('Different password.')) continue #url = 'http://%s/sync?action=usermodify&ident=%s&user=%s&pass=%s&newpass=%s' % \ # (self.conf['server'], self.conf['id'], urllib.quote(vals['username']), # urllib.quote(vals['oldpass']), urllib.quote(vals['password1'])) req = { 'act': 'modifyuser', 'id': self.conf['id'], 'username': vals['username'], 'password': vals['password1'], 'oldpass': vals['oldpass'] } try: reqconn = netreq.Request() header, data = reqconn.docmd(req) except Exception, e: wx.MessageBox(str(e), _('Error'), wx.OK | wx.ICON_INFORMATION) continue val = json.loads(data) #errstr = val.get('error') if val['ret'] != 1: logfile.info(errstr) dlg.set_warn(self.errors[val['status']]) continue wx.MessageBox(_('Password successfully changed!'), _('Success'), wx.OK | wx.ICON_INFORMATION) self.conf['user'] = vals['username'] self.conf['password'] = vals['password1'] self.conf.dump() self.username.SetValue(vals['username']) self.password.SetValue(vals['password']) break
def __init__(self, window, ntsDict, dirRev): threading.Thread.__init__(self) self.window = window self.timeToQuit = threading.Event() self.timeToQuit.clear() # bufferDict used to store StaticText handler global bufferList, bufferDict bufferList = window bufferDict = ntsDict global dirRevFile dirRevFile = dirRev logfile.info("--- dirrevfile directory is %s ---" % dirRevFile)
def query(self): req = { 'act': 'query', 'id': self.conf['id'], 'ver': self.conf['sync_ver'], 'md5': self.md5val } header, data = self.reqconn.docmd(req) logfile.info('query resp:', header, data) self.status = header['status'] return header
def __init__(self, timeout=15): self.timeout = timeout self.addr = config.cf['server'].split(':') self.addr[0] = str(self.addr[0]) if len(self.addr) == 1: self.addr.append(9900) else: self.addr[1] = int(self.addr[1]) self.addr = tuple(self.addr) logfile.info('req addr:', self.addr) self.conn = None self.connect()
def OnFileExportData(self, event): dlg = wx.FileDialog( self, message=_("Export Data"), defaultDir=os.getcwd(), defaultFile="", wildcard=_("csv file (*.csv)|*.csv"), style=wx.SAVE) dlg.SetFilterIndex(2) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() exp = export.DataExport(self.db, 'gbk') try: exp.itemdata(path) except Exception, e: logfile.info(traceback.format_exc()) wx.MessageBox(str(e), _('Export Error:'), wx.OK|wx.ICON_INFORMATION)
def docmd(self, x, data=None, trycount=2): while trycount > 0: try: self.send(x, data) except: logfile.info(traceback.format_exc()) self.conn.close() self.connect() trycount -= 1 continue break return self.recv()
def __init__(self, selfUIFrame): threading.Thread.__init__(self) global bufferList, bufferDict,dirRevFile,mainFrame mainFrame = selfUIFrame self.window = mainFrame.conPan self.timeToQuit = threading.Event() self.timeToQuit.clear() # bufferDict used to store StaticText handler bufferDict = mainFrame.ntsDict bufferList = self.window dirRevFile = mainFrame.dirRec logfile.info("--- dirrevfile directory is %s ---" % dirRevFile)
def insert_income(self, data): sql = "insert into capital (category,num,ctime,year,month,day,payway,explain,type) values (?,?,?,?,?,?,?,?,1)" #cate = data['cate'].split('->')[-1] cateid = category.income_catemap[data['cate']] tnow = int(time.time()) num = float(data['num']) payway = 0 year = data['date'].GetYear() month = data['date'].GetMonth() + 1 day = data['date'].GetDay() logfile.info('insert capital:', sql) self.db.execute_param(sql, (cateid, num, tnow, year, month, day, payway, data['explain'],))
def initcate(self): sql = "select count(*) from category" count = self.db.query_one(sql) #print 'count:', count, 'iscreate:', config.cf.iscreate, 'lang:', config.cf['lang'] if count == 0 and config.cf.iscreate and config.cf['lang'] == 'zh_CN': path = os.path.join(self.rundir, 'data', 'category.csv') if not os.path.isfile(path): return exp = export.DataImport(self.db, 'gbk') try: exp.category(path) except: logfile.info(traceback.format_exc()) self.reload()
def initcate(self): sql = "select count(*) from category" count = self.db.query_one(sql) # print 'count:', count, 'iscreate:', config.cf.iscreate, 'lang:', config.cf['lang'] if count == 0 and config.cf.iscreate and config.cf["lang"] == "zh_CN": path = os.path.join(self.rundir, "data", "category.csv") if not os.path.isfile(path): return exp = export.DataImport(self.db, "gbk") try: exp.category(path) except: logfile.info(traceback.format_exc()) self.reload()
def query(self): url = self.user_url % ('query', self.conf['user'], self.conf['password']) resp = urllib2.urlopen(url) data = resp.read() logfile.info('query resp:', data) x = json.loads(data) if x.has_key('error'): return 0, x if self.conf['sync_way'] == 'user' and self.conf['id'] != x['id']: logfile.info('sync_way: user, local id:', self.conf['id'], 'remote id:', x['id']) self.conf['id'] = x['id'] self.conf.dump() #logfile.info(self.get_conf()) self.status = self.ADD return self.status, x #if self.conf['sync_way'] == 'user' and not x['haveconf']: # self.upload_conf() # return x is last version information if x['ver'] == 0 and not x.has_key('error'): self.status = self.ADD return self.status, x # get local sync_ver if len(self.conf['sync_ver']) > 0: localver = int(self.conf['sync_ver']) else: # not have local sync_ver logfile.info('not found local sync_ver, remote:', x['ver']) if x['ver'] > 0: # remove have sync_ver, update self.status = self.UPDATE return self.status, x else: # remote and local both not have sync_ver, ADD self.status = self.ADD return self.status, x if x['ver'] == localver: # the same version logfile.info('check md5, local db: ', self.md5val, 'remote:', x['md5']) if x['md5'] == self.md5val: # the same md5, not update self.status = self.NOUPDATE else: # modified, commit self.status = self.COMMIT elif x['ver'] > localver: # remote version is newer than local #if x['modify']: #if self.conf['sync_md5'] != self.md5val: # local modified if x['modify']: # user modified on old data, conflict self.status = self.CONFLICT else: # update self.status = self.UPDATE else: self.status = self.ERROR return self.status, x
def run(self): ## get local ip ipList = socket.gethostbyname_ex(socket.gethostname()) for i in ipList: logfile.info("--- all ips are %s ---" % i) iplocal = socket.gethostbyname(socket.gethostname()) logfile.info("--- iplocal is %s --- " % iplocal) #host = iplocal host = '192.168.0.10' port = 9999 addr = (host, port) #tcpStHandler = TCPStreamHandlerr(self.window[0]) try: self.server = Server(addr, TCPStreamHandlerr) logfile.info("--- start to run network serering ---") curtime = time.strftime("%Y-%m-%d-%H:%M:%S") printLog(curtime+":"+u"本机ip("+ host + u")等待客户机连接..\n") self.server.serve_forever() except: logfile.info("--- bind 192.168.0.10 failed ---") curtime = time.strftime("%Y-%m-%d-%H:%M:%S") printLog(curtime+":"+u" 本地ip地址绑定失败,请检查网络连接,然后重启本程序\n")
def OnCloseWindow(self, event): # if self.conf['sync_way'] == 'user': # sync.synchronization(self) task.taskq.put(None) logfile.info("task thread end") vi = sys.version_info if vi[0] == 2 and vi[1] >= 6: task.server.shutdown() else: task.server.server_close() logfile.info("server thread end") self.Destroy() sys.exit()
def OnCloseWindow(self, event): #if self.conf['sync_way'] == 'user': # sync.synchronization(self) task.taskq.put(None) logfile.info('task thread end') vi = sys.version_info if vi[0] == 2 and vi[1] >= 6: task.server.shutdown() else: task.server.server_close() logfile.info('server thread end') self.Destroy() sys.exit()
def initcate(self): dbx = datamodel.CategoryData(self.db) count = dbx.count() #print 'count:', count, 'iscreate:', config.cf.iscreate, 'lang:', config.cf['lang'] if count == 0 and config.cf.iscreate and config.cf['lang'] == 'zh_CN': path = os.path.join(self.rundir, 'data', 'category.csv') if not os.path.isfile(path): return exp = export.DataImport(self.db, 'gbk') try: exp.category(path) except: logfile.info(traceback.format_exc()) self.reload()
def update_payout(self, data): sql = "update capital set category=?,num=?,year=?,month=?,day=?,payway=?,explain=? where id=?" #cateid = self.category.payout_catemap[cate] cateid = category.payout_catemap[data['cate']] num = float(data['num']) payway = storage.payways[data['pay']] year = data['date'].GetYear() month = data['date'].GetMonth() + 1 day = data['date'].GetDay() #sql = sql % (cateid, num, year, month, day, payway, data['explain'], data['id']) logfile.info('update capital:', sql) self.db.execute_param(sql, (cateid, num, year, month, day, payway, data['explain'], data['id'],))
def Dis_WriteRecord(fd_out): """ write one record to file from dict_frm""" # compare every time, select the min time, here exist eight time # 1. conver time to seconds startTime = 23*3600 + 59*60 + 59 indexTime = 'pumpInd_0' for i in range(pumpNum): pump_index="pumpInd_%d" % i tmpTime = dict_frm[pump_index]['start_h'] * 3600 + dict_frm[pump_index]['start_m'] * 60 + dict_frm[pump_index]['start_s'] if tmpTime != 0 and tmpTime < startTime: startTime = tmpTime indexTime = pump_index if startTime == 23*3600 + 59*60 + 59: logfile.info("--- this record is invalid because time = 0 ---") if dict_frm[indexTime]['start_h'] < 10: time_h = "0%d" % dict_frm[indexTime]['start_h'] else: time_h = "%d" % dict_frm[indexTime]['start_h'] if dict_frm[indexTime]['start_m'] < 10: time_m = "0%d" % dict_frm[indexTime]['start_m'] else: time_m = "%d" % dict_frm[indexTime]['start_m'] if dict_frm[indexTime]['start_s'] < 10: time_s = "0%d" % dict_frm[indexTime]['start_s'] else: time_s = "%d" % dict_frm[indexTime]['start_s'] vol_str = "%d, %d, %d, %d, %d, %d, %d, %d" %(dict_frm['pumpInd_0']['vol'], dict_frm['pumpInd_1']['vol'], dict_frm['pumpInd_2']['vol'], dict_frm['pumpInd_3']['vol'], \ dict_frm['pumpInd_4']['vol'], dict_frm['pumpInd_5']['vol'], dict_frm['pumpInd_6']['vol'], dict_frm['pumpInd_7']['vol']) # recalcuate time """ diff_time = [ 0 for x in range(8)] for i in range(pumpNum): pump_index="pumpInd_%d" % i diff_time[i] = (dict_frm[pump_index]['end_h'] - dict_frm[pump_index]['start_h'] ) * 3600 + \ (dict_frm[pump_index]['end_m'] - dict_frm[pump_index]['start_m'] ) * 60 + \ (dict_frm[pump_index]['end_s'] - dict_frm[pump_index]['start_s'] ) """ valueline = "%d, %d, %s:%s:%s, %d, %d, %d, %d, %d, %d, %d, %d,%d, %d, %d, %d, %d, %d, %d, %d, %d \n" \ %(dict_frm['devid'],dict_frm['type'], time_h,time_m,time_s, \ dict_frm['pumpInd_0']['wash_type'], dict_frm['pumpInd_0']['vol'],dict_frm['pumpInd_1']['wash_type'],dict_frm['pumpInd_1']['vol'],\ dict_frm['pumpInd_2']['wash_type'], dict_frm['pumpInd_2']['vol'],dict_frm['pumpInd_3']['wash_type'],dict_frm['pumpInd_3']['vol'],\ dict_frm['pumpInd_4']['wash_type'], dict_frm['pumpInd_4']['vol'],dict_frm['pumpInd_5']['wash_type'],dict_frm['pumpInd_5']['vol'],\ dict_frm['pumpInd_6']['wash_type'], dict_frm['pumpInd_6']['vol'],dict_frm['pumpInd_7']['wash_type'],dict_frm['pumpInd_7']['vol'],\ dict_frm['wash_cnt']) fd_out.write(valueline)
def payout_dialog(self, ready): dlg = dialogs.PayoutDialog(self, ready) dlg.CenterOnScreen() while dlg.ShowModal() == wx.ID_OK: data = dlg.values() logfile.info('payout dialog:', data) cate = data['cate'].split('->')[-1] if data['mode'] == 'insert': #sql = "insert into capital (category,num,ctime,year,month,day,payway,explain,type) values (%d,%f,%d,%d,%d,%d,%d,'%s',0)" sql = "insert into capital (category,num,ctime,year,month,day,payway,explain,type) values (?,?,?,?,?,?,?,?,0)" try: #cateid = self.category.payout_catemap[cate] cateid = self.category.payout_catemap[data['cate']] tnow = int(time.time()) num = float(data['num']) payway = payways[data['pay']] year = data['date'].GetYear() month = data['date'].GetMonth() + 1 day = data['date'].GetDay() #sql = sql % (cateid, num, tnow, year, month, day, payway, data['explain']) logfile.info('insert capital payout:', sql) self.db.execute_param(sql, (cateid, num, tnow, year, month, day, payway, data['explain'],)) except Exception, e: wx.MessageBox(_('Add payout failture:') + str(e), _('Add payout information'), wx.OK|wx.ICON_INFORMATION) logfile.info('insert payout error:', traceback.format_exc()) else: self.reload() dlg.ClearForReinput() elif data['mode'] == 'update': #sql = "update capital set category=%d,num=%d,year=%d,month=%d,day=%d,payway=%d,explain='%s' where id=%d" sql = "update capital set category=?,num=?,year=?,month=?,day=?,payway=?,explain=? where id=?" try: #cateid = self.category.payout_catemap[cate] cateid = self.category.payout_catemap[data['cate']] num = float(data['num']) payway = payways[data['pay']] year = data['date'].GetYear() month = data['date'].GetMonth() + 1 day = data['date'].GetDay() #sql = sql % (cateid, num, year, month, day, payway, data['explain'], data['id']) logfile.info('update capital:', sql) self.db.execute_param(sql, (cateid, num, year, month, day, payway, data['explain'], data['id'],)) except Exception, e: wx.MessageBox(_('Change payout failture:') + str(e), _('Change payout information'), wx.OK|wx.ICON_INFORMATION) logfile.info('update error:', traceback.format_exc())