Exemplo n.º 1
0
 def execute(self, _sql, _args=None, **_kwargs):
     """Wrap the execute so that unhandled exceptions are handled."""
     if _args is None:
         _args = _kwargs
     try:
         if self.connection.logSql \
                 and cx_Logging.Debug("SQL\n%s", _sql or self.statement):
             if isinstance(_args, dict):
                 _output = [(k, v) for k, v in _args.items() \
                         if not k.endswith("_")]
                 _output.sort()
             else:
                 _output = enumerate(_args)
             _output = ["    %s => %r" % (n, v) for n, v in _output]
             if _output:
                 cx_Logging.Debug("BIND VARIABLES\n%s", "\n".join(_output))
         return cx_Oracle.Cursor.execute(self, _sql, _args)
     except:
         exc = self.connection.ExceptionHandler(*sys.exc_info())
         exc.details.append("SQL: %s" % _sql or self.statement)
         exc.details.append("Bind Variables:")
         if isinstance(_args, dict):
             _output = [(k, v) for k, v in _args.items() \
                     if not k.endswith("_")]
             _output.sort()
         else:
             _output = enumerate(_args)
         for name, value in _output:
             exc.details.append("  %s -> %r" % (name, value))
         raise exc
Exemplo n.º 2
0
 def UpdateRow(self, cache, externalRow, contextItem=None):
     row = self._FindRow(externalRow)
     if row is None:
         cx_Logging.Debug("%s: creating new row with source as %s",
                          self.name, externalRow)
         row = self.rowClass.New()
         self._CopyAttrs(row, externalRow, contextItem)
         self.OnLoadRow(cache, row)
         if not self.loadAllRowsOnFirstLoad:
             for path in self.paths:
                 if isinstance(path, MultipleRowPath):
                     key = path.GetKeyValue(row)
                     path.rows.setdefault(key, []).append(row)
         if self.allRowsLoaded:
             self.allRows.append(row)
     else:
         cx_Logging.Debug("%s: modifying row %s", self.name, row)
         beforeKeyValues = []
         for path in self.singleRowPaths:
             beforeKeyValues.append((path, path.GetKeyValue(row)))
         self._CopyAttrs(row, externalRow, contextItem)
         for path, beforeKeyValue in beforeKeyValues:
             afterKeyValue = path.GetKeyValue(row)
             if afterKeyValue != beforeKeyValue:
                 del path.rows[beforeKeyValue]
                 path.rows[afterKeyValue] = row
         method = getattr(self, self.setExtraAttrValuesMethodName, None)
         if method is not None:
             method(cache, row)
Exemplo n.º 3
0
def Run(threadNum):
    cx_Logging.Debug("Thread-%d: starting", threadNum)
    iterationsLeft = numIterations
    while iterationsLeft > 0:
        numFiles = len(os.listdir("."))
        cx_Logging.Debug("Thread-%d: counted %d files, %d iterations left",
                         threadNum, numFiles, iterationsLeft)
        iterationsLeft -= 1
Exemplo n.º 4
0
 def __exit__(self, excType, excValue, excTraceback):
     if excValue is None:
         cx_Logging.Debug("transaction succeeded, committing")
         self.dataSource.commit()
     else:
         cx_Logging.Debug("transaction failed, rolling back")
         self.dataSource.rollback()
         return super(TransactionContext,
                      self).__exit__(excType, excValue, excTraceback)
Exemplo n.º 5
0
 def __ShouldTrace(self, fileName):
     cx_Logging.Debug("should trace code from file %s?", fileName)
     fileName, ext = os.path.splitext(fileName)
     if os.path.isabs(fileName):
         for path in sys.path:
             if fileName.startswith(path + os.sep):
                 fileName = fileName[len(path) + 1:]
     moduleName = fileName.split(os.sep)[0]
     domain = self.traceManager.modules.get(moduleName)
     trace = (domain in self.domains)
     cx_Logging.Debug("  tracing for module %s is %s", moduleName, trace)
     return trace
