jtoolkit-cvs Mailing List for jToolkit (Page 7)
Brought to you by:
davidfraser,
friedelwolff
You can subscribe to this list here.
2003 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(1) |
Sep
(15) |
Oct
(12) |
Nov
|
Dec
(4) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
|
Feb
(100) |
Mar
(27) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <dav...@us...> - 2003-09-25 18:18:43
|
Update of /cvsroot/jtoolkit/jToolkit/demo In directory sc8-pr-cvs1:/tmp/cvs-serv20907 Added Files: __init__.py helloworld.py Log Message: added basic hello world demo --- NEW FILE: __init__.py --- """jToolkit.demo package index""" # Copyright 2002, 2003 St James Software # # This file is part of jToolkit. # # jToolkit is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # jToolkit is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with jToolkit; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # list of modules in this package __all__ = ["helloworld"] --- NEW FILE: helloworld.py --- """this is a Hello World-style demonstration program of jToolkit""" from jToolkit.web import server from jToolkit.widgets import widgets # Copyright 2002, 2003 St James Software # # This file is part of jToolkit. # # jToolkit is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # jToolkit is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with jToolkit; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class HelloWorldServer(server.AppServer): """the Server that serves the Hello World Pages""" def getpage(self, pathwords, session, argdict): """return a page that will be sent to the user""" return widgets.PlainContents("Hello World") class HelloWorldConfig: """the configuration parameters for a hello world server""" serverclass = HelloWorldServer localedir = "/share/sjsoft/code/jSuite.py/localize" localedomains = ['jToolkit', 'jLogbook.python'] |
From: <dav...@us...> - 2003-09-25 18:17:50
|
Update of /cvsroot/jtoolkit/jToolkit/demo/html In directory sc8-pr-cvs1:/tmp/cvs-serv20746/html Log Message: Directory /cvsroot/jtoolkit/jToolkit/demo/html added to the repository |
From: <dav...@us...> - 2003-09-25 18:10:56
|
Update of /cvsroot/jtoolkit/jToolkit/data In directory sc8-pr-cvs1:/tmp/cvs-serv19067 Added Files: _strptime.py Log Message: imported modified _strptime from Python 2.3 --- NEW FILE: _strptime.py --- """Strptime-related classes and functions. CLASSES: LocaleTime -- Discovers and/or stores locale-specific time information TimeRE -- Creates regexes for pattern matching a string of text containing time information as is returned by time.strftime() FUNCTIONS: _getlang -- Figure out what language is being used for the locale strptime -- Calculates the time struct represented by the passed-in string Requires Python 2.2.1 or higher (mainly because of the use of property()). Can be used in Python 2.2 if the following line is added: True = 1; False = 0 """ # this file is from Python 2.3 and has been modified to work in Python 2.2 import time import locale import calendar from re import compile as re_compile from re import IGNORECASE try: from datetime import date as datetime_date except ImportError: # compatibility mode for Python 2.2 without datetime module from DateTime import mxDateTime class datetime_date: fromordinal = mxDateTime.DateTimeFromAbsDays def __init__(self,y,m,d): self.date = mxDateTime.DateTime(y,m,d) def toordinal(self): return self.date.absdate def weekday(self): return self.date.day_of_week __author__ = "Brett Cannon" __email__ = "br...@py..." __all__ = ['strptime'] def _getlang(): # Figure out what the current language is set to. return locale.getlocale(locale.LC_TIME) class LocaleTime(object): """Stores and handles locale-specific information related to time. This is not thread-safe! Attributes are lazily calculated and no precaution is taken to check to see if the locale information has changed since the creation of the instance in use. ATTRIBUTES (all read-only after instance creation! Instance variables that store the values have mangled names): f_weekday -- full weekday names (7-item list) a_weekday -- abbreviated weekday names (7-item list) f_month -- full weekday names (14-item list; dummy value in [0], which is added by code) a_month -- abbreviated weekday names (13-item list, dummy value in [0], which is added by code) am_pm -- AM/PM representation (2-item list) LC_date_time -- format string for date/time representation (string) LC_date -- format string for date representation (string) LC_time -- format string for time representation (string) timezone -- daylight- and non-daylight-savings timezone representation (3-item list; code tacks on blank item at end for possible lack of timezone such as UTC) lang -- Language used by instance (string) """ def __init__(self, f_weekday=None, a_weekday=None, f_month=None, a_month=None, am_pm=None, LC_date_time=None, LC_time=None, LC_date=None, timezone=None, lang=None): """Optionally set attributes with passed-in values.""" if f_weekday is None: self.__f_weekday = None elif len(f_weekday) == 7: self.__f_weekday = list(f_weekday) else: raise TypeError("full weekday names must be a 7-item sequence") if a_weekday is None: self.__a_weekday = None elif len(a_weekday) == 7: self.__a_weekday = list(a_weekday) else: raise TypeError( "abbreviated weekday names must be a 7-item sequence") if f_month is None: self.__f_month = None elif len(f_month) == 12: self.__f_month = self.__pad(f_month, True) else: raise TypeError("full month names must be a 12-item sequence") if a_month is None: self.__a_month = None elif len(a_month) == 12: self.__a_month = self.__pad(a_month, True) else: raise TypeError( "abbreviated month names must be a 12-item sequence") if am_pm is None: self.__am_pm = None elif len(am_pm) == 2: self.__am_pm = am_pm else: raise TypeError("AM/PM representation must be a 2-item sequence") self.__LC_date_time = LC_date_time self.__LC_time = LC_time self.__LC_date = LC_date self.__timezone = timezone if timezone: if len(timezone) != 2: raise TypeError("timezone names must contain 2 items") else: self.__timezone = self.__pad(timezone, False) if lang: self.__lang = lang else: self.__lang = _getlang() def __pad(self, seq, front): # Add '' to seq to either front (is True), else the back. seq = list(seq) if front: seq.insert(0, '') else: seq.append('') return seq def __set_nothing(self, stuff): # Raise TypeError when trying to set an attribute. raise TypeError("attribute does not support assignment") def __get_f_weekday(self): # Fetch self.f_weekday. if not self.__f_weekday: self.__calc_weekday() return self.__f_weekday def __get_a_weekday(self): # Fetch self.a_weekday. if not self.__a_weekday: self.__calc_weekday() return self.__a_weekday f_weekday = property(__get_f_weekday, __set_nothing, doc="Full weekday names") a_weekday = property(__get_a_weekday, __set_nothing, doc="Abbreviated weekday names") def __get_f_month(self): # Fetch self.f_month. if not self.__f_month: self.__calc_month() return self.__f_month def __get_a_month(self): # Fetch self.a_month. if not self.__a_month: self.__calc_month() return self.__a_month f_month = property(__get_f_month, __set_nothing, doc="Full month names (dummy value at index 0)") a_month = property(__get_a_month, __set_nothing, doc="Abbreviated month names (dummy value at index 0)") def __get_am_pm(self): # Fetch self.am_pm. if not self.__am_pm: self.__calc_am_pm() return self.__am_pm am_pm = property(__get_am_pm, __set_nothing, doc="AM/PM representation") def __get_timezone(self): # Fetch self.timezone. if not self.__timezone: self.__calc_timezone() return self.__timezone timezone = property(__get_timezone, __set_nothing, doc="Timezone representation (dummy value at index 2)") def __get_LC_date_time(self): # Fetch self.LC_date_time. if not self.__LC_date_time: self.__calc_date_time() return self.__LC_date_time def __get_LC_date(self): # Fetch self.LC_date. if not self.__LC_date: self.__calc_date_time() return self.__LC_date def __get_LC_time(self): # Fetch self.LC_time. if not self.__LC_time: self.__calc_date_time() return self.__LC_time LC_date_time = property( __get_LC_date_time, __set_nothing, doc= "Format string for locale's date/time representation ('%c' format)") LC_date = property(__get_LC_date, __set_nothing, doc="Format string for locale's date representation ('%x' format)") LC_time = property(__get_LC_time, __set_nothing, doc="Format string for locale's time representation ('%X' format)") lang = property(lambda self: self.__lang, __set_nothing, doc="Language used for instance") def __calc_weekday(self): # Set self.__a_weekday and self.__f_weekday using the calendar # module. a_weekday = [calendar.day_abbr[i] for i in range(7)] f_weekday = [calendar.day_name[i] for i in range(7)] if not self.__a_weekday: self.__a_weekday = a_weekday if not self.__f_weekday: self.__f_weekday = f_weekday def __calc_month(self): # Set self.__f_month and self.__a_month using the calendar module. a_month = [calendar.month_abbr[i] for i in range(13)] f_month = [calendar.month_name[i] for i in range(13)] if not self.__a_month: self.__a_month = a_month if not self.__f_month: self.__f_month = f_month def __calc_am_pm(self): # Set self.__am_pm by using time.strftime(). # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that # magical; just happened to have used it everywhere else where a # static date was needed. am_pm = [] for hour in (01,22): time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0)) am_pm.append(time.strftime("%p", time_tuple)) self.__am_pm = am_pm def __calc_date_time(self): # Set self.__date_time, self.__date, & self.__time by using # time.strftime(). # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of # overloaded numbers is minimized. The order in which searches for # values within the format string is very important; it eliminates # possible ambiguity for what something represents. time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0)) date_time = [None, None, None] date_time[0] = time.strftime("%c", time_tuple) date_time[1] = time.strftime("%x", time_tuple) date_time[2] = time.strftime("%X", time_tuple) for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')): current_format = date_time[offset] for old, new in ( ('%', '%%'), (self.f_weekday[2], '%A'), (self.f_month[3], '%B'), (self.a_weekday[2], '%a'), (self.a_month[3], '%b'), (self.am_pm[1], '%p'), (self.timezone[0], '%Z'), (self.timezone[1], '%Z'), ('1999', '%Y'), ('99', '%y'), ('22', '%H'), ('44', '%M'), ('55', '%S'), ('76', '%j'), ('17', '%d'), ('03', '%m'), ('3', '%m'), # '3' needed for when no leading zero. ('2', '%w'), ('10', '%I')): # Must deal with possible lack of locale info # manifesting itself as the empty string (e.g., Swedish's # lack of AM/PM info) or a platform returning a tuple of empty # strings (e.g., MacOS 9 having timezone as ('','')). if old: current_format = current_format.replace(old, new) time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0)) if time.strftime(directive, time_tuple).find('00'): U_W = '%U' else: U_W = '%W' date_time[offset] = current_format.replace('11', U_W) if not self.__LC_date_time: self.__LC_date_time = date_time[0] if not self.__LC_date: self.__LC_date = date_time[1] if not self.__LC_time: self.__LC_time = date_time[2] def __calc_timezone(self): # Set self.__timezone by using time.tzname. # # Empty string used for matching when timezone is not used/needed. try: time.tzset() except AttributeError: pass time_zones = ["UTC", "GMT"] if time.daylight: time_zones.extend(time.tzname) else: time_zones.append(time.tzname[0]) self.__timezone = self.__pad(time_zones, 0) class TimeRE(dict): """Handle conversion from format directives to regexes.""" def __init__(self, locale_time=None): """Init inst with non-locale regexes and store LocaleTime object.""" #XXX: Does 'Y' need to worry about having less or more than 4 digits? base = super(TimeRE, self) base.__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])", 'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])", 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", # W is set below by using 'U' 'y': r"(?P<y>\d\d)", 'Y': r"(?P<Y>\d\d\d\d)"}) base.__setitem__('W', base.__getitem__('U')) if locale_time: self.locale_time = locale_time else: self.locale_time = LocaleTime() def __getitem__(self, fetch): """Try to fetch regex; if it does not exist, construct it.""" try: return super(TimeRE, self).__getitem__(fetch) except KeyError: constructors = { 'A': lambda: self.__seqToRE(self.locale_time.f_weekday, fetch), 'a': lambda: self.__seqToRE(self.locale_time.a_weekday, fetch), 'B': lambda: self.__seqToRE(self.locale_time.f_month[1:], fetch), 'b': lambda: self.__seqToRE(self.locale_time.a_month[1:], fetch), 'c': lambda: self.pattern(self.locale_time.LC_date_time), 'p': lambda: self.__seqToRE(self.locale_time.am_pm, fetch), 'x': lambda: self.pattern(self.locale_time.LC_date), 'X': lambda: self.pattern(self.locale_time.LC_time), 'Z': lambda: self.__seqToRE(self.locale_time.timezone, fetch), '%': lambda: '%', } if fetch in constructors: self[fetch] = constructors[fetch]() return self[fetch] else: raise def __seqToRE(self, to_convert, directive): """Convert a list to a regex string for matching a directive.""" def sorter(a, b): """Sort based on length. Done in case for some strange reason that names in the locale only differ by a suffix and thus want the name with the suffix to match first. """ try: a_length = len(a) except TypeError: a_length = 0 try: b_length = len(b) except TypeError: b_length = 0 return cmp(b_length, a_length) to_convert = to_convert[:] # Don't want to change value in-place. for value in to_convert: if value != '': break else: return '' to_convert.sort(sorter) regex = '|'.join(to_convert) regex = '(?P<%s>%s' % (directive, regex) return '%s)' % regex def pattern(self, format): """Return re pattern for the format string. Need to make sure that any characters that might be interpreted as regex syntax is escaped. """ processed_format = '' # The sub() call escapes all characters that might be misconstrued # as regex syntax. regex_chars = re_compile(r"([\\.^$*+?{}\[\]|])") format = regex_chars.sub(r"\\\1", format) whitespace_replacement = re_compile('\s+') format = whitespace_replacement.sub('\s*', format) while format.find('%') != -1: directive_index = format.index('%')+1 processed_format = "%s%s%s" % (processed_format, format[:directive_index-1], self[format[directive_index]]) format = format[directive_index+1:] return "%s%s" % (processed_format, format) def compile(self, format): """Return a compiled re object for the format string.""" return re_compile(self.pattern(format), IGNORECASE) def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input data and the format string.""" time_re = TimeRE() locale_time = time_re.locale_time format_regex = time_re.compile(format) found = format_regex.match(data_string) if not found: raise ValueError("time data did not match format: data=%s fmt=%s" % (data_string, format)) if len(data_string) != found.end(): raise ValueError("unconverted data remains: %s" % data_string[found.end():]) year = 1900 month = day = 1 hour = minute = second = 0 tz = -1 # weekday and julian defaulted to -1 so as to signal need to calculate values weekday = julian = -1 found_dict = found.groupdict() for group_key in found_dict.iterkeys(): if group_key == 'y': year = int(found_dict['y']) # Open Group specification for strptime() states that a %y #value in the range of [00, 68] is in the century 2000, while #[69,99] is in the century 1900 if year <= 68: year += 2000 else: year += 1900 elif group_key == 'Y': year = int(found_dict['Y']) elif group_key == 'm': month = int(found_dict['m']) elif group_key == 'B': month = _insensitiveindex(locale_time.f_month, found_dict['B']) elif group_key == 'b': month = _insensitiveindex(locale_time.a_month, found_dict['b']) elif group_key == 'd': day = int(found_dict['d']) elif group_key == 'H': hour = int(found_dict['H']) elif group_key == 'I': hour = int(found_dict['I']) ampm = found_dict.get('p', '').lower() # If there was no AM/PM indicator, we'll treat this like AM if ampm in ('', locale_time.am_pm[0].lower()): # We're in AM so the hour is correct unless we're # looking at 12 midnight. # 12 midnight == 12 AM == hour 0 if hour == 12: hour = 0 elif ampm == locale_time.am_pm[1].lower(): # We're in PM so we need to add 12 to the hour unless # we're looking at 12 noon. # 12 noon == 12 PM == hour 12 if hour != 12: hour += 12 elif group_key == 'M': minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) elif group_key == 'A': weekday = _insensitiveindex(locale_time.f_weekday, found_dict['A']) elif group_key == 'a': weekday = _insensitiveindex(locale_time.a_weekday, found_dict['a']) elif group_key == 'w': weekday = int(found_dict['w']) if weekday == 0: weekday = 6 else: weekday -= 1 elif group_key == 'j': julian = int(found_dict['j']) elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if # it can be something other than -1. found_zone = found_dict['Z'].lower() if locale_time.timezone[0] == locale_time.timezone[1] and \ time.daylight: pass #Deals with bad locale setup where timezone info is # the same; first found on FreeBSD 4.4. elif found_zone in ("utc", "gmt"): tz = 0 elif locale_time.timezone[2].lower() == found_zone: tz = 0 elif time.daylight and \ locale_time.timezone[3].lower() == found_zone: tz = 1 # Cannot pre-calculate datetime_date() since can change in Julian #calculation and thus could have different value for the day of the week #calculation if julian == -1: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will #be accurate datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month day = datetime_result.day if weekday == -1: weekday = datetime_date(year, month, day).weekday() return time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz)) def _insensitiveindex(lst, findme): # Perform a case-insensitive index search. #XXX <bc>: If LocaleTime is not exposed, then consider removing this and # just lowercase when LocaleTime sets its vars and lowercasing # search values. findme = findme.lower() for key in range(len(lst)): if lst[key].lower() == findme: return key else: raise ValueError("value not in list") |
From: <dav...@us...> - 2003-09-25 17:37:03
|
Update of /cvsroot/jtoolkit/jToolkit/web In directory sc8-pr-cvs1:/tmp/cvs-serv11292/web Modified Files: __init__.py safeapache.py server.py session.py Log Message: hate to do this, but a simple update of all the files from sjsoft for the meantime... Index: __init__.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/web/__init__.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** __init__.py 25 Aug 2003 12:16:45 -0000 1.2 --- __init__.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 26,33 **** --- 26,47 ---- servers = {} + import os, thread, time + logfilename = 'C:\\Temp\\threads.log' + + def logtime(message): + osid = os.getpid() + threadid = thread.get_ident() + t = time.time() + ms = int((t - int(t))*1000.0) + timestr = time.strftime('%Y-%m-%d %H:%M:%S') + '.%03d' % ms + f = open(logfilename, 'a') + f.write('%s: pid %r tid %r: %s\n' % (timestr, osid, threadid, message)) + f.close() + # handler is in here so that we can say PythonHandler jToolkit.web # (modpython automatically looks for handler in that module) def handler(req): """the standard handler which locates the instance, creates the server if neccessary, and hands off to it""" + logtime('handler start: ' + req.uri) apache_options = req.get_options() modulename = apache_options['jToolkit.module'] *************** *** 46,50 **** servers[fullinstancename] = server pathwords = filter(None, req.uri.split('/')) # split into bits, strip out empty strings thepage = server.handle(req, pathwords) ! return server.sendpage(req, thepage) --- 60,68 ---- servers[fullinstancename] = server pathwords = filter(None, req.uri.split('/')) # split into bits, strip out empty strings + logtime('calling server.handle: ' + req.uri) thepage = server.handle(req, pathwords) ! logtime('calling server.sendpage: ' + req.uri) ! result = server.sendpage(req, thepage) ! logtime('done: ' + req.uri) ! return result Index: safeapache.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/web/safeapache.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** safeapache.py 25 Aug 2003 12:16:45 -0000 1.2 --- safeapache.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 53,73 **** # fakereq is useful for testing in Python interpreter fakereq = FakeRequest() - util = FakeUtil() - apache = FakeApache() try: from mod_python import apache except: ! print "Can't import mod_python.apache; possibly not running within apache" ! e = sys.exc_info() ! print e[0], e[1] ! print "Simulating fake connection: this will not work on the web server" ! print try: from mod_python import util # for FieldStorage class except: ! print "Can't import mod_python.util; possibly not running within apache" ! e = sys.exc_info() ! print e[0], e[1] ! print --- 53,65 ---- # fakereq is useful for testing in Python interpreter fakereq = FakeRequest() try: from mod_python import apache except: ! apache = FakeApache() ! try: from mod_python import util # for FieldStorage class except: ! util = FakeUtil() Index: server.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/web/server.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** server.py 25 Aug 2003 12:16:45 -0000 1.2 --- server.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 150,181 **** class AppServer(object): """base class for AppServers... handles requests. need to define getpage in subclass""" ! def __init__(self, instance, sessioncache, errorhandler=None, loginpageclass=LoginPage): """constructs a Server for a given instance, using the given session cache and error handler""" self.instance = instance ! self.sessioncache = sessioncache if errorhandler is None: self.errorhandler = errors.ErrorHandler(instance) else: self.errorhandler = errorhandler - if not hasattr(self.instance, 'db'): - self.instance.db = database.dbwrapper(instance, self.errorhandler) - if not hasattr(self.instance, 'checkshift'): - self.instance.checkshift = self.checkshift - self.loginpageclass = loginpageclass self.languagelist = localize.getinstalledlanguages(self.instance.localedir) self.languagenames = localize.getlanguagenames(self.languagelist) self.translation = localize.translation(self.instance.localedomains, self.instance.localedir, self.languagelist) ! self.defaultlanguage = self.languagelist[0] def handle(self, req, pathwords): """handles the request and returns a page object in response""" argdict = self.processargs(self.instance, req) ! session = self.checklogin(req, argdict) ! if session.isopen: ! session.pagecount += 1 ! session.remote_ip = req.connection.remote_ip ! return self.getpage(pathwords, session, argdict) ! else: ! return self.loginpageclass(session, argdict, languagenames=self.languagenames) def sendpage(self, req, thepage): --- 150,184 ---- class AppServer(object): """base class for AppServers... handles requests. need to define getpage in subclass""" ! def __init__(self, instance, sessioncache=None, errorhandler=None): """constructs a Server for a given instance, using the given session cache and error handler""" self.instance = instance ! if sessioncache is None: ! self.sessioncache = session.SessionCache() ! else: ! self.sessioncache = sessioncache if errorhandler is None: self.errorhandler = errors.ErrorHandler(instance) else: self.errorhandler = errorhandler self.languagelist = localize.getinstalledlanguages(self.instance.localedir) self.languagenames = localize.getlanguagenames(self.languagelist) self.translation = localize.translation(self.instance.localedomains, self.instance.localedir, self.languagelist) ! if hasattr(self.instance, 'defaultlanguage'): ! self.defaultlanguage = self.instance.defaultlanguage ! else: ! self.defaultlanguage = localize.getdefaultlanguage(self.languagelist) def handle(self, req, pathwords): """handles the request and returns a page object in response""" argdict = self.processargs(self.instance, req) ! session = self.getsession(req, argdict) ! session.pagecount += 1 ! session.remote_ip = req.connection.remote_ip ! return self.getpage(pathwords, session, argdict) ! ! def getsession(self, req, argdict): ! """gets the session for the request""" ! session = self.sessioncache.getsession(req,self) ! return session def sendpage(self, req, thepage): *************** *** 190,194 **** # return the html response (whether customized or standard) req.send_http_header() ! req.write(response) return safeapache.apache.OK elif isinstance(thepage, Redirect): --- 193,201 ---- # return the html response (whether customized or standard) req.send_http_header() ! if type(response) == unicode: ! # TODO: get encoding from http request... ! req.write(response.encode('iso8859')) ! else: ! req.write(response) return safeapache.apache.OK elif isinstance(thepage, Redirect): *************** *** 213,224 **** if type(value) == list: # this only happens with multiple arguments, which we don't want ! return value[0] elif hasattr(value, 'value'): # this is for a StringField from mod_python 3... ! return value.value else: ! return value ! def checklogin(self, req, argdict): """checks login. if valid, return the requested page, otherwise return the login page""" islogin = argdict.get("islogin",0) --- 220,279 ---- if type(value) == list: # this only happens with multiple arguments, which we don't want ! value = value[0] elif hasattr(value, 'value'): # this is for a StringField from mod_python 3... ! value = value.value ! if type(value) == str: ! return value.decode('iso8859') ! return value ! def gettranslation(self, language): ! """returns a translation object for the given language (or default if language is None)""" ! if language is None: ! return self.translation else: ! languagelist = [language] + self.languagelist ! return localize.translation(self.instance.localedomains, self.instance.localedir, languagelist) ! def localize(self, message): ! """returns the localized form of a message""" ! # this is used when no session is available ! return self.translation.gettext(message) ! ! def initsession(self, session): ! """takes a new session and adds attributes we need""" ! pass ! ! class DBAppServer(AppServer): ! """basic App Server that also handles connection to the database...""" ! def __init__(self, instance, sessioncache=None, errorhandler=None): ! """constructs a Server for a given instance, using the given session cache and error handler""" ! super(DBAppServer, self).__init__(instance, sessioncache, errorhandler) ! self.instance = instance ! if not hasattr(self.instance, 'db'): ! self.instance.db = database.dbwrapper(instance, self.errorhandler) ! ! class LoginAppServer(DBAppServer): ! """AppServer that includes a login facility""" ! def __init__(self, instance, sessioncache=None, errorhandler=None, loginpageclass=LoginPage): ! """constructs a Server for a given instance, using the given session cache and error handler""" ! if sessioncache is None: ! sessioncache = session.SessionCache(sessionclass=session.LoginSession) ! super(LoginAppServer, self).__init__(instance, sessioncache, errorhandler) ! if not hasattr(self.instance, 'checkshift'): ! self.instance.checkshift = self.checkshift ! self.loginpageclass = loginpageclass ! ! def handle(self, req, pathwords): ! """handles the request and returns a page object in response""" ! argdict = self.processargs(self.instance, req) ! session = self.getsession(req, argdict) ! if session.isopen: ! session.pagecount += 1 ! session.remote_ip = req.connection.remote_ip ! return self.getpage(pathwords, session, argdict) ! else: ! return self.loginpageclass(session, argdict, languagenames=self.languagenames) ! ! def getsession(self, req, argdict): """checks login. if valid, return the requested page, otherwise return the login page""" islogin = argdict.get("islogin",0) *************** *** 240,261 **** return 1 ! def initsession(self, session): ! """takes a new session and adds attributes we need""" ! pass ! ! def gettranslation(self, language): ! """returns a translation object for the given language (or default if language is None)""" ! if language is None: ! return self.translation ! else: ! languagelist = [language] + self.languagelist ! return localize.translation(self.instance.localedomains, self.instance.localedir, languagelist) ! ! def localize(self, message): ! """returns the localized form of a message""" ! # this is used when no session is available ! return self.translation.gettext(message) ! ! class MultiAppServer(AppServer): """serves multiple instances in subdirectories...""" def __init__(self, instance, sessioncache=None, errorhandler=None, loginpageclass=LoginPage): --- 295,299 ---- return 1 ! class MultiAppServer(LoginAppServer): """serves multiple instances in subdirectories...""" def __init__(self, instance, sessioncache=None, errorhandler=None, loginpageclass=LoginPage): *************** *** 325,329 **** return widgets.Page(session.localize("Select Application"), links) ! class SharedLoginAppServer(AppServer): """allows instance to be passed a shared session...""" def handle(self, req, pathwords, sharedsession=None): --- 363,367 ---- return widgets.Page(session.localize("Select Application"), links) ! class SharedLoginAppServer(LoginAppServer): """allows instance to be passed a shared session...""" def handle(self, req, pathwords, sharedsession=None): *************** *** 331,335 **** argdict = self.processargs(self.instance, req) exitapp = argdict.get('exitapp', 0) ! session = self.checklogin(req, argdict, sharedsession) if exitapp: return Redirect("../index.html") --- 369,373 ---- argdict = self.processargs(self.instance, req) exitapp = argdict.get('exitapp', 0) ! session = self.getsession(req, argdict, sharedsession) if exitapp: return Redirect("../index.html") *************** *** 341,345 **** return self.loginpageclass(session, argdict, languagenames=self.languagenames) ! def checklogin(self, req, argdict, sharedsession): """checks login. if valid, return the requested page, otherwise return the login page""" islogin = argdict.get("islogin",0) --- 379,383 ---- return self.loginpageclass(session, argdict, languagenames=self.languagenames) ! def getsession(self, req, argdict, sharedsession): """checks login. if valid, return the requested page, otherwise return the login page""" islogin = argdict.get("islogin",0) *************** *** 347,351 **** islogout = argdict.get("islogout",0) manualmode = islogin or confirmlogin or islogout ! session = super(SharedLoginAppServer, self).checklogin(req, argdict) if not (manualmode or session.isopen) and sharedsession is not None and sharedsession.isopen: sharedsession.sharelogindetails(req, session) --- 385,389 ---- islogout = argdict.get("islogout",0) manualmode = islogin or confirmlogin or islogout ! session = super(SharedLoginAppServer, self).getsession(req, argdict) if not (manualmode or session.isopen) and sharedsession is not None and sharedsession.isopen: sharedsession.sharelogindetails(req, session) *************** *** 358,362 **** """constructs the multi-app server""" if sessioncache is None: ! sessioncache = session.SessionCache(sessioncookiename=instance.__name__+'session') super(SharedLoginMultiAppServer, self).__init__(instance, sessioncache, errorhandler, loginpageclass) self.instances = self.instance.instances --- 396,400 ---- """constructs the multi-app server""" if sessioncache is None: ! sessioncache = session.SessionCache(sessionclass=LoginSession,sessioncookiename=instance.__name__+'session') super(SharedLoginMultiAppServer, self).__init__(instance, sessioncache, errorhandler, loginpageclass) self.instances = self.instance.instances *************** *** 385,389 **** else: argdict = self.processargs(self.instance, req) ! session = self.checklogin(req, argdict) if session.isopen: session.pagecount += 1 --- 423,427 ---- else: argdict = self.processargs(self.instance, req) ! session = self.getsession(req, argdict) if session.isopen: session.pagecount += 1 *************** *** 403,410 **** return widgets.Page(session.localize("Select Application"), [status, links]) ! def checklogin(self, req, argdict): """checks login. if valid, return the requested page, otherwise return the login page""" islogin = argdict.get("islogin",0) ! session = super(SharedLoginMultiAppServer, self).checklogin(req, argdict) # remember the password so we can give it to other sessions... if islogin and session.isopen: --- 441,448 ---- return widgets.Page(session.localize("Select Application"), [status, links]) ! def getsession(self, req, argdict): """checks login. if valid, return the requested page, otherwise return the login page""" islogin = argdict.get("islogin",0) ! session = super(SharedLoginMultiAppServer, self).getsession(req, argdict) # remember the password so we can give it to other sessions... if islogin and session.isopen: *************** *** 422,427 **** if pathwords[0] in self.instances: session = self.sessioncache.getsession(req, self) ! if session.isopen: ! return self.handledefer(req, pathwords, session) else: return None --- 460,464 ---- if pathwords[0] in self.instances: session = self.sessioncache.getsession(req, self) ! return self.handledefer(req, pathwords, session) else: return None *************** *** 429,433 **** argdict = self.processargs(self.instance, req) exitapp = argdict.get('exitapp', 0) ! session = self.checklogin(req, argdict, sharedsession) if exitapp: return Redirect("../index.html") --- 466,470 ---- argdict = self.processargs(self.instance, req) exitapp = argdict.get('exitapp', 0) ! session = self.getsession(req, argdict, sharedsession) if exitapp: return Redirect("../index.html") Index: session.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/web/session.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** session.py 25 Aug 2003 12:16:45 -0000 1.2 --- session.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 139,143 **** self.setcookie(req, cookiedict) ! class Session: """represents a user session""" def __init__(self, sessioncache, server, sessionstring = None): --- 139,143 ---- self.setcookie(req, cookiedict) ! class Session(object): """represents a user session""" def __init__(self, sessioncache, server, sessionstring = None): *************** *** 145,149 **** self.server = server self.instance = server.instance - self.db = server.instance.db self.parentsessionname = "" self.childsessions = {} --- 145,148 ---- *************** *** 158,168 **** # allow the server to add any attributes it requires server.initsession(self) ! if sessionstring is not None: ! # split up the sessionstring into components ! if sessionstring.count(':') >= 3: ! self.username,self.timestamp,self.sessionid,self.parentsessionname = sessionstring.split(':',3) ! # make sure this is valid, and open it... ! self.validate() ! self.open() def getstatus(self): --- 157,161 ---- # allow the server to add any attributes it requires server.initsession(self) ! self.setsessionstring(sessionstring) def getstatus(self): *************** *** 216,220 **** """check the login status (auto logoff etc)""" if self.isopen: ! self.status = self.localize("logged in as <b>%s</b>") % (self.username) self.updatelastused() --- 209,213 ---- """check the login status (auto logoff etc)""" if self.isopen: ! self.status = self.localize("connected") self.updatelastused() *************** *** 223,236 **** return dates.nosepdateparser.parse(self.timestamp) - def getsessionid(self, password): - """returns the hex sessionid for the session, using the password""" - md5password = md5hexdigest(password) - return md5hexdigest(self.username+':'+self.timestamp+':'+md5password+':'+self.instance.sessionkey+':'+self.server.name) - def getsessionstring(self): """creates the full session string using the sessionid""" ! sessionstring = self.username+':'+self.timestamp+':'+self.sessionid+':'+self.parentsessionname return sessionstring def updatecookie(self, req, server): """update session string in cookie in req to reflect whether session is open""" --- 216,234 ---- return dates.nosepdateparser.parse(self.timestamp) def getsessionstring(self): """creates the full session string using the sessionid""" ! sessionstring = self.timestamp+':'+self.sessionid return sessionstring + def setsessionstring(self, sessionstring): + """sets the session string for this session""" + if sessionstring is not None: + # split up the sessionstring into components + if sessionstring.count(':') >= 1: + self.timestamp,self.sessionid = sessionstring.split(':',1) + # make sure this is valid, and open it... + self.validate() + self.open() + def updatecookie(self, req, server): """update session string in cookie in req to reflect whether session is open""" *************** *** 239,276 **** else: self.sessioncache.setsessioncookie(req, server, '-') - - def create(self,username,password,timestamp,language): - """initializes the session with the parameters""" - self.username, password, self.timestamp = username.lower(), password.lower(), timestamp - self.setlanguage(language) - self.sessionid = self.getsessionid(password) - self.validate() - self.open() - - def sharelogindetails(self, req, othersession): - """shares this session's login details with othersession""" - username = self.username - # this expects that self.password exist ... see SharedLoginMultiAppServer.checklogin... - password = getattr(self, 'password', '') - language = self.language - timestamp = dates.currentdate().Format('%Y%m%d%H%M%S') - # currently assumes we do not need to close the other session - otherusername = getattr(othersession, 'username', '') - othersession.parentsessionname = self.server.name - othersession.create(username, password, timestamp, language) - if othersession.isopen: - othersession.updatecookie(req, othersession.server) - self.childsessions[othersession.server.name] = othersession - else: - othersession.close(req) - othersession.parentsessionname = "" - othersession.username = otherusername - othersession.status = "" - - def invalidatechild(self, childname): - """logs out of a child session""" - childsession = self.childsessions.get(childname, 0) - if childsession: - childsession.markinvalid() def markinvalid(self): --- 237,240 ---- *************** *** 283,303 **** self.isopen = 0 ! def confirmlogin(self, req, username, password, timestamp): ! """validates a username and password for an already-established session""" ! username, password = username.lower(), password.lower() ! if not self.isvalid: ! # create a new session ! self.create(username, password, timestamp, self.language) ! if self.isopen: ! self.updatecookie(req, self.server) else: ! # validate the old session... ! if username != self.username: ! self.close(req) ! self.status = self.localize("failed login confirmation") ! self.sessionid = self.getsessionid(password) ! if not self.validate(): ! self.close(req) ! self.status = self.localize("failed login confirmation") def validate(self): --- 247,291 ---- self.isopen = 0 ! def validate(self): ! """checks if this session is valid""" ! self.isvalid = 1 ! return 1 ! ! def checksessionid(self): ! """returns the hex sessionid for the session, using the password""" ! correctsessionid = self.timestamp+':'+md5hexdigest(self.timestamp) ! return correctsessionid == self.sessionid ! ! def setlanguage(self, language): ! """sets the language for the session""" ! if language is None: ! self.language = self.server.defaultlanguage else: ! self.language = language ! self.translation = self.server.gettranslation(self.language) ! ! def localize(self, message): ! """returns the localized form of a message""" ! return self.translation.gettext(message) ! ! class LoginSession(Session): ! """A session that allows login based on a database""" ! def __init__(self, sessioncache, server, sessionstring = None): ! self.db = server.instance.db ! super(LoginSession, self).__init__(sessioncache, server, sessionstring) ! ! def open(self): ! """tries to open the given session, returns success""" ! self.isopen = 0 ! super(LoginSession, self).open() ! if self.isopen: ! self.status = self.localize("logged in as <b>%s</b>") % self.username ! return self.isopen ! ! def checkstatus(self, req): ! """check the login status (auto logoff etc)""" ! if self.isopen: ! self.status = self.localize("logged in as <b>%s</b>") % (self.username) ! self.updatelastused() def validate(self): *************** *** 313,316 **** --- 301,309 ---- return self.isvalid + def getsessionid(self, password): + """returns the hex sessionid for the session, using the password""" + md5password = md5hexdigest(password) + return md5hexdigest(self.username+':'+self.timestamp+':'+md5password+':'+self.instance.sessionkey+':'+self.server.name) + def checksessionid(self): """returns the hex sessionid for the session, using the password""" *************** *** 320,323 **** --- 313,332 ---- return correctsessionid == self.sessionid + def getsessionstring(self): + """creates the full session string using the sessionid""" + sessionstring = self.username+':'+self.timestamp+':'+self.sessionid+':'+self.parentsessionname + return sessionstring + + def setsessionstring(self, sessionstring): + """sets the session string for this session""" + # split up the sessionstring into components + if sessionstring is not None: + # split up the sessionstring into components + if sessionstring.count(':') >= 3: + self.username,self.timestamp,self.sessionid,self.parentsessionname = sessionstring.split(':',3) + # make sure this is valid, and open it... + self.validate() + self.open() + def getmd5password(self, username=None): """retrieves the md5 hash of the password for this user, or another if another is given...""" *************** *** 344,359 **** count = int(q.fetchone()[0]) return count > 0 ! def setlanguage(self, language): ! """sets the language for the session""" ! if language is None: ! self.language = self.server.defaultlanguage else: ! self.language = language ! self.translation = self.server.gettranslation(language) ! def localize(self, message): ! """returns the localized form of a message""" ! return self.translation.gettext(message) --- 353,407 ---- count = int(q.fetchone()[0]) return count > 0 + + def create(self,username,password,timestamp,language): + """initializes the session with the parameters""" + self.username, password, self.timestamp = username.lower(), password.lower(), timestamp + self.setlanguage(language) + self.sessionid = self.getsessionid(password) + self.validate() + self.open() ! def sharelogindetails(self, req, othersession): ! """shares this session's login details with othersession""" ! username = self.username ! # this expects that self.password exist ... see SharedLoginMultiAppServer.checklogin... ! password = getattr(self, 'password', '') ! language = self.language ! timestamp = dates.currentdate().Format('%Y%m%d%H%M%S') ! # currently assumes we do not need to close the other session ! otherusername = getattr(othersession, 'username', '') ! othersession.parentsessionname = self.server.name ! othersession.create(username, password, timestamp, language) ! if othersession.isopen: ! othersession.updatecookie(req, othersession.server) ! self.childsessions[othersession.server.name] = othersession else: ! othersession.close(req) ! othersession.parentsessionname = "" ! othersession.username = otherusername ! othersession.status = "" ! def invalidatechild(self, childname): ! """logs out of a child session""" ! childsession = self.childsessions.get(childname, 0) ! if childsession: ! childsession.markinvalid() + def confirmlogin(self, req, username, password, timestamp): + """validates a username and password for an already-established session""" + username, password = username.lower(), password.lower() + if not self.isvalid: + # create a new session + self.create(username, password, timestamp, self.language) + if self.isopen: + self.updatecookie(req, self.server) + else: + # validate the old session... + if username != self.username: + self.close(req) + self.status = self.localize("failed login confirmation") + self.sessionid = self.getsessionid(password) + if not self.validate(): + self.close(req) + self.status = self.localize("failed login confirmation") |
From: <dav...@us...> - 2003-09-25 17:37:00
|
Update of /cvsroot/jtoolkit/jToolkit/data In directory sc8-pr-cvs1:/tmp/cvs-serv11292/data Modified Files: __init__.py database.py dates.py dbtable.py Log Message: hate to do this, but a simple update of all the files from sjsoft for the meantime... Index: __init__.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/data/__init__.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** __init__.py 25 Aug 2003 12:16:45 -0000 1.2 --- __init__.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 20,23 **** # list of modules in this package ! __all__ = ["ADOProviders","ADOTypes","PyADO","database","dates"] --- 20,23 ---- # list of modules in this package ! __all__ = ["ADOProviders","ADOTypes","PyADO","database","dates","jsuite"] Index: database.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/data/database.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** database.py 25 Aug 2003 12:16:45 -0000 1.2 --- database.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 112,115 **** --- 112,118 ---- def importdriver(self): + if self.DBTYPE == 'oracle' and hasattr(self.instance, 'NLS_LANG'): + import os + os.environ['NLS_LANG'] = self.instance.NLS_LANG if self.DBTYPE in ('access', 'oracle', 'sqlserver'): self.driver, self.dberror = importPyADO() *************** *** 169,172 **** --- 172,182 ---- raise + def getaddcolumnsql(self, tablename, columnname, columntype): + """returns the sql required to add a column of the given name and type to a table""" + if self.DBTYPE == 'access': + return "alter table %s add column %s %s" % (tablename, columnname, self.dbtypename(columntype)) + else: + return "alter table %s add %s %s" % (tablename, columnname, self.dbtypename(columntype)) + def dblowerfn(self): """return a function that converts text to lower case""" *************** *** 199,221 **** raise ValueError, "unknown database type %r in dblowerfn" % (self.DBTYPE) - def dbreprstr(self, value): - dbvalue = "" - for ch in value: - chnum = ord(ch) - if (chnum >= 32 and chnum < 128) or chnum in (9,10,13): - dbvalue += ch - else: - # TODO: store them like following, then convert them when reading back... - # dbvalue += "\\x%x" % chnum - dbvalue += "-" - return dbvalue - def dbrepr(self, value, formattype = None): # currently, the griddisplayformat is used to format datetimestrings in logtable. It should NOT be #configured on string or text objects in categoryconf. ! if formattype is None: formattype = '' if value is None: return 'null' ! if (type(value) == str or type(value) == unicode) and formattype in dates.dateparsers: value = dates.parsedate(value, formattype) return dates.dbdatestring(value, self.DBTYPE) --- 209,219 ---- raise ValueError, "unknown database type %r in dblowerfn" % (self.DBTYPE) def dbrepr(self, value, formattype = None): # currently, the griddisplayformat is used to format datetimestrings in logtable. It should NOT be #configured on string or text objects in categoryconf. ! if formattype is None or formattype == 'None': formattype = '' if value is None: return 'null' ! if (type(value) == str or type(value) == unicode) and formattype.lower() not in ('', 'attachment'): value = dates.parsedate(value, formattype) return dates.dbdatestring(value, self.DBTYPE) *************** *** 226,232 **** # we know how to deal with basic strings... elif type(value) == str: ! return "'" + self.dbreprstr(value.replace("'","''")) + "'" elif type(value) == unicode: ! return "'" + self.dbreprstr(value.replace("'","''")) + "'" # we know how to deal with certain objects elif type(value) == types.InstanceType: --- 224,230 ---- # we know how to deal with basic strings... elif type(value) == str: ! return "'" + value.replace("'","''") + "'" elif type(value) == unicode: ! return "'" + value.replace("'","''") + "'" # we know how to deal with certain objects elif type(value) == types.InstanceType: *************** *** 348,352 **** cachedrow, description = self.singlerowcache.get(sql, (None, None)) if cachedrow is not None: - self.errorhandler.logtrace("using singlerowcache for "+sql) if withdescription: return cachedrow, description --- 346,349 ---- *************** *** 371,375 **** cachedrows, description = self.allrowscache.get(sql, (None, None)) if cachedrows is not None: - self.errorhandler.logtrace("using allrowscache for "+sql) if withdescription: return cachedrows, description --- 368,371 ---- Index: dates.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/data/dates.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** dates.py 25 Aug 2003 12:16:45 -0000 1.2 --- dates.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 22,25 **** --- 22,38 ---- from jToolkit import cidict import sre + import time + + # we have copied _strptime from Python2.3 so that it can be used in earlier versions + if not hasattr(time, 'strptime'): + from jToolkit.data import _strptime + time.strptime = _strptime.strptime + + # pywintypes has an error in time formatting, so we need to be able to detect this type on windows + try: + import pywintypes + errortimetype = pywintypes.TimeType + except ImportError: + errortimetype = None date = mxDateTime.DateTime *************** *** 134,153 **** def parsedate(value, formattype): """parses a date/time string of the given type, returns a datetime object""" ! parser = dateparsers.get(formattype, dateparsers['GENERAL DATE']) ! if type(value) in (str,unicode): ! value = parser.parse(value) ! # elif type(value).__name__ == 'time': ! else: raise ValueError, "unexpected type in parsedate: %r, %r" % (value, type(value)) ! return value def formatdate(value, formattype): """formats a date/time object of the given type, returns a string""" ! dateformat = dateformats.get(formattype, dateformats['GENERAL DATE']) if hasattr(value,'Format'): return value.Format(dateformat) # handle null values elif value is None or value == '': return '' else: raise ValueError, "unexpected type in formatdate: %r, %r" % (value, type(value)) --- 147,183 ---- def parsedate(value, formattype): """parses a date/time string of the given type, returns a datetime object""" ! if type(value) not in (str,unicode): raise ValueError, "unexpected type in parsedate: %r, %r" % (value, type(value)) ! try: ! # we still want to support things like 'GENERAL DATE' for now ! # TODO: remove 'GENERAL DATE' support once people have upgraded ! if formattype in dateformats: ! timevalue = time.strptime(value, dateformats[formattype]) ! else: ! timevalue = time.strptime(value, formattype) ! return apply(date, timevalue[:6]) ! except ValueError: ! parser = dateparsers.get(formattype, dateparsers['GENERAL DATE']) ! return parser.parse(value) def formatdate(value, formattype): """formats a date/time object of the given type, returns a string""" ! # we still want to support things like 'GENERAL DATE' for now ! # TODO: remove 'GENERAL DATE' support once people have upgraded ! if formattype in dateformats: ! dateformat = dateformats[formattype] ! else: ! dateformat = formattype if hasattr(value,'Format'): + # this is to correct an error in PyTime.Format (always displays weekday as Sunday) + # TODO: remove this if the error is fixed + if type(value) == errortimetype: + value = mxDateTime.DateTime(value.year, value.month, value.day, value.hour, value.minute, value.second) return value.Format(dateformat) # handle null values elif value is None or value == '': return '' + elif type(value) == tuple: + return time.strftime(dateformat, value) else: raise ValueError, "unexpected type in formatdate: %r, %r" % (value, type(value)) Index: dbtable.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/data/dbtable.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** dbtable.py 25 Aug 2003 12:16:45 -0000 1.2 --- dbtable.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 23,27 **** from jToolkit import cidict ! class DBTable: """DBTable is an abstraction of a table and its related data""" def __init__(self, db, tablename, columnlist, rowidcols, orderbycols): --- 23,27 ---- from jToolkit import cidict ! class DBTable(object): """DBTable is an abstraction of a table and its related data""" def __init__(self, db, tablename, columnlist, rowidcols, orderbycols): |
From: <dav...@us...> - 2003-09-25 17:36:59
|
Update of /cvsroot/jtoolkit/jToolkit/widgets In directory sc8-pr-cvs1:/tmp/cvs-serv11292/widgets Modified Files: grid.py table.py widgets.py Log Message: hate to do this, but a simple update of all the files from sjsoft for the meantime... Index: grid.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/widgets/grid.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** grid.py 25 Aug 2003 12:16:45 -0000 1.2 --- grid.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 68,72 **** contents = text else: ! contents = widgets.Link(href, text, {'target':hreftarget}) return table.TableCell(contents, newattribs={'valign':'top','style':style}) --- 68,72 ---- contents = text else: ! contents = widgets.Link(href, widgets.Font(text, newattribs={'style':style}), {'target':hreftarget}) return table.TableCell(contents, newattribs={'valign':'top','style':style}) Index: table.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/widgets/table.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** table.py 25 Aug 2003 12:16:45 -0000 1.2 --- table.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 89,93 **** def minrownum(self): ! return min(self.rowsdict.keys()) def maxrownum(self): --- 89,93 ---- def minrownum(self): ! return min(self.rowsdict.iterkeys()) def maxrownum(self): *************** *** 98,105 **** def mincolnum(self): ! return min([min(row.keys()) for row in self.rowsdict.values()]) def maxcolnum(self): ! return max([self.rowmaxcolnum(row) for row in self.rowsdict.values()]) def colrange(self): --- 98,105 ---- def mincolnum(self): ! return min([min(row.iterkeys()) for row in self.rowsdict.itervalues()]) def maxcolnum(self): ! return max([self.rowmaxcolnum(row) for row in self.rowsdict.itervalues()]) def colrange(self): *************** *** 248,254 **** def rowwidth(self, rownum): width = 0 ! for cell in self.getrow(rownum).values(): ! if hasattr(cell,'width'): ! width += cell.width return width --- 248,253 ---- def rowwidth(self, rownum): width = 0 ! for cell in self.getrow(rownum).itervalues(): ! width += getattr(cell, 'width', 0) return width *************** *** 258,266 **** def calcweights(self): # calculate column widths for all the cells for rownum in self.rowrange(): for colnum in self.colrange(): cell = self.getcell(rownum, colnum) if cell.width != 0: ! width=100.0*cell.width/self.maxwidth() styleattribs = {'width':'%d%%' % int(width)} cell.overrideattribs({'style':styleattribs}) --- 257,266 ---- def calcweights(self): # calculate column widths for all the cells + maxwidth = self.maxwidth() for rownum in self.rowrange(): for colnum in self.colrange(): cell = self.getcell(rownum, colnum) if cell.width != 0: ! width=100.0*cell.width/maxwidth styleattribs = {'width':'%d%%' % int(width)} cell.overrideattribs({'style':styleattribs}) Index: widgets.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/widgets/widgets.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** widgets.py 25 Aug 2003 12:16:45 -0000 1.2 --- widgets.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 35,39 **** def gethtml(self): ! return "<"+self.tagname+" "+self.gethtmlattribs()+">" + self.getcontents() + "</"+self.tagname+">\r" def getcontents(self): --- 35,39 ---- def gethtml(self): ! return "<%s %s>%s</%s>\r" % (self.tagname, self.gethtmlattribs(), self.getcontents(), self.tagname) def getcontents(self): *************** *** 43,48 **** def gethtmlattribs(self): #return a string representing all the attribs in this class ! htmlattribstrs = [self.gethtmlattrib(item) for item in self.attribs.items()] ! return " ".join(htmlattribstrs) def escape(self, s, quote=None): --- 43,47 ---- def gethtmlattribs(self): #return a string representing all the attribs in this class ! return " ".join([self.gethtmlattrib(key, value) for key, value in self.attribs.iteritems()]) def escape(self, s, quote=None): *************** *** 51,63 **** s = s.replace("<", "<").replace(">", ">") if quote: ! if '"' in s: ! if "'" in s: s = '"%s"' % s.replace('"', """) ! else: s = "'%s'" % s ! else: s = '"%s"' % s return s ! def gethtmlattrib(self,item): """turns the key and value into something usable as an html attribute and value...""" - key, value = item valuetype = type(value) if valuetype == str or valuetype == unicode: --- 50,58 ---- s = s.replace("<", "<").replace(">", ">") if quote: ! s = '"' + s.replace('"', """) + '"' return s ! def gethtmlattrib(self, key, value): """turns the key and value into something usable as an html attribute and value...""" valuetype = type(value) if valuetype == str or valuetype == unicode: *************** *** 93,100 **** return contents elif type(contents) in (tuple, list): ! contentslist = [] ! for contentspart in contents: ! contentslist.append(self.getcontentshtml(contentspart)) ! return "".join(contentslist) elif hasattr(contents, "gethtml"): return contents.gethtml() --- 88,92 ---- return contents elif type(contents) in (tuple, list): ! return "".join([self.getcontentshtml(contentspart) for contentspart in contents]) elif hasattr(contents, "gethtml"): return contents.gethtml() *************** *** 124,127 **** --- 116,124 ---- return self.getcontents() + + class Font(ContentWidget): + def __init__(self, contents, newattribs={}): + ContentWidget.__init__(self, "FONT", contents, newattribs) + class Button(ContentWidget): # Represents a button widget. *************** *** 154,165 **** # Return the html for this combo. and store the result in the output string. html = "" ! for option in self.options: ! value, description = option if type(value) not in (str, unicode): value = str(value) selected = "" ! if value.lower() == self.attribs['value'].lower(): selected = " SELECTED" ! html += ' <OPTION VALUE="' + value + '"' + selected + '>' + description + ' </OPTION>\r' return html --- 151,162 ---- # Return the html for this combo. and store the result in the output string. html = "" ! selectedvalue = self.attribs['value'].lower() ! for value, description in self.options: if type(value) not in (str, unicode): value = str(value) selected = "" ! if value.lower() == selectedvalue: selected = " SELECTED" ! html += ' <OPTION VALUE="%s"%s>%s </OPTION>\r' % (value, selected, description) return html *************** *** 180,184 **** self.attribs = {'href':href} self.overrideattribs(newattribs) - self.contents = contents class Tooltip(ContentWidget): --- 177,180 ---- *************** *** 187,191 **** self.attribs = {'title':tooltip} self.overrideattribs(newattribs) - self.contents = contents class TextArea(ContentWidget): --- 183,186 ---- *************** *** 201,210 **** class Paragraph(ContentWidget): """this is a simple widgetlist wrapping some widgets in a paragraph""" ! def __init__(self, contents=[]): ! ContentWidget.__init__(self, tagname="p", contents=contents) class Page(ContentWidget): ! def __init__(self, title="", contents=[], newattribs={}): self.title = title ContentWidget.__init__(self, None, contents, newattribs) --- 196,206 ---- class Paragraph(ContentWidget): """this is a simple widgetlist wrapping some widgets in a paragraph""" ! def __init__(self, contents=[], newattribs={}): ! ContentWidget.__init__(self, tagname="p", contents=contents, newattribs=newattribs) class Page(ContentWidget): ! def __init__(self, title="", contents=[], newattribs={}, script=""): self.title = title + self.script = script ContentWidget.__init__(self, None, contents, newattribs) *************** *** 212,216 **** return self.getheader() + self.getbody() + self.getfooter() ! def getheader(self,script=""): base=self.attribs.get('base','') target=self.attribs.get('target','') --- 208,212 ---- return self.getheader() + self.getbody() + self.getfooter() ! def getheader(self): base=self.attribs.get('base','') target=self.attribs.get('target','') *************** *** 240,244 **** <BASE href="%s" target="%s">""" % (base, target) # any script required ! result += script # finished the head result += """ --- 236,240 ---- <BASE href="%s" target="%s">""" % (base, target) # any script required ! result += self.script # finished the head result += """ |
From: <dav...@us...> - 2003-09-25 17:36:59
|
Update of /cvsroot/jtoolkit/jToolkit In directory sc8-pr-cvs1:/tmp/cvs-serv11292 Modified Files: cidict.py errors.py localize.py timecache.py Log Message: hate to do this, but a simple update of all the files from sjsoft for the meantime... Index: cidict.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/cidict.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** cidict.py 25 Aug 2003 12:16:45 -0000 1.2 --- cidict.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 92,97 **** def update(self, updatedict): """D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]""" ! for key in updatedict.keys(): ! self[key] = updatedict[key] def __delitem__(self, key): --- 92,97 ---- def update(self, updatedict): """D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]""" ! for key, value in updatedict.iteritems(): ! self[key] = value def __delitem__(self, key): Index: errors.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/errors.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** errors.py 25 Aug 2003 12:16:45 -0000 1.2 --- errors.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 45,49 **** #f.write(time.asctime()+': ') f.write(time.strftime('%Y-%m-%d %H:%M:%S')+': ') ! f.write(message) f.write('\n') f.close() --- 45,52 ---- #f.write(time.asctime()+': ') f.write(time.strftime('%Y-%m-%d %H:%M:%S')+': ') ! if type(message) == unicode: ! f.write(message.encode('iso8859')) ! else: ! f.write(message) f.write('\n') f.close() *************** *** 57,61 **** def logaudit(self, msg, recorddict=None): if recorddict is not None: ! recordstr = ', '.join([key + ':' + str(value) for key, value in recorddict.iteritems()]) msg+=recordstr self.writelog(self.instance.auditfile,msg) --- 60,64 ---- def logaudit(self, msg, recorddict=None): if recorddict is not None: ! recordstr = ', '.join([key + ':' + unicode(value) for key, value in recorddict.iteritems()]) msg+=recordstr self.writelog(self.instance.auditfile,msg) Index: localize.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/localize.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** localize.py 25 Aug 2003 12:16:45 -0000 1.2 --- localize.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 23,26 **** --- 23,27 ---- import gettext + import locale import os.path from errno import ENOENT *************** *** 93,95 **** --- 94,120 ---- return ManyTranslations(translations) + def getdefaultlanguage(languagelist): + """tries to work out the default language from a list""" + def reducelocale(locale): + pos = locale.find('_') + if pos == -1: + return locale + else: + return locale[:pos] + currentlocale, currentencoding = locale.getlocale() + try: + defaultlocale, defaultencoding = locale.getdefaultlocale() + except ValueError: + defaultlocale, defaultencoding = None, None + if currentlocale is not None: + if currentlocale in languagelist: + return currentlocale + elif reducelocale(currentlocale) in languagelist: + return reducelocale(currentlocale) + if defaultlocale is not None: + if defaultlocale in languagelist: + return defaultlocale + elif reducelocale(defaultlocale) in languagelist: + return reducelocale(defaultlocale) + return languagelist[0] Index: timecache.py =================================================================== RCS file: /cvsroot/jtoolkit/jToolkit/timecache.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** timecache.py 25 Aug 2003 12:16:45 -0000 1.2 --- timecache.py 25 Sep 2003 17:36:55 -0000 1.3 *************** *** 38,44 **** def purge(self): """removes all items that are older then self.expiryperiod""" ! for key, (timestamp, value) in dict.items(self): ! if self.expired(timestamp): ! self.__delitem__(key) def __contains__(self, key): --- 38,47 ---- def purge(self): """removes all items that are older then self.expiryperiod""" ! keystodelete = [] ! for key, (timestamp, value) in dict.iteritems(self): ! if self.expired(timestamp): ! keystodelete.append(key) ! for key in keystodelete: ! self.__delitem__(key) def __contains__(self, key): *************** *** 107,111 **** def keys(self): self.purge() ! return dict.values(self) def values(self): --- 110,114 ---- def keys(self): self.purge() ! return dict.keys(self) def values(self): |
From: <dav...@us...> - 2003-09-18 16:27:57
|
Update of /cvsroot/jtoolkit/jToolkit/demo In directory sc8-pr-cvs1:/tmp/cvs-serv29953/demo Log Message: Directory /cvsroot/jtoolkit/jToolkit/demo added to the repository |
From: David F. <da...@sj...> - 2003-08-29 10:06:03
|
This is to announce that the jToolkit project has been created at sourceforge. These lists are for announcements, developer discussions, and user discussions respectively. The CVS list will contain commit messages whenever something is committed... Regards David Fraser |