rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return doctest.DocFileSuite('testrunner.txt', 'testrunner-edge-cases.txt', setUp=setUp, tearDown=tearDown, optionflags=doctest.ELLIPSIS +doctest.NORMALIZE_WHITESPACE, checker=checker, )
suite = doctest.DocFileSuite( 'testrunner.txt', 'testrunner-edge-cases.txt', setUp=setUp, tearDown=tearDown, optionflags=doctest.ELLIPSIS+doctest.NORMALIZE_WHITESPACE, checker=checker) if not __debug__: suite = unittest.TestSuite([suite, doctest.DocFileSuite( 'profiling.txt', setUp=setUp, tearDown=tearDown, optionflag...
def tearDown(test): sys.path, sys.argv = test.globs['saved-sys-info']
self.starte = False
self.started = False
def stop(self): assert self.started, "can't stop if not started" if not self.donothing: sys.settrace(None) threading.settrace(None) self.starte = False
import trace, tempfile, cPickle
def run_tests(options, tests, name, failures, errors): repeat = options.repeat or 1 ran = 0 for i in range(repeat): if repeat > 1: print "Iteration", i+1 if options.verbose > 0 or options.progress: print ' Running:' if options.verbose == 1 and not options.progress: print ' ', result = TestResult(options, tests) t ...
tracer.runctx('tests(result)', globals=globals(),
tracer.ignore = IgnoreDocTests() tracer.runctx('tests(result)', globals=globals(),
def run_tests(options, tests, name, failures, errors): repeat = options.repeat or 1 ran = 0 for i in range(repeat): if repeat > 1: print "Iteration", i+1 if options.verbose > 0 or options.progress: print ' Running:' if options.verbose == 1 and not options.progress: print ' ', result = TestResult(options, tests) t ...
try: if options.profile: prof_prefix = 'tests_profile' prof_suffix = '.prof' prof_glob = prof_prefix + '*' + prof_suffix dummy, file_path = tempfile.mkstemp(prof_suffix, prof_prefix, '.') prof = hotshot.Profile(file_path) prof.start() try: try: failed = run_with_options(options) except EndRun: failed = True finally: i...
if options.profile: prof_prefix = 'tests_profile' prof_suffix = '.prof' prof_glob = prof_prefix + '*' + prof_suffix if not options.resume_layer:
def run(defaults=None, args=None): if args is None: args = sys.argv # Control reporting flags during run old_reporting_flags = doctest.set_unittest_reportflags(0) # Check to see if we are being run as a subprocess. If we are, # then use the resume-layer and defaults passed in. if len(args) > 1 and args[1] == '--resum...
with the given anme. A code coverage summary is printed to standard
with the given name. A code coverage summary is printed to standard
def refcount_available(*args): if not hasattr(sys, "gettotalrefcount"): raise optparse.OptionValueError("""\
l.tearDown()
if hasattr(l, 'tearDown'): l.tearDown()
def tear_down_unneeded(needed, setup_layers, optional=False): # Tear down any layers not needed for these tests. The unneeded # layers might interfere. unneeded = [l for l in setup_layers if l not in needed] unneeded = order_by_bases(unneeded) unneeded.reverse() for l in unneeded: print " Tear down %s" % name_from_lay...
setup_layer(base, setup_layers)
if base is not object: setup_layer(base, setup_layers)
def setup_layer(layer, setup_layers): if layer not in setup_layers: for base in layer.__bases__: setup_layer(base, setup_layers) print " Set up %s" % name_from_layer(layer), t = time.time() layer.setUp() print "in %.3f seconds." % (time.time() - t) setup_layers[layer] = 1
layer.setUp()
if hasattr(layer, 'setUp'): layer.setUp()
def setup_layer(layer, setup_layers): if layer not in setup_layers: for base in layer.__bases__: setup_layer(base, setup_layers) print " Set up %s" % name_from_layer(layer), t = time.time() layer.setUp() print "in %.3f seconds." % (time.time() - t) setup_layers[layer] = 1
self.layers = []
def __init__(self, options, tests, layer_name=None): unittest.TestResult.__init__(self) self.options = options # Calculate our list of relevant layers we need to call testSetUp # and testTearDown on. self.layers = [] if layer_name != 'unit': gather_layers(layer_from_name(layer_name), self.layers) if options.progress: c...
gather_layers(layer_from_name(layer_name), self.layers)
layers = [] gather_layers(layer_from_name(layer_name), layers) self.layers = order_by_bases(layers) else: self.layers = []
def __init__(self, options, tests, layer_name=None): unittest.TestResult.__init__(self) self.options = options # Calculate our list of relevant layers we need to call testSetUp # and testTearDown on. self.layers = [] if layer_name != 'unit': gather_layers(layer_from_name(layer_name), self.layers) if options.progress: c...
for layer in self.layers[-1::-1]:
for layer in self.layers:
def testSetUp(self): """A layer may define a setup method to be called before each individual test. """ for layer in self.layers[-1::-1]: if hasattr(layer, 'testSetUp'): layer.testSetUp()
for layer in self.layers:
for layer in self.layers[-1::-1]:
def testTearDown(self): """A layer may define a teardown method to be called after each individual test. This is useful for clearing the state of global resources or resetting external systems such as relational databases or daemons. """ for layer in self.layers: if hasattr(layer, 'testTearDown'): layer.testTearDown()
result.append(layer)
if layer is not object: result.append(layer)
def gather_layers(layer, result): result.append(layer) for b in layer.__bases__: gather_layers(b, result)
self._test_dirs = [d[0] + os.path.sep for d in test_dirs(options, {})]
self._test_dirs = [os.path.abspath(d[0]) + os.path.sep for d in test_dirs(options, {})]
def __init__(self, options): self._test_dirs = [d[0] + os.path.sep for d in test_dirs(options, {})] self._ignore = {} self._ignored = self._ignore.get
(re.compile('\\\\'), '/'), (re.compile('/r'), '\\\\r'), (re.compile(r'\r'), '\\\\r\n'), (re.compile(r'\d+[.]\d\d\d seconds'), 'N.NNN seconds'), (re.compile(r'\d+[.]\d\d\d ms'), 'N.NNN ms'),
(re.compile("'[A-Z]:\\\\"), "'"), (re.compile(r'\\\\'), '/'), (re.compile(r'\\'), '/'), (re.compile('/r'), '\\\\r'), (re.compile(r'\r'), '\\\\r\n'), (re.compile(r'\d+[.]\d\d\d seconds'), 'N.NNN seconds'), (re.compile(r'\d+[.]\d\d\d ms'), 'N.NNN ms'),
def test_suite(): import renormalizing checker = renormalizing.RENormalizing([ # 2.5 changed the way pdb reports exceptions (re.compile(r"<class 'exceptions.(\w+)Error'>:"), r'exceptions.\1Error:'), (re.compile('^> [^\n]+->None$', re.M), '> ...->None'), (re.compile('\\\\'), '/'), # hopefully, we'll make windows hap...
'R0903': ('To few public methods (%s/%s)', 'Used when class has to few public methods, so be sure it\'s \
'R0903': ('Too few public methods (%s/%s)', 'Used when class has too few public methods, so be sure it\'s \
def class_is_abstract(klass): """return true if the given class node should be considered as an abstract class """ for attr in klass.values(): if isinstance(attr, Function): if attr.is_abstract(pass_is_abstract=False): return True return False
pass
self.skip('no display, can\'t run this test')
def test_gtk_import(self): try: import gtk except ImportError: self.skip('test skipped: gtk is not available') except RuntimeError: # RuntimeError when missing display pass linter.check('regrtest_data/pygtk_import.py') got = linter.reporter.finalize().strip() self.failUnlessEqual(got, '')
if counter < len(flist) \ and counter > 0:
if fdict[funct].define: if counter < len(flist) \ and counter > 0 :
def GenerateLookup(): global flist global fdict global gParamDict print "-----*----- Generating the lookup table" cwd = os.getcwd() os.chdir(cwd) sname = cwd + "/lookup.c" g = open(sname, "w") olist = StandardFileHeader(sname) ##### -jsv 8/14
chunk = body.read(2**6) while chunk: adapter.write(chunk) chunk = body.read(2**6)
adapter.write(body.read())
def PUT(self): request = self.request
self.request.unauthorized("basic realm='Zope'")
self.request.unauthorized('basic realm="Zope"')
def __call__(self): self.request.unauthorized("basic realm='Zope'") return ''
cur=self.conn.cursor() cur.execute('select max(rowid) from %s' % name) return int(cur.fetchone()[0])
return self.conn.db.sqlite_last_insert_rowid()
def getAutoIncrement(self, name): cur=self.conn.cursor() cur.execute('select max(rowid) from %s' % name) return int(cur.fetchone()[0])
if not sessionDict.hasKey('UserDir'):
if not sessionDict.has_key('UserDir'):
def doUserDirPost(sessionDict): #requestHandler.requestHandler.EndSession if not Configuration.userDir: return if not sessionDict.hasKey('UserDir'): return if not sessionDict['UserDir']: return Configuration.documentRoot = sessionDict['UserDirDocRoot'] Configuration.compileCacheRoot = sessionDict['UserDirCC'] del sess...
if pb[-1] == '/':
if pb and pb[-1] == '/':
def _fix(dict): nd = {} for k,v in dict.items(): nd[str(k)] = str(v) pb = Configuration.CGIProgramBase if nd["SCRIPT_NAME"][:len(pb)] == pb: remnant = nd["SCRIPT_NAME"][len(pb):] if remnant: nd["PATH_INFO"] = '/' + remnant else: nd["PATH_INFO"] = '' if pb[-1] == '/': nd["SCRIPT_NAME"] = pb[:-1] else: nd["SCRIPT_NAME"]...
DEBUG(EXTCGI, "I'm still here! killing self")
os.write(kid_stderr, "exception executing CGI : %s %s" % (sys.exc_info()[0], sys.exc_info()[1])) DEBUG(EXTCGI, "I'm still here! killing self");
def _processRequest(conn, sessionDict): DEBUG(EXTCGI, 'extcgi Processing Request') #dict of environ, headers, stdin kid_stdin, parent_to_kid_stdin = os.pipe() parent_to_kid_stdout, kid_stdout = os.pipe() parent_to_kid_stderr, kid_stderr = os.pipe() pid = os.fork() if pid: #ok I'm the parent DEBUG(EXTCGI, 'child pid is ...
raise "CGIError", "cgi died by signal"
raise "CGIError", ( "cgi died by signal: %s" % ''.join(stderrl))
def _handleParentSide(pid, stdin, stdout, stderr, stdindata): stderrl = [] stdoutl = [] try: while 1: #DEBUG(EXTCGI, "in while") if stdindata: inlist = [stdin] else: inlist = [] r, w, e = select.select([stdout, stderr], inlist, [], 1) #DEBUG(EXTCGI, "rwe= %s %s %s" % (r,w,e)) #DEBUG(EXTCGI, "IOE= %s %s %s" % (stdin, s...
codeout.write ( indent+4, 'MailServices.sendmail ( %s, %s, %s, '
codeout.write ( indent+4, '__h.MailServices.sendmail ( %s, %s, %s, '
def genCode(self, indent, codeout, tagreg, tag): DTCompilerUtil.tagDebug(indent, codeout, tag) args=DTUtil.tagCall(tag, ['to_addrs', 'subject', 'msg', ( 'from_addr', None )] ) args=DTCompilerUtil.pyifyArgs(tag, args)
codeout.write ( indent+4, 'MailServices.sendmail ( %s, %s, %s )' %
codeout.write ( indent+4, '__h.MailServices.sendmail ( %s, %s, %s )' %
def genCode(self, indent, codeout, tagreg, tag): DTCompilerUtil.tagDebug(indent, codeout, tag) args=DTUtil.tagCall(tag, ['to_addrs', 'subject', 'msg', ( 'from_addr', None )] ) args=DTCompilerUtil.pyifyArgs(tag, args)
DEBUG(CORE, "calling %s with args (%s, %s)" % (str(f), str(args), str(kw)))
if DEBUGIT(CORE): DEBUG(CORE, "calling %s with args (%s, %s)" % (str(f), str(args), str(kw)))
def __call__(self, jobName, *args, **kw): # SkunkWeb will not bootstrap if this is imported at the top level global DEBUG try: DEBUG except: import SkunkWeb.LogObj DEBUG=SkunkWeb.LogObj.DEBUG for f in self._getFuncList(jobName): DEBUG(CORE, "calling %s with args (%s, %s)" % (str(f), str(args), str(kw))) try: retVal=f(*...
newresult = [] for row in rows: d = {} for item, desc in map(None, row, colnames): a = attributes[desc] if _isDateKind(a): d[desc] = _dateConvertFromDB(item) elif _isNumber(a): if a in ('FLOAT4', 'FLOAT8'): f = float else: if item is None: f = lambda x: x else: f = lambda x: x is None and None or int(float(x)) d[desc]...
newresult = [] for row in rows: d = {} for item, desc in map(None, row, colnames): a = attributes[desc].upper() if _isIntervalKind(a): d[desc]=_intervalConvertFromDB(item) elif _isTimeKind(a): d[desc]=_timeConvertFromDB(item) elif _isDateKind(a): d[desc] = _dateConvertFromDB(item) elif _isNumber(a) and not item is Non...
def convertResultRows(self, colnames, attributes, rows): newresult = [] for row in rows: d = {} for item, desc in map(None, row, colnames): #do dbtype->python type conversions here a = attributes[desc] if _isDateKind(a): d[desc] = _dateConvertFromDB(item) elif _isNumber(a): if a in ('FLOAT4', 'FLOAT8'): f = float else:...
raise TypeError,'trying to assign %s to %s and is not a date, being of type %s ' % (val, aname, type(val))
raise TypeError,( 'trying to assign %s to %s and is not a date, '\ 'being of type %s ' ) % (val, aname, type(val))
def typeCheckAndConvert(self, val, aname, attr): if val == None: val = "NULL" elif _isDateKind(attr): if (not isDateTime(val)) and not val == PyDBI.SYSDATE: raise TypeError,'trying to assign %s to %s and is not a date, being of type %s ' % (val, aname, type(val)) val = _dateConvertToDB(val) elif _isNumber(attr): if at...
return '1=1'
return 'TRUE'
def typeCheckAndConvert(self, val, aname, attr): if val == None: val = "NULL" elif _isDateKind(attr): if (not isDateTime(val)) and not val == PyDBI.SYSDATE: raise TypeError,'trying to assign %s to %s and is not a date, being of type %s ' % (val, aname, type(val)) val = _dateConvertToDB(val) elif _isNumber(attr): if at...
return '0=1'
return 'FALSE'
def typeCheckAndConvert(self, val, aname, attr): if val == None: val = "NULL" elif _isDateKind(attr): if (not isDateTime(val)) and not val == PyDBI.SYSDATE: raise TypeError,'trying to assign %s to %s and is not a date, being of type %s ' % (val, aname, type(val)) val = _dateConvertToDB(val) elif _isNumber(attr): if at...
try: return DateTime.strptime(d, '%Y-%m-%d') except: pass try: return DateTime.strptime(d, '%H:%M:%S') except: pass dashind = string.rindex(d, '-')
for format in ('%Y-%m-%d', '%H:%M:%S', '%H:%M'): try: return DateTime.strptime(d, format) except: pass dashind = d.rfind('-')
def _dateConvertFromDB(d): if d==None: return None try: return DateTime.strptime(d, '%Y-%m-%d') #just Y/M/D except: pass try: return DateTime.strptime(d, '%H:%M:%S') #just hh:mm:ss except: pass dashind = string.rindex(d, '-') tz = d[dashind:] d = d[:dashind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz e...
try: return DateTime.strptime(d, '%H:%M:%S'), tz except: pass
def _dateConvertFromDB(d): if d==None: return None try: return DateTime.strptime(d, '%Y-%m-%d') #just Y/M/D except: pass try: return DateTime.strptime(d, '%H:%M:%S') #just hh:mm:ss except: pass dashind = string.rindex(d, '-') tz = d[dashind:] d = d[:dashind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz e...
def _timeConvertFromDB(t): if t==None: return None for format in ('%H:%M:%S', '%H:%M'): try: return DateTime.strptime(t, format) except: pass raise DateTime.Error, "could not parse time: %s" % t def _intervalConvertFromDB(i): if i==None: return None raise NotImplementedError
def _dateConvertFromDB(d): if d==None: return None try: return DateTime.strptime(d, '%Y-%m-%d') #just Y/M/D except: pass try: return DateTime.strptime(d, '%H:%M:%S') #just hh:mm:ss except: pass dashind = string.rindex(d, '-') tz = d[dashind:] d = d[:dashind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz e...
'NUMERIC')
'NUMERIC', 'BIGINT', 'SMALLINT')
def _isNumber(t): return string.upper(t) in ( 'OID', 'DECIMAL', 'FLOAT4', 'FLOAT8', 'INT2', 'INT4', 'INT8', 'NUMERIC')
compileCacheRoot = "%s/cache" % Configuration.SkunkRoot, componentCacheRoot = "%s/cache" % Configuration.SkunkRoot,
compileCacheRoot = confvars.DEFAULT_CACHE, componentCacheRoot = confvars.DEFAULT_CACHE,
def __initConfig(): from AE import cfg from SkunkWeb import Configuration, confvars # set our defaults from AE defaults Configuration.mergeDefaults( documentRoot = confvars.DEFAULT_DOCROOT, compileCacheRoot = "%s/cache" % Configuration.SkunkRoot, componentCacheRoot = "%s/cache" % Configuration.SkunkRoot, failoverCompon...
return compile(codestr, name, 'exec'), codestr
try: return compile(codestr, name, 'exec'), codestr except SyntaxError, synerror: se = SkunkExcept.SkunkSyntaxError(name, codestr, synerror, 'error compiling PSP template', 0) fmt = se.format().split('\n') raise "PSPSyntaxError", '\n'.join(fmt[1:-2])
def psp_compile(s, name): """<% and %> are the code delimiters""" l = [] while 1: ci = s.find('<%') if ci == -1: l.append((LITERAL, s)) break l.append((LITERAL,s[:ci])) code = s[ci+2:] #print 'code is ', code ce = code.find('%>') if ce == -1: raise 'EOFError', 'End of file reached while in code' code = code[:ce] l.appe...
self.comp_path=rectifyRelativePath(comp_path)
self.comp_path=rectifyRelativeName(comp_path)
def __init__(self, comp_path): self.comp_path=rectifyRelativePath(comp_path)
self.conn = SQL.getConnection(realConn)
self.conn = Oracle.getConnection(realConn)
def __init__(self, connectString): self.connectString = connectString realConn, self.verbose = self._parseConnectString(connectString) self.realConn = realConn self.conn = SQL.getConnection(realConn) #self.conn = DCOracle.Connect(realConn) self.bvcount = 0 oraConns.append(self.conn) self.bindVariables = 1 if self.verbo...
return SQL.getProcedure(self.realConn, procName)
return Oracle.getProcedure(self.realConn, procName)
def getProcedure(self, procName): return SQL.getProcedure(self.realConn, procName)
'%H:%M'):
'%H:%M', '%Y-%m'):
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M'): # hh:mm try: return DateTime.strptime(d, format) except: pass dashind = d.rfind('-') tz = d[dashind:] d = d[:dashind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz except: pass try: #...
dashind = d.rfind('-')
dashind = max(d.rfind('-'), d.rfind('+'))
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M'): # hh:mm try: return DateTime.strptime(d, format) except: pass dashind = d.rfind('-') tz = d[dashind:] d = d[:dashind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz except: pass try: #...
try:
if 1:
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M'): # hh:mm try: return DateTime.strptime(d, format) except: pass dashind = d.rfind('-') tz = d[dashind:] d = d[:dashind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz except: pass try: #...
except: raise
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M'): # hh:mm try: return DateTime.strptime(d, format) except: pass dashind = d.rfind('-') tz = d[dashind:] d = d[:dashind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz except: pass try: #...
'Lists the names of registered methods')
'Lists the names of registered methods', [[ARRAY]])
def __init__(self, add_system_methods=1, max_request=50000): self.funcs={} self.max_request=max_request if add_system_methods: self.register_function(self.funcs.keys, 'system.listMethods', 'Lists the names of registered methods') # using lambdas to keep the method signature accurate self.register_function(lambda method...
'Raises a Fault if the method does not exist.'))
'Raises a Fault if the method does not exist'), [[ARRAY, STRING]])
def __init__(self, add_system_methods=1, max_request=50000): self.funcs={} self.max_request=max_request if add_system_methods: self.register_function(self.funcs.keys, 'system.listMethods', 'Lists the names of registered methods') # using lambdas to keep the method signature accurate self.register_function(lambda method...
"Raises a Fault if the method does not exist."))
"Raises a Fault if the method does not exist."), [[STRING, STRING]])
def __init__(self, add_system_methods=1, max_request=50000): self.funcs={} self.max_request=max_request if add_system_methods: self.register_function(self.funcs.keys, 'system.listMethods', 'Lists the names of registered methods') # using lambdas to keep the method signature accurate self.register_function(lambda method...
_multicall_doc) def _methodSignature(self, method):
_multicall_doc, [[ARRAY, ARRAY]]) self.register_function(lambda method: self._methodPydoc(method), 'system.methodPydoc', ('Gives pydoc method signature for the method requested. '\ 'Raises a Rault if the method does not exist.'), [[STRING]]) def _methodPydoc(self, method):
def __init__(self, add_system_methods=1, max_request=50000): self.funcs={} self.max_request=max_request if add_system_methods: self.register_function(self.funcs.keys, 'system.listMethods', 'Lists the names of registered methods') # using lambdas to keep the method signature accurate self.register_function(lambda method...
docstring=None):
docstring=None, signature=UNDEF):
def register_function(self, func, name=None, docstring=None): if name is None: name=func.__name__ if docstring is None: docstring=func.__doc__ or "" self.funcs[name]=(func, docstring.strip())
self.funcs[name]=(func, docstring.strip())
self.funcs[name]=(func, docstring.strip(), signature)
def register_function(self, func, name=None, docstring=None): if name is None: name=func.__name__ if docstring is None: docstring=func.__doc__ or "" self.funcs[name]=(func, docstring.strip())
def _dorewrite(match, connection, sessionDict, replacement):
def _dorewrite(match, connection, sessionDict, replacement, key):
def _dorewrite(match, connection, sessionDict, replacement): if callable(replacement): if isinstance(replacement, DynamicRewriter): replacement.refresh(connection, sessionDict) connection.uri = match.re.sub(replacement, connection.uri) else: connection.uri = match.expand(replacement) groupdict=m.groupdict() if Configur...
groupdict=m.groupdict()
groupdict=match.groupdict()
def _dorewrite(match, connection, sessionDict, replacement): if callable(replacement): if isinstance(replacement, DynamicRewriter): replacement.refresh(connection, sessionDict) connection.uri = match.re.sub(replacement, connection.uri) else: connection.uri = match.expand(replacement) groupdict=m.groupdict() if Configur...
_dorewrite(m, connection, sessionDict, rule[1])
_dorewrite(m, connection, sessionDict, rule[1], key)
def _rewritePre(connection, sessionDict): """ hook for web.protocol.PreHandleConnection """ sessionDict['rewriteRules'] = {} try: DEBUG(REWRITE, 'executing PreRewriteMatch hook') PreRewriteMatch(connection, sessionDict) DEBUG(REWRITE, 'survived PreRewriteMatch hook') except: logException() rules = Configuration.rewrite...
if item[:l] == l:
if item[:ll] == l:
def _aPrefixIn(item, l): for i in l: ll = len(l) if item[:l] == l: return 1 return None
if not results: return
def static_getUnique(self, **kw): """given the attribute/value pairs in kw, retrieve a unique row and return a data class instance representing said row or None if no row was retrieved""" unique = self._matchUnique(kw) sql = self._baseSelect() + " WHERE " conn = self.getDBI() where, values = self._uniqueWhere(conn, kw...
os.seteuid(0)
if hasattr(os, 'seteuid'): os.seteuid(0)
def addService(sockAddr, func): reset = None if hasattr(os, 'geteuid') and os.getuid() != os.geteuid(): reset = os.geteuid() #uid to switch back to os.seteuid(0) try: svr.addConnection(sockAddr, func) finally: # make sure we go back to the initial user if reset is not None and hasattr(os, 'seteuid'): os.seteuid(reset)...
self._mergeDefaultsKw(kw)
self._mergeDefaultsKw(**kw)
def mergeDefaults(self, *args, **kw): """ added for compatibility with the config object used by SkunkWeb """ self._mergeDefaultsKw(kw) for dict in args: self._mergeDict(dict)
if isinstance(item, DateTime.DateTime):
if type(item)==DateTime.DateTimeType:
def _dateConvertFromDB(item): if item is None: return item # MySQLdb will now return DateTime objects is egenix is present. if isinstance(item, DateTime.DateTime): return item if string.find(item, '-') == -1: #timestamp form y = item[:4] mo = item[4:6] d = item[6:8] h = item[8:10] mi = item[10:12] s = item[12:14] else:...
self.requestCookie.load(self.requestHeaders['Cookie'])
try: self.requestCookie.load(self.requestHeaders['Cookie']) except Cookie.CookieError: logException()
def _initCookies(self): self.requestCookie = Cookie.SimpleCookie() if self.requestHeaders.has_key('Cookie'): self.requestCookie.load(self.requestHeaders['Cookie']) self.responseCookie = Cookie.SimpleCookie()
robustlist=classdict.get('robust') robustify=classdict.get('robustify')
robustlist=classdict.get('robust', [])
def __new__(self, classname, bases, classdict): robustlist=classdict.get('robust') robustify=classdict.get('robustify') if robustlist and robustify: for mname in robustlist: m=classdict.get(mname) if m and isinstance(m, types.FunctionType): classdict[mname]=robustify(m) return type.__new__(self, classname, bases, clas...
if robustlist and robustify: for mname in robustlist: m=classdict.get(mname) if m and isinstance(m, types.FunctionType): classdict[mname]=robustify(m)
for mname in robustlist: m=classdict.get(mname) if not m: for b in bases: if hasattr(b, mname): m=getattr(b, mname) break if m: classdict[mname]=_robustify(m) else: print type(m)
def __new__(self, classname, bases, classdict): robustlist=classdict.get('robust') robustify=classdict.get('robustify') if robustlist and robustify: for mname in robustlist: m=classdict.get(mname) if m and isinstance(m, types.FunctionType): classdict[mname]=robustify(m) return type.__new__(self, classname, bases, clas...
def robustify(func): def robuster(*args, **kwargs): try: func(*args, **kwargs) except ftplib.error_temp: self=args[0] try: self.login(self.user, self.passwd, self.acct) except (socket.error, IOError): self.connect(self.host, self.port) self.login(self.user, self.passwd, self.acct) return func(*args, **kwargs) return ro...
def login(self, user='', passwd='', acct=''): self.user=user self.passwd=passwd self.acct=acct ftplib.FTP.login(self, user, passwd, acct)
return str(self.values)
l=len(self.values) if l>1: return str(self.values) else: return "(%s)" % repr(self.values[0])
def __str__(self): return str(self.values)
return "SET(%s)" % str(self.values)
return "SET(%s)" % self.__str__()
def __repr__(self): return "SET(%s)" % str(self.values)
def getStartForm(self):
def getStartForm(self, argdict):
def getStartForm(self): return self.forms[0]
os.execle(*args)
DEBUG(EXTCGI, 'args is %s' % repr(args)) oldpwd = os.getcwd() try: os.chdir(os.path.split(env["PATH_TRANSLATED"])[0]) os.execle(*args) finally: os.chdir(oldpwd)
def _processRequest(conn, sessionDict): DEBUG(EXTCGI, 'extcgi Processing Request') #dict of environ, headers, stdin kid_stdin, parent_to_kid_stdin = os.pipe() parent_to_kid_stdout, kid_stdout = os.pipe() parent_to_kid_stderr, kid_stderr = os.pipe() pid = os.fork() try: if pid: #ok I'm the parent DEBUG(EXTCGI, 'child pi...
ns_copy = namespace.copy( ) del componentStack[ topOfComponentStack+1 : ] namespace = ns_copy
def _realRenderComponent( name, argDict, auxArgs, compType, srcModTime ): global topOfComponentStack DEBUG(COMPONENT, "_realRenderComponent") executable = Executables.getExecutable( name, compType, srcModTime ) if compType == DT_INCLUDE and componentStack: namespace = componentStack[topOfComponentStack].namespace else...
documentRoot = "%s/docroot" % confvars.DEFAULT_DOCROOT,
documentRoot = confvars.DEFAULT_DOCROOT,
def __initConfig(): from AE import cfg from SkunkWeb import Configuration, confvars # set our defaults from AE defaults Configuration.mergeDefaults( documentRoot = "%s/docroot" % confvars.DEFAULT_DOCROOT, compileCacheRoot = "%s/cache" % Configuration.SkunkRoot, componentCacheRoot = "%s/cache" % Configuration.SkunkRoot,...
PostgreSql.getConnection(connectArgs)
self.conn = PostgreSql.getConnection(connectArgs)
def __init__(self, connectArgs): connectArgs = string.split(connectArgs,':') host = None if connectArgs and connectArgs[0]: #if host is there if '|' in connectArgs[0]: #if specified port host = connectArgs[0].replace('|', ':') if connectArgs and connectArgs[-1] == 'verbose': self.verbose = 1 connectArgs = connectArgs[...
data = eval(data,{'__builtin__': {}} , {})
data = eval('\n'.join(data.split('\r\n')),{'__builtin__': {}} , {})
def _mcCompileFunc(name, data): data = eval(data,{'__builtin__': {}} , {}) return _mcMakeCat(data, name)
for k,v in respp.items(): resl.append("%s: %s" % (self._fixHeader(k), v)) return "\r\n".join(resl)+"\r\n\r\n"+respp.fp.read()
for k in respp.keys(): kf=self._fixHeader(k) for v in respp.getheaders(k): resl.append("%s: %s" % (kf, v)) return "%s\r\n\r\n%s" % ("\r\n".join(resl), respp.fp.read())
def marshalResponse(self, response, sessionDict): httpVersion=sessionDict.get(constants.HTTP_VERSION, '') respp = rfc822.Message(cStringIO.StringIO(response)) status = respp.getheader('status') server = respp.getheader('server') if not status: status = "200 OK" else: del respp['status'] if not server: respp['server'] =...
global Configuration
def reload(self): # extract what we need from configuration, and wipe it out global Configuration ver, cf, sr = (Configuration.SkunkWebVersion, Configuration._config_files_, Configuration.SkunkRoot) SocketMan.reload(self) del Configuration global LogObj del LogObj sm = ['ConfigAdditives', 'Configuration', 'Hooks', 'K...
morsel[a]=v+time.time()
morsel[a]=Cookie._getdate(v)
def _add_usertracking_cookie(conn, sessionDict): if Configuration.usertrackingOn: cookiename=Configuration.usertrackingCookieName if not _verify_cookie(conn, cookiename): f=Configuration.usertrackingGenUIDFunc if f is None: conn.responseCookie[cookiename]=uuid() else: conn.responseCookie[cookiename]=f(conn) morsel=conn...
p=os.join(_sesspath, f)
p=os.path.join(_sesspath, f)
def reapOldRecords(self): # walk through contents of session directory and delete any # lapsed files for f in os.listdir(_sesspath): p=os.join(_sesspath, f) lastAccess=os.path.getatime(p) now=time.time() if now-lastAccess>Configuration.SessionTimeout: os.remove(p)
now=time.time()
def reapOldRecords(self): # walk through contents of session directory and delete any # lapsed files for f in os.listdir(_sesspath): p=os.join(_sesspath, f) lastAccess=os.path.getatime(p) now=time.time() if now-lastAccess>Configuration.SessionTimeout: os.remove(p)
return self.__sessionID
sid=self.__sessionID
def getSessionID(self, create=1): ''' obtain the session id from the request cookie, or, if not available, create a new one. ''' try: return self.__sessionID except AttributeError: sesskey=Configuration.SessionIDKey try: sid=self.requestCookie[sesskey].value except KeyError: # look in connection arguments for session i...
_connections[connectParams] = apply(pgdb.connect, connectParams) except pgdb.error:
_connections[connectParams] = pgdb.connect(connectParams) except pgdb.Error:
def getConnection(connUser): """ Returns a database connection as defined by connUser. If this module already has an open connection for connUser, it returns it; otherwise, it creates a new connection, stores it, and returns it. """ if not _users.has_key ( connUser ): raise SkunkStandardError, 'user %s is not initiali...
def execSql(self, sql, args=None):
def execSql(self, sql, args=None, expect=1):
def execSql(self, sql, args=None): DEBUG(SESSIONHANDLER, sql) try: db=self.getConnection() cursor=db.cursor() if args: cursor.execute(sql, args) else: cursor.execute(sql) retval=cursor.fetchall() cursor.close() db.commit() return retval except Exception, e: DEBUG(SESSIONHANDLER, "sql exception -- see error log") logExc...
retval=cursor.fetchall()
if expect: retval=cursor.fetchall() else: retval=None
def execSql(self, sql, args=None): DEBUG(SESSIONHANDLER, sql) try: db=self.getConnection() cursor=db.cursor() if args: cursor.execute(sql, args) else: cursor.execute(sql) retval=cursor.fetchall() cursor.close() db.commit() return retval except Exception, e: DEBUG(SESSIONHANDLER, "sql exception -- see error log") logExc...
self.execSql(self.touchSQL % args)
self.execSql(self.touchSQL % args, expect=0)
def touch(self): """ resets the timestamp for the session's corresponding record. """ DEBUG(SESSIONHANDLER, "in touch") args={'table' : self.table, 'timeCol' : self.timeCol, 'idCol' : self.idCol, 'id' : self.__id} self.execSql(self.touchSQL % args) self._touched=int(time.time())
self.execSql(self.deleteSQL % args)
self.execSql(self.deleteSQL % args, expect=0)
def delete(self): DEBUG(SESSIONHANDLER, "in delete") args={'id' : self.__id, 'idCol' : self.idCol, 'table' : self.table} self.execSql(self.deleteSQL % args) self._touched=int(time.time())
ret=self.jobFunc(*args, **kwargs)
return self.jobFunc(*args, **kwargs)
def __call__(self, local_ns=None, global_ns=None, *args, **kwargs): if callable(self.jobFunc): ret=self.jobFunc(*args, **kwargs) else: if local_ns is None: local_ns=globals() if global_ns is None: global_ns=globals() ret=eval(self.jobFunc, global_ns, local_ns) return ret
ret=eval(self.jobFunc, global_ns, local_ns) return ret
exec self.jobFunc in global_ns, local_ns
def __call__(self, local_ns=None, global_ns=None, *args, **kwargs): if callable(self.jobFunc): ret=self.jobFunc(*args, **kwargs) else: if local_ns is None: local_ns=globals() if global_ns is None: global_ns=globals() ret=eval(self.jobFunc, global_ns, local_ns) return ret
signal.signal(signal.SIGCHLD, sig.SIG_DFL) signal.signal(signal.SIGTERM, sig.SIG_DFL)
signal.signal(signal.SIGCHLD, signal.SIG_DFL) signal.signal(signal.SIGTERM, signal.SIG_DFL)
def run(self, termhandler=None): """ this method is used if you want the crontab to run in its own loop. If you don't, you are responsible for killing off the zombies yourself. """ signal.signal(signal.SIGCHLD, self._handle_sigchld) if termhandler: signal.signal(signal.SIGTERM, termhandler) while 1: try: time.sleep(se...
SessionHandler_FSSessionDir=os.path.join(Configuration.SkunkRoot, 'var/run/skunksessions')
SessionHandler_FSSessionDir=os.path.join(Configuration.SkunkRoot, 'var/run/skunksessions'),
def __initConfig(): from SkunkWeb import Configuration Configuration.mergeDefaults( # session timeout, in seconds. SessionTimeout = 30*60, # the key under which the session is kept SessionIDKey='sessionID', # the host, user, password, and database (for MySQLSessionStoreImpl) SessionHandler_MySQLHost='localhost', Sess...
nd['SCRIPT_NAME']=uri[len(Configuration.documentRoot):]
nd['SCRIPT_NAME']=fullpath[len(Configuration.documentRoot):]
def _fix(dict, uri): DEBUG(PYCGI, "in _fix") nd = {} for k,v in dict.items(): nd[str(k)] = str(v) fullpath, extra=Configuration.documentRootFS.split_extra(\ AE.Cache._fixPath(Configuration.documentRoot, uri)) if not fullpath: raise vfs.FileNotFoundException, fullpath # file exists nd['PATH_INFO']=extra nd['PATH_TRANSLA...
raise PreemptiveResponse, fourOhFourHandler(conn, sessionDict)
return fourOhFourHandler(conn, sessionDict)
def _processRequest(conn, sessionDict): DEBUG(PYCGI, "pycgi processing request") try: env=_fix(conn.env, conn.uri) except vfs.FileNotFoundException: DEBUG(PYCGI, "file not found!") raise PreemptiveResponse, fourOhFourHandler(conn, sessionDict) DEBUG(PYCGI, "file evidently exists") oldpwd=os.getcwd() os.environ.update(e...
from_addr = Configuration.FromAddress ):
from_addr = Configuration.FromAddress, **extended ):
def sendmail ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ): """** <p>The general-purpose sendmail function, which is called by the STML &lt;:sendmail:&gt; tag, or directly by Python code.</p> <p><tt>to_addrs</tt> should be a list or tuple of email address strings. <tt>subj</tt> must be a string, althou...
<p>This function returns nothing on success, and raises a <code>MailError</code> on any mail failure.</p> """
<p>This function returns nothing on success, and raises a <code>MailError</code> on any mail failure.</p> <p> The From: and To: headers are always built from supplied parameters. Cc: and Bcc: headers in the supplied mail text are not touched and not used. </p> <p> The sendmail function adds a correct Date: header, ensu...
def sendmail ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ): """** <p>The general-purpose sendmail function, which is called by the STML &lt;:sendmail:&gt; tag, or directly by Python code.</p> <p><tt>to_addrs</tt> should be a list or tuple of email address strings. <tt>subj</tt> must be a string, althou...
sendmail_smtp(to_addrs, subj, msg, from_addr) else: sendmail_pipe(to_addrs, subj, msg, from_addr) def sendmail_smtp ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ):
sendmail_smtp(to_addrs, messagetext, envelope_sender) elif _method == 'qmail': qmail_pipe(to_addrs, messagetext, envelope_sender) else: sendmail_pipe(to_addrs, messagetext, envelope_sender) def sendmail_smtp ( to_addrs, msg, envelope_sender):
def sendmail ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ): """** <p>The general-purpose sendmail function, which is called by the STML &lt;:sendmail:&gt; tag, or directly by Python code.</p> <p><tt>to_addrs</tt> should be a list or tuple of email address strings. <tt>subj</tt> must be a string, althou...
msg = 'Subject: %s\n' % subj + msg
def sendmail_smtp ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ): """** <p>Called by <code>sendmail</code> function, this function uses SMTP to send a mail message. Function raises a <code>MailError</code> if it cannot connect to the SMTP server; any other errors are merely sent as warnings to the Skunk...
errs = conn.sendmail ( from_addr, to_addrs, msg )
errs = conn.sendmail ( envelope_sender, to_addrs, msg )
def sendmail_smtp ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ): """** <p>Called by <code>sendmail</code> function, this function uses SMTP to send a mail message. Function raises a <code>MailError</code> if it cannot connect to the SMTP server; any other errors are merely sent as warnings to the Skunk...
WARN ( 'URL %s: sendmail: not all recepients received mail:' )
WARN ( 'URL %s: sendmail(smtp): not all recepients received mail:' )
def sendmail_smtp ( to_addrs, subj, msg, from_addr = Configuration.FromAddress ): """** <p>Called by <code>sendmail</code> function, this function uses SMTP to send a mail message. Function raises a <code>MailError</code> if it cannot connect to the SMTP server; any other errors are merely sent as warnings to the Skunk...
data=cPickle.load(f)
try: data=cPickle.load(f) except: logException() data={}
def __getPickle(self): if os.path.exists(self.__picklepath): f=open(self.__picklepath) fd=f.fileno() # let reads coexist fcntl.flock(fd, fcntl.LOCK_SH) data=cPickle.load(f) fcntl.flock(fd, fcntl.LOCK_UN) f.close() return data
cPickle.dump(data, f, 1)
try: cPickle.dump(data, f, 1) except: logException()
def __setPickle(self, data): # lock and unlock, TBD f=open(self.__picklepath, 'w') fd=f.fileno() fcntl.flock(fd, fcntl.LOCK_EX) cPickle.dump(data, f, 1) fcntl.flock(fd, fcntl.LOCK_UN) f.close()
return str(self.values)
return "(%s)" % ', '.join([self.__escape_string(x) for x in self.values])
def __str__(self): l=len(self.values) if l>1: return str(self.values) else: return "(%s)" % repr(self.values[0])
return "(%s)" % repr(self.values[0])
return "(%s)" % self.__escape_string(self.values[0]) def __escape_string(self, s): return "'%s'" % string.replace(s, "'", "\\'")
def __str__(self): l=len(self.values) if l>1: return str(self.values) else: return "(%s)" % repr(self.values[0])
def connect(self, host='', port=0):
def connect(self, host='', port=ftplib.FTP_PORT):
def connect(self, host='', port=0): self.host=host self.port=port ftplib.FTP.connect(host, port)