Exemplo n.º 6
0
 def OnGenerateReceipts(self):
     with ceGUI.BusyCursorContext(self):
         cx_Logging.Debug("generating receipts for year %s",
                          self.config.year)
         yearRow = Models.Years.GetRow(self.config.dataSource,
                                       year=self.config.year)
         origReceiptDict = self.__GetOriginalReceipts()
         cx_Logging.Debug("%s original receipts", len(origReceiptDict))
         maxReceiptNum = self.__GetNextReceiptNum()
         cx_Logging.Debug("max receipt number is %s", maxReceiptNum)
         donatedAmounts = self.__GetDonatedAmounts()
         cx_Logging.Debug("%s donations to receipt", len(donatedAmounts))
         receiptsCanceled = receiptsUpdated = receiptsCreated = 0
         cursor = self.config.dataSource.connection.cursor()
         for donatorId, amount in donatedAmounts:
             origReceipt = origReceiptDict.get(donatorId)
             if origReceipt is not None and origReceipt.amount == amount:
                 continue
             if yearRow.receiptsIssued and origReceipt is not None:
                 receiptsCanceled += 1
                 cursor.execute(
                     """
                         update TaxReceipts set
                             Canceled = 't'
                         where ReceiptNumber = ?""",
                     origReceipt.receiptNumber)
             if not yearRow.receiptsIssued and origReceipt is not None:
                 receiptsUpdated += 1
                 cursor.execute(
                     """
                         update TaxReceipts set
                             Amount = ?
                         where ReceiptNumber = ?""", amount,
                     origReceipt.receiptNumber)
             else:
                 receiptsCreated += 1
                 maxReceiptNum += 1
                 cursor.execute(
                     """
                         insert into TaxReceipts
                         (ReceiptNumber, Year, DonatorId, Amount, Canceled,
                                 DateIssued, IsDuplicate)
                         values (?, ?, ?, ?, 'f', ?, 'f')""", maxReceiptNum,
                     yearRow.year, donatorId, amount, datetime.date.today())
         cursor.connection.commit()
     message = "%d canceled. %d updated. %d created." % \
             (receiptsCanceled, receiptsUpdated, receiptsCreated)
     wx.MessageBox(message, "Receipt Generation Results",
                   wx.OK | wx.ICON_INFORMATION, self)
     if receiptsCanceled or receiptsUpdated or receiptsCreated:
         self.config.GetCachedRows(self.dataSet.rowClass, refresh=True)
         self.Retrieve()
 def run(self):
     cx_Logging.Debug("stdout=%r", sys.stdout)
     sys.stdout = open(os.path.join(self.directory, "stdout.log"), "a")
     sys.stderr = open(os.path.join(self.directory, "stderr.log"), "a")
     app.run(host="0.0.0.0")
     self.stopRequestedEvent.wait()
     self.stopEvent.set()
Exemplo n.º 8
0
def ExecuteOSCommands(*commands):
    """Execute OS commands, raising an error if any return errors."""
    for command in commands:
        cx_Logging.Debug("executing command %s", command)
        exitCode = os.system(command)
        if exitCode != 0:
            raise CommandExecutionFailed(command=command, exitCode=exitCode)
Exemplo n.º 9
0
 def SetEnvironment(self):
     cx_Logging.Debug("setting environment for %s", self)
     os.environ["ORACLE_SID"] = self.sid
     os.environ["ORACLE_HOME"] = self.oracleHome
     self.__PrependPathEnvVar("PATH", self.binDir)
     if sys.platform != "win32":
         self.__PrependPathEnvVar("LD_LIBRARY_PATH", self.libDir)
Exemplo n.º 10
0
 def AddRow(self, cache, key1, key2):
     cx_Logging.Debug("%s: adding xref between %s and %s", self.name, key1,
                      key2)
     path1, path2 = self.paths
     if key1 in path1.rows:
         path1.rows[key1].append(key2)
     if key2 in path2.rows:
         path2.rows[key2].append(key1)
Exemplo n.º 11
0
 def RemoveRow(self, cache, key1, key2):
     cx_Logging.Debug("%s: removing xref between %s and %s", self.name,
                      key1, key2)
     path1, path2 = self.paths
     if key1 in path1.rows:
         path1.rows[key1].remove(key2)
     if key2 in path2.rows:
         path2.rows[key2].remove(key1)
Exemplo n.º 12
0
 def LoadAllRows(self, cache):
     if self.tracePathLoads:
         cx_Logging.Debug("%s: loading all rows", self.name)
     rows = self.GetAllRowsFromDataSource(cache)
     self.OnLoadRows(cache, rows)
     self.allRows = rows
     self.allRowsLoaded = True
     return self.allRows
Exemplo n.º 13
0
 def _GenerateMethod(cls, targetClass, methodName, methodLines, *args):
     actualArgs = ("self", ) + args
     codeString = "def %s(%s):\n    %s" % \
             (methodName, ", ".join(actualArgs), "\n    ".join(methodLines))
     cx_Logging.Debug("%s: GENERATED CODE\n%s", cls.name, codeString)
     code = compile(codeString, "SubCacheGeneratedCode.py", "exec")
     temp = {}
     exec(code, dict(), temp)
     setattr(targetClass, methodName, temp[methodName])
