def update_name_and_description(self, document_id: int, name: str, description: str): if not name: raise ServerException(ServerErrors.file_name_cannot_be_empty) # file_name_cannot_be_empty # raise Exception("Name cannot be empty") mainlog.debug('Renaming doc:{} to:{} with description:{}'.format( document_id, name, description)) try: self._rename_file_in_storage(document_id, name) except Exception as ex: mainlog.error("Could not rename document {}".format(document_id)) mainlog.exception(ex) doc = session().query(Document).filter( Document.document_id == document_id).one() doc.description = description or "" doc.filename = name audit_trail_service.record("DOCUMENT_RENAMED", "", document_id, commit=False) session().commit()
def __call__(self, *args, **kwargs): global mainlog global session # FIXME That's not right : how can we be sure that's the actual session that has thrown the exception ? try: r = self.call_decorated(*args, **kwargs) # mainlog.debug("RollbackDecorator.__call__ calling with args : {} kwargs :{}".format(args, kwargs)) # r = super(RollbackDecorator,self).__call__(*args,**kwargs) # mainlog.debug("RollbackDecorator.__call__ call complete") return r # if self.instance: # return self.func(self.instance,*args,**kwargs) # else: # return self.func(*args) except Exception as e: session().rollback() if type(e) != DataException: # I assume DataException are handled properly mainlog.info("Rollback done because of an exception") mainlog.exception(str(e)) log_stacktrace() if RollbackDecorator.callback_operational_error is not None and isinstance( e, OperationalError): f = RollbackDecorator.callback_operational_error[0] f(e) raise e
def parse(self, s): """ Parse a date time stamp like ''28/2/2009 23:59:59''. The time part is optional. Returns ''False'' if the parsing is not successful. """ # mainlog.debug("Parsing {}".format(s)) if not s: return False date_scan = self._date_re.search(s) if date_scan and date_scan.groups(): # mainlog.debug("Time scan on |{}|".format(s[date_scan.end():len(s)])) time_scan = self._time_re.search(s[date_scan.end():len(s)]) # mainlog.debug("date_scan {}".format(date_scan.groups())) # if time_scan: mainlog.debug("time_scan {}".format(time_scan.groups())) if time_scan and time_scan.groups(): t = time_scan.groups() if len(t) < 3: t = t + [0] * (3 - len(t)) elif s[date_scan.end():len(s)].strip() == '': t = [0, 0, 0] else: # mainlog.debug("parse failed") return False try: d = date_scan.groups() #mainlog.debug("parse groups : {}".format(d)) d = [(dc or 0) for dc in d] t = [(tc or 0) for tc in t] # mainlog.debug(d) # mainlog.debug(t) return datetime(year=int(d[2]), month=int(d[1]), day=int(d[0]), hour=int(t[0]), minute=int(t[1]), second=int(t[2])) except ValueError as e: mainlog.debug("parse groups failed") mainlog.exception(e) return False else: # mainlog.debug("date scan parse failed") return False
def clear_caches(self): self._turnover_computation_cache = dict() for attr_name in dir(self): if "chart" in attr_name: a = getattr(self, attr_name) # We assume the function is decorated and has the clear_cache # method ! try: a.clear_cache() except Exception as ex: mainlog.error( "Error while refreshing {}".format(attr_name)) mainlog.exception(ex)
def makeErrorBox(text,info_text = None,ex=None): mainlog.warning("makeErrorBox : {}".format(text)) errorBox = QMessageBox() errorBox.setObjectName("error_box") errorBox.setWindowTitle(_("Error !")) errorBox.setIcon(QMessageBox.Critical) t = info_text if ex: nfo = "" if info_text: nfo = info_text + u'\n' t = u"{}{}\n{}".format(nfo,_("Additional information :"), str(ex)) _setBoxTexts(errorBox,text,t) errorBox.setStandardButtons(QMessageBox.Ok) if ex: log_stacktrace() mainlog.exception(ex) return errorBox
def accept(self): try: try: slip_id = int(self.slip_number.text()) except ValueError as e: makeErrorBox( _("The delivery slip number {} is not valid").format( self.slip_number.text())).exec_() return if self.dao.delivery_slip_part_dao.id_exists(slip_id): print_delivery_slip(self.dao, slip_id) else: makeErrorBox( _("The delivery slip {} doesn't exist").format( slip_id)).exec_() return except Exception as e: mainlog.exception(e) msgBox = makeErrorBox(_("Something wrong happened while printing")) msgBox.exec_() return super(ReprintDeliverySlipDialog, self).accept()
def drop_functions(current_session): try: current_session.connection().execute( "SET search_path TO {}".format("horse")) except Exception as ex: # Schema's not there, so nothing to delete mainlog.exception(ex) return current_session.connection().execute("BEGIN") try: # current_session.connection().execute("DROP TRIGGER IF EXISTS control_orders_accounting ON orders") # current_session.connection().execute("DROP TRIGGER IF EXISTS control_orders_accounting2 ON orders") # current_session.connection().execute("DROP TRIGGER IF EXISTS control_orders_accounting3 ON orders") current_session.connection().execute( "DROP TRIGGER IF EXISTS control_orders_accounting_delete ON {}.orders" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP TRIGGER IF EXISTS control_orders_accounting_update ON {}.orders" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP TRIGGER IF EXISTS control_orders_accounting_insert ON {}.orders" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP TRIGGER IF EXISTS control_delivery_slips_delete ON {}.delivery_slip" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP TRIGGER IF EXISTS control_delivery_slips_update ON {}.delivery_slip" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP TRIGGER IF EXISTS control_delivery_slips_insert ON {}.delivery_slip" .format(DATABASE_SCHEMA)) current_session.connection().execute("COMMIT") except: current_session.connection().execute("ROLLBACK") schema_name = "horse" current_session.connection().execute("BEGIN") current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.check_orders_gapless_sequence()".format( DATABASE_SCHEMA)) current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.check_orders_gapless_sequence_insert()". format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.check_orders_gapless_sequence_delete()". format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.check_orders_gapless_sequence_update()". format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.check_delivery_slips_gapless_sequence_insert()" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.check_delivery_slips_gapless_sequence_delete()" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.check_delivery_slips_gapless_sequence_update()" .format(DATABASE_SCHEMA)) current_session.connection().execute( "DROP FUNCTION IF EXISTS {0}.gseq_nextval(t text)".format( DATABASE_SCHEMA)) current_session.connection().execute("COMMIT") mainlog.info("Dropped all functions")
def upgrade_process(args): if platform.system() != 'Windows': mainlog.info( "The upgrade process won't work on something else than Windows... I skip that." ) return this_version = configuration.this_version # the one of this very code mainlog.debug("Client version is {}".format(this_version)) if args.no_update: mainlog.info("Skipping update process because --no-update is set") # This is rather strange. If we are started by regular Windows ways # (double click, cmd,...) PySide finds its DLL fine. # But, if it is started through the upgrade process (via Popen), then # it doesn't because Windows can't expand junction points correctly # (according to what I saw, this is not a bug in windows, but rather a # feature to prevent old code to misuse junction points) # So, for this code to work, one has to make sure that _setupQtDir # is not called during the import but right after (else it crashes). # This is how to patch the __init__py of PySide : # def _setupQtDirectories(zedir=None): # import sys # import os # from . import _utils # # if zedir: # pysideDir = zedir # else: # pysideDir = _utils.get_pyside_dir() # try: from PySide import _setupQtDirectories except Exception as ex: mainlog.error( "Unable to import _setupQtDirectories. Remember this was a bug fix, make sure " + "_setupQtDirectories is not called at the end of the __init__.py of pyside. " + "Check the comments in the code for more info.") mainlog.exception(ex) return if getattr(sys, 'frozen', False): # Frozen mainlog.debug("Fixing Qt import on frozen exe {}".format( os.path.normpath(os.getcwd()))) _setupQtDirectories(os.path.normpath(os.getcwd())) else: mainlog.debug("Fixed Qt import on NON frozen exe") _setupQtDirectories() return next_version = get_server_version( configuration.update_url_version ) # available on the server (abd maybe already downloaded) current_version = find_highest_installed_version( ) # one we have downloaded in the past mainlog.info( "This version is {}, last downloaded version = {}, version available on server = {}" .format(this_version, current_version, next_version)) if (not current_version or (current_version and this_version >= current_version)) and \ (not next_version or (next_version and this_version >= next_version)): mainlog.info( "The available versions are not more recent than the current one. No update necessary." ) return codename = configuration.get("Globals", "codename") # Update only if we have no current version or if the # next version is higher than ours if next_version and (not current_version or next_version > current_version): try: tmpfile = make_temp_file(prefix='NewVersion_' + version_to_str(next_version), extension='.zip') download_file(configuration.update_url_file, tmpfile) newdir = os.path.join( get_data_dir(), "{}-{}".format(codename, version_to_str(next_version))) extractAll(tmpfile, newdir) # show that we actually downloaded something current_version = next_version except Exception as ex: mainlog.error( "The download of version {} failed. Therefore, I'll go on with the current one." .format(next_version)) mainlog.exception(ex) # If we were able to download a version now or in the # past, then use this one. If not, then we run the # program (that is, the version that was installed # by the user) if current_version: current_dir = os.path.join( get_data_dir(), "{}-{}".format(codename, version_to_str(current_version))) # --no-update "signals" the control transfer (without it we'd # try to update with the latest version again creating an # endless loop) # os.chdir(os.path.join(current_dir,codename)) # FIXME Not sure this is useful; too tired to test cmd = [ os.path.join(os.path.join(current_dir, codename), codename + '.exe'), '--no-update' ] mainlog.info("Transferring control to {}".format(' '.join(cmd))) # DETACHED_PROCESS = 0x00000008 # CREATE_NEW_PROCESS_GROUP = 0x00000200 # subprocess.Popen( cmd,cwd=os.path.join(current_dir,'xxx'),creationflags=DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP) # From what I can see WinExec don't run in os.getcwd(), so I give it an absolute path. try: # win32api.WinExec will *NOT* block. The new version is run # in parallel. This allow us to quit so we don't have two # instances of Koi running simulatenaously # Unfortunaately, because of that it's hard to build a watch # dog that will protect us against a broken upgrade. # For example, we'd have to release our log files... res = win32api.WinExec(" ".join(cmd), win32con.SW_SHOWMAXIMIZED) sys.exit(RETURN_CODE_SUCCESS) except Exception as ex: mainlog.error( "Control transfer failed. There was an error while starting the newer version {}" .format(current_version)) mainlog.exception(ex) return False