Exemplo n.º 14
0
 def executemany(self, _sql, _args):
     try:
         if self.connection.logSql \
                 and cx_Logging.Debug("SQL\n%s", _sql or self.statement):
             _output = ["    %s" % (r, ) for r in _args]
             cx_Logging.Debug("ROWS (%s):\n%s", len(_output),
                              "\n".join(_output))
         return cx_Oracle.Cursor.executemany(self, _sql, _args)
     except:
         exc = self.connection.ExceptionHandler(*sys.exc_info())
         exc.details.append("SQL: %s" % _sql or self.statement)
         if self.rowcount > -1 and self.rowcount < len(_args):
             exc.details.append("FAILED ROW: %s" % (_args[self.rowcount], ))
         exc.details.append("ROWS (%s, %s before error):" % \
                 (len(_args), self.rowcount))
         for row in _args:
             exc.details.append("    %s" % (row, ))
         raise exc
def Enable(connection, pipeName=None):
    """Enable debugging messages on the given pipe."""
    cursor = connection.cursor()
    if pipeName is None:
        pipeName = cursor.callfunc("dbms_pipe.unique_session_name",
                                   cx_Oracle.STRING)
    cursor.callproc("pkg_Debug.Enable", (pipeName, ))
    cx_Logging.Debug("logging messages to pipe %s", pipeName)
    return pipeName
def LogMessages(connection, pipeName):
    """Log messages using the cx_Logging module."""
    cx_Logging.Debug("logging messages from pipe %s", pipeName)
    debugConnection = cx_Oracle.Connection(connection.username,
                                           connection.password,
                                           connection.tnsentry,
                                           threaded=True)
    for message in MessageGenerator(debugConnection, pipeName):
        cx_Logging.Trace("%s", message)
Exemplo n.º 17
0
 def run(self):
     cx_Logging.Debug("stdout=%r", sys.stdout)
     sys.stdout = open(os.path.join(self.directory, "stdout.log"), "a")
     sys.stderr = open(os.path.join(self.directory, "stderr.log"), "a")
     #sys.stdout = open(os.path.join("C:\\Data\\logs\\", "stdout.log"), "a")
     #sys.stderr = open(os.path.join("C:\\Data\\logs\\", "stderr.log"), "a")
     app.run(host="127.0.0.1",port=5123)
     self.stopRequestedEvent.wait()
     self.stopEvent.set()
Exemplo n.º 18
0
 def SetValue(self, handle, attrName, value):
     row = self.rows[handle]
     origValue = getattr(row, attrName)
     if value != origValue:
         self.MarkAsChanged(handle)
         row = self.rows[handle]
         cx_Logging.Debug("setting attr %s on row %s to %r (from %r)",
                 attrName, handle, value, origValue)
         self._OnSetValue(row, attrName, value, origValue)
         setattr(row, attrName, value)
Exemplo n.º 19
0
 def GetValue(self, key, defaultValue=None):
     """Return a value from the database, returning the default value
        if a value cannot be found and destroying invalid values if
        any are found."""
     key = "%s.%s" % (self.baseName, key)
     try:
         value = self.database[key]
     except KeyError:
         cx_Logging.Debug("no value for key %s, default value is %s",
                          key, defaultValue)
         return defaultValue
     try:
         value = eval(value)
     except:
         del self.database[key]
         cx_Logging.Debug("bad value for key %s, default value is %s",
                          key, defaultValue)
         return defaultValue
     cx_Logging.Debug("value for key %s is %r", key, value)
     return value
Exemplo n.º 20
0
 def Update(self):
     if not self.PendingChanges():
         cx_Logging.Debug("no update to perform")
         return
     self._PreUpdate()
     transaction = self.dataSource.BeginTransaction()
     self._Update(transaction)
     self.dataSource.CommitTransaction(transaction)
     self._GetPrimaryKeyValues(transaction)
     self.ClearChanges()
     self._PostUpdate()
Exemplo n.º 21
0
 def GetValue(self, key, defaultValue=None):
     """Return a value from the registry, returning the default value
        if a value cannot be found and destroying invalid values if
        any are found."""
     try:
         value, type = win32api.RegQueryValueEx(self.key, key)
     except:
         cx_Logging.Debug(
             "Getting default for session key %s\\%s. Value=\"%s\"",
             self.baseName, key, defaultValue)
         return defaultValue
     try:
         returnValue = eval(str(value))
         cx_Logging.Debug("Getting session key %s\\%s. Value=\"%s\"",
                          self.baseName, key, returnValue)
         return returnValue
     except:
         win32api.RegDeleteValue(self.key, key)
         cx_Logging.Debug(
             "Getting default for session key %s\\%s. Value=\"%s\"",
             self.baseName, key, defaultValue)
         return defaultValue
Exemplo n.º 22
0
 def ExecuteForDatabase(self, database):
     cx_Logging.Debug("executing program for database %s", database)
     database.SetEnvironment()
     os.environ[ENV_NAME] = "Y"
     os.environ["START_MODE"] = database.startMode
     if sys.platform == "win32":
         executable = '"%s"' % sys.executable
     else:
         executable = sys.executable
     returnCode = os.spawnv(os.P_WAIT, sys.executable,
                            [executable] + sys.argv[1:])
     if returnCode != 0:
         sys.exit(1)
Exemplo n.º 23
0
 def Load(self, cache, pathName, *args):
     if self.tracePathLoads:
         cx_Logging.Debug("%s: loading rows by path %s with args %s",
                          self.name, pathName, args)
     path = self.pathsByName[pathName]
     actualArgs = []
     for attrName, value in zip(path.retrievalAttrNames, args):
         if isinstance(value, ceDatabase.Row):
             value = getattr(value, attrName)
         actualArgs.append(value)
     actualArgs = tuple(actualArgs)
     if self.loadAllRowsOnFirstLoad:
         if not self.allRowsLoaded:
             self.LoadAllRows(cache)
         return path.GetCachedValue(actualArgs)
     return path.Load(cache, self, *actualArgs)
Exemplo n.º 24
0
 def AddModule(self, module, domain = None):
     """Add a module to the list of modules to trace. If the domain is
        specified, then it will be added to the domain regardless of
        whether or not a domain is specified in the module itself; otherwise
        the module will be searched for the above domains and only added to
        the list if the correct attribute is specified."""
     if domain is None:
         domain = getattr(module, STATIC_DOMAIN_ATTR, None)
     if domain is not None:
         origDomain = self.modules.get(module.__name__)
         self.modules[module.__name__] = domain
         if origDomain is not None and domain != origDomain:
             cx_Logging.Warning("swapping domain for %s from %s to %s",
                     module.__name__, origDomain, domain)
         else:
             cx_Logging.Debug("adding %s to domain %s",
                     module.__name__, domain)
         dynamicDomains = getattr(module, DYNAMIC_DOMAIN_ATTR, [])
         for domain in dynamicDomains:
             self.dynamicDomains[domain] = None
from flask import Flask
from app import create_app
import os
import sys
import cx_Logging

app = create_app('default')

cx_Logging.Debug("stdout=%r", sys.stdout)
sys.stdout = open(os.path.join("C:\\Data\\logs\\", "stdout_console.log"), "a")
sys.stderr = open(os.path.join("C:\\Data\\logs\\", "stderr_console.log"), "a")
cx_Logging.StartLogging(os.path.join("C:\\Data\\logs\\", "teste_console.log"), cx_Logging.DEBUG)

if __name__ == "__main__":

    app.run(host="127.0.0.1",port=5123)
    
    
Exemplo n.º 26
0
 def run(self):
     cx_Logging.Debug('Starting kukur.exe')
     self.process = subprocess.Popen(['kukur.exe'], cwd=self.directory)
     self.process.wait()
     self.stopRequestedEvent.wait()
     self.stopEvent.set()
Exemplo n.º 27
0
 def stop(self):
     if self.process:
         cx_Logging.Debug('Stopping kukur.exe')
         self.process.kill()
     self.stopRequestedEvent.set()
     self.stopEvent.wait()
Exemplo n.º 28
0
 def RemoveRow(self, cache, externalRow):
     row = self._FindRow(externalRow, errorIfMissing=True)
     cx_Logging.Debug("%s: removing row %s", self.name, row)
     self.OnRemoveRow(cache, row)
     if self.allRowsLoaded:
         self.allRows.remove(row)
Exemplo n.º 29
0
 def SetValue(self, key, value):
     """Set the value in the database."""
     key = "%s.%s" % (self.baseName, key)
     self.database[key] = repr(value)
     cx_Logging.Debug("setting value for key %s to %r", key, value)
Exemplo n.º 30
0
 def SetValue(self, key, value):
     """Set the value in the registry."""
     cx_Logging.Debug("Setting Session key %s\\%s=\"%s\"",
                      self.baseName, key, repr(value))
     win32api.RegSetValueEx(self.key, key, 0, win32con.REG_SZ,
                            repr(value))