rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
if not pops.has_key('type'):
|
if not props.has_key('type'):
|
def serve_file(self, designator, dre=re.compile(r'([^\d]+)(\d+)')): ''' Serve the file from the content property of the designated item. ''' m = dre.match(str(designator)) if not m: raise NotFound, str(designator) classname, nodeid = m.group(1), m.group(2)
|
if not pops.has_key('content'):
|
if not props.has_key('content'):
|
def serve_file(self, designator, dre=re.compile(r'([^\d]+)(\d+)')): ''' Serve the file from the content property of the designated item. ''' m = dre.match(str(designator)) if not m: raise NotFound, str(designator) classname, nodeid = m.group(1), m.group(2)
|
pt = Templates(self.instance.config.TEMPLATES).get(name, extension)
|
pt = templating.Templates(self.instance.config.TEMPLATES).get(name, extension)
|
def renderContext(self): ''' Return a PageTemplate for the named page ''' name = self.classname extension = self.template pt = Templates(self.instance.config.TEMPLATES).get(name, extension)
|
except NoTemplate, message:
|
except templating.NoTemplate, message:
|
def renderContext(self): ''' Return a PageTemplate for the named page ''' name = self.classname extension = self.template pt = Templates(self.instance.config.TEMPLATES).get(name, extension)
|
req = HTMLRequest(self)
|
req = templating.HTMLRequest(self)
|
def searchAction(self, wcre=re.compile(r'[\s,]+')): ''' Mangle some of the form variables.
|
class RoundupService(win32serviceutil.ServiceFramework, RoundupHTTPServer):
|
class RoundupService(win32serviceutil.ServiceFramework, BaseHTTPServer.HTTPServer):
|
def error(): exc_type, exc_value = sys.exc_info()[:2] return _('Error: %s: %s' % (exc_type, exc_value))
|
RoundupHTTPServer.__init__(self, self.address,
|
BaseHTTPServer.HTTPServer.__init__(self, self.address,
|
def __init__(self, args): # redirect stdout/stderr to our logfile if LOGFILE: # appending, unbuffered sys.stdout = sys.stderr = open(LOGFILE, 'a', 0) win32serviceutil.ServiceFramework.__init__(self, args) RoundupHTTPServer.__init__(self, self.address, RoundupRequestHandler)
|
-l: sets a filename to log to (instead of stdout)
|
-l: sets a filename to log to (instead of stderr / stdout)
|
def usage(message=''): if RoundupService: win = ''' -c: Windows Service options. If you want to run the server as a Windows Service, you must configure the rest of the options by changing the constants of this program. You will at least configure one tracker in the TRACKER_HOMES variable. This option is mutually exclusive from the rest. Typing "roundup-server -c help" shows Windows Services specifics.''' else: win = '' port=PORT print _('''%(message)s
|
httpd = RoundupHTTPServer(address, RoundupRequestHandler)
|
httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler)
|
def run(port=PORT, success_message=None): ''' Script entry point - handle args and figure out what to to. ''' # time out after a minute if we can import socket if hasattr(socket, 'setdefaulttimeout'): socket.setdefaulttimeout(60) hostname = HOSTNAME pidfile = PIDFILE logfile = LOGFILE user = ROUNDUP_USER group = ROUNDUP_GROUP svc_args = None try: # handle the command-line args options = 'n:p:u:d:l:hN' if RoundupService: options += 'c' try: optlist, args = getopt.getopt(sys.argv[1:], options) except getopt.GetoptError, e: usage(str(e)) user = ROUNDUP_USER group = None for (opt, arg) in optlist: if opt == '-n': hostname = arg elif opt == '-p': port = int(arg) elif opt == '-u': user = arg elif opt == '-g': group = arg elif opt == '-d': pidfile = os.path.abspath(arg) elif opt == '-l': logfile = os.path.abspath(arg) elif opt == '-h': usage() elif opt == '-N': RoundupRequestHandler.LOG_IPADDRESS = 0 elif opt == '-c': svc_args = [opt] + args; args = None if svc_args is not None and len(optlist) > 1: raise ValueError, _("windows service option must be the only one") if pidfile and not logfile: raise ValueError, _("logfile *must* be specified if pidfile is") # obtain server before changing user id - allows to use port < # 1024 if started as root address = (hostname, port) try: httpd = RoundupHTTPServer(address, RoundupRequestHandler) except socket.error, e: if e[0] == errno.EADDRINUSE: raise socket.error, \ _("Unable to bind to port %s, port already in use." % port) raise if group is not None and hasattr(os, 'getgid'): # if root, setgid to the running user if not os.getgid() and user is not None: try: import pwd except ImportError: raise ValueError, _("Can't change groups - no pwd module") try: gid = pwd.getpwnam(user)[3] except KeyError: raise ValueError,_("Group %(group)s doesn't exist")%locals() os.setgid(gid) elif os.getgid() and user is not None: print _('WARNING: ignoring "-g" argument, not root') if hasattr(os, 'getuid'): # if root, setuid to the running user if not os.getuid() and user is not None: try: import pwd except ImportError: raise ValueError, _("Can't change users - no pwd module") try: uid = pwd.getpwnam(user)[2] except KeyError: raise ValueError, _("User %(user)s doesn't exist")%locals() os.setuid(uid) elif os.getuid() and user is not None: print _('WARNING: ignoring "-u" argument, not root') # People can remove this check if they're really determined if not os.getuid() and user is None: raise ValueError, _("Can't run as root!") # handle tracker specs if args: d = {} for arg in args: try: name, home = arg.split('=') except ValueError: raise ValueError, _("Instances must be name=home") d[name] = os.path.abspath(home) RoundupRequestHandler.TRACKER_HOMES = d except SystemExit: raise except ValueError: usage(error()) except: print error() sys.exit(1) # we don't want the cgi module interpreting the command-line args ;) sys.argv = sys.argv[:1] if pidfile: if not hasattr(os, 'fork'): print "Sorry, you can't run the server as a daemon on this" \ 'Operating System' sys.exit(0) else: daemonize(pidfile) if svc_args is not None: # don't do any other stuff return win32serviceutil.HandleCommandLine(RoundupService, argv=svc_args) # redirect stdout/stderr to our logfile if logfile: # appending, unbuffered sys.stdout = sys.stderr = open(logfile, 'a', 0) if success_message: print success_message else: print _('Roundup server started on %(address)s')%locals() try: httpd.serve_forever() except KeyboardInterrupt: print 'Keyboard Interrupt: exiting'
|
self.klass, self.property, self.check)
|
self.klass, self.properties, self.check)
|
def __repr__(self): return '<Permission 0x%x %r,%r,%r,%r>'%(id(self), self.name, self.klass, self.property, self.check)
|
def login(self, message=None):
|
def login(self, message=None, newuser_form=None):
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
<td><input name="realname"></td></tr>
|
<td><input name="realname" value="%(realname)s"></td></tr>
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
<td><input name="organisation"></td></tr>
|
<td><input name="organisation" value="%(organisation)s"></td></tr>
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
<td><input name="address"></td></tr>
|
<td><input name="address" value="%(address)s"></td></tr>
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
<td><input name="phone"></td></tr>
|
<td><input name="phone" value="%(phone)s"></td></tr>
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
<td><input name="username"></td></tr>
|
<td><input name="username" value="%(username)s"></td></tr>
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
<td><input type="password" name="password"></td></tr>
|
<td><input type="password" name="password" value="%(password)s"></td></tr>
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
<td><input type="password" name="confirm"></td></tr>
|
<td><input type="password" name="confirm" value="%(confirm)s"></td></tr>
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
''')
|
'''%values)
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
cl = self.db.classes['user'] props, dummy = parsePropsFromForm(self.db, cl, self.form) uid = cl.create(**props) self.user = self.db.user.get(uid, 'username') password = self.db.user.get(uid, 'password') self.set_cookie(self.user, password)
|
cl = self.db.user try: props, dummy = parsePropsFromForm(self.db, cl, self.form) uid = cl.create(**props) except ValueError, message: return self.login(message, newuser_form=self.form) self.user = cl.get(uid, 'username') password = cl.get(uid, 'password') self.set_cookie(self.user, self.form['password'].value)
|
def newuser_action(self, message=None): ''' create a new user based on the contents of the form and then set the cookie ''' # re-open the database as "admin" self.db.close() self.db = self.instance.open('admin')
|
env['SCRIPT_NAME'] = '/'.join(self.getPhysicalPath()[:-1]) env['INSTANCE_NAME'] = self.id
|
import urlparse path = urlparse.urlparse( self.absolute_url() )[2] path_components = path.split( '/' ) if path == "/" : env['SCRIPT_NAME'] = "/" env['INSTANCE_NAME'] = '' else : env['SCRIPT_NAME'] = '/'.join( path_components[:-1] ) env['INSTANCE_NAME'] = path_components[-1] del path_components , path
|
def _opendb(self): '''Open the roundup instance database for a transaction. ''' instance = roundup.instance.open(self.instance_home) request = RequestWrapper(self.REQUEST['RESPONSE']) env = self.REQUEST.environ env['SCRIPT_NAME'] = '/'.join(self.getPhysicalPath()[:-1]) env['INSTANCE_NAME'] = self.id if env['REQUEST_METHOD'] == 'GET': # force roundup to re-parse the request because Zope fiddles # with it and we lose all the :filter, :columns, etc goodness form = None else: form = FormWrapper(self.REQUEST.form) return instance.Client(instance, request, env, form)
|
self.assertEqual(keys, ['title', 'status', 'user'], 'wrong prop list')
|
self.assertEqual(keys, ['fixer', 'status', 'title'], 'wrong prop list')
|
def testChanges(self): self.db.issue.create(title="spam", status='1') self.db.issue.create(title="eggs", status='2') self.db.issue.create(title="ham", status='4') self.db.issue.create(title="arguments", status='2') self.db.issue.create(title="abuse", status='1') self.db.issue.addprop(fixer=Link("user")) props = self.db.issue.getprops() keys = props.keys() keys.sort() self.assertEqual(keys, ['title', 'status', 'user'], 'wrong prop list') self.db.issue.set('5', status=2) self.db.issue.get('5', "status") self.db.status.get('2', "name") self.db.issue.get('5', "title") self.db.issue.find(status = self.db.status.lookup("in-progress")) self.db.issue.history('5') self.db.status.history('1') self.db.status.history('2')
|
raise ValueError, 'Unknown spec %r'%spec
|
raise ValueError, 'Unknown spec %r' % (spec,)
|
def __init__(self, spec='.', offset=0, add_granularity=0, translator=i18n): """Construct a date given a specification and a time zone offset.
|
if not os.path.isabs(_val):
|
if _val and not os.path.isabs(_val):
|
def get(self): _val = Option.get(self) if not os.path.isabs(_val): _val = os.path.join(self.config["TRACKER_HOME"], _val) return _val
|
if type(v) is type([]):
|
if typeof(v) is typeof([]):
|
def pagefoot(self): if self.debug: self.write('<hr><small><dl>') self.write('<dt><b>Path</b></dt>') self.write('<dd>%s</dd>'%(', '.join(map(repr, self.split_path)))) keys = self.form.keys() keys.sort() if keys: self.write('<dt><b>Form entries</b></dt>') for k in self.form.keys(): v = self.form.getvalue(k, "<empty>") if type(v) is type([]): # Multiple username fields specified v = "|".join(v) self.write('<dd><em>%s</em>=%s</dd>'%(k, cgi.escape(v))) keys = self.headers_sent.keys() keys.sort() self.write('<dt><b>Sent these HTTP headers</b></dt>') for k in keys: v = self.headers_sent[k] self.write('<dd><em>%s</em>=%s</dd>'%(k, cgi.escape(v))) keys = self.env.keys() keys.sort() self.write('<dt><b>CGI environment</b></dt>') for k in keys: v = self.env[k] self.write('<dd><em>%s</em>=%s</dd>'%(k, cgi.escape(v))) self.write('</dl></small>') self.write('</body></html>')
|
if type(arg) == type([]):
|
if typeof(arg) == typeof([]):
|
def index_arg(self, arg): ''' handle the args to index - they might be a list from the form (ie. submitted from a form) or they might be a command-separated single string (ie. manually constructed GET args) ''' if self.form.has_key(arg): arg = self.form[arg] if type(arg) == type([]): return [arg.value for arg in arg] return arg.value.split(',') return []
|
if type(value) == type([]):
|
if typeof(value) == typeof([]):
|
def index_filterspec(self, filter): ''' pull the index filter spec from the form
|
type = cl.get(nodeid, 'type') if type == 'message/rfc822': type = 'text/plain' self.header(headers={'Content-Type': type})
|
mimetype = cl.get(nodeid, 'type') if mimetype == 'message/rfc822': mimetype = 'text/plain' self.header(headers={'Content-Type': mimetype})
|
def showfile(self): ''' display a file ''' nodeid = self.nodeid cl = self.db.file type = cl.get(nodeid, 'type') if type == 'message/rfc822': type = 'text/plain' self.header(headers={'Content-Type': type}) self.write(cl.get(nodeid, 'content'))
|
if type(value) != type([]): value = [value]
|
if typeof(value) != typeof([]): value = [value]
|
def _post_editnode(self, nid, changes=None): ''' do the linking and message sending part of the node creation ''' cn = self.classname cl = self.db.classes[cn] # link if necessary keys = self.form.keys() for key in keys: if key == ':multilink': value = self.form[key].value if type(value) != type([]): value = [value] for value in value: designator, property = value.split(':') link, nodeid = roundupdb.splitDesignator(designator) link = self.db.classes[link] value = link.get(nodeid, property) value.append(nid) link.set(nodeid, **{property: value}) elif key == ':link': value = self.form[key].value if type(value) != type([]): value = [value] for value in value: designator, property = value.split(':') link, nodeid = roundupdb.splitDesignator(designator) link = self.db.classes[link] link.set(nodeid, **{property: nid})
|
if type(value) != type([]):
|
if typeof(value) != typeof([]):
|
def parsePropsFromForm(db, cl, form, nodeid=0): '''Pull properties for the given class out of the form. ''' props = {} changed = [] keys = form.keys() num_re = re.compile('^\d+$') for key in keys: if not cl.properties.has_key(key): continue proptype = cl.properties[key] if isinstance(proptype, hyperdb.String): value = form[key].value.strip() elif isinstance(proptype, hyperdb.Password): value = password.Password(form[key].value.strip()) elif isinstance(proptype, hyperdb.Date): value = date.Date(form[key].value.strip()) elif isinstance(proptype, hyperdb.Interval): value = date.Interval(form[key].value.strip()) elif isinstance(proptype, hyperdb.Link): value = form[key].value.strip() # see if it's the "no selection" choice if value == '-1': # don't set this property continue else: # handle key values link = cl.properties[key].classname if not num_re.match(value): try: value = db.classes[link].lookup(value) except KeyError: raise ValueError, 'property "%s": %s not a %s'%( key, value, link) elif isinstance(proptype, hyperdb.Multilink): value = form[key] if type(value) != type([]): value = [i.strip() for i in value.value.split(',')] else: value = [i.value.strip() for i in value] link = cl.properties[key].classname l = [] for entry in map(str, value): if not num_re.match(entry): try: entry = db.classes[link].lookup(entry) except KeyError: raise ValueError, \ 'property "%s": "%s" not an entry of %s'%(key, entry, link.capitalize()) l.append(entry) l.sort() value = l props[key] = value # get the old value if nodeid: try: existing = cl.get(nodeid, key) except KeyError: # this might be a new property for which there is no existing # value if not cl.properties.has_key(key): raise # if changed, set it if nodeid and value != existing: changed.append(key) props[key] = value return props, changed
|
if self.user is None and not self.ANONYMOUS_REGISTER == 'deny':
|
if self.user is None and self.ANONYMOUS_REGISTER == 'deny':
|
def login(self, message=None): self.pagehead('Login to roundup', message) self.write('''
|
return self.index()
|
return self.login()
|
def logout(self, message=None): self.make_user_anonymous() # construct the logout cookie path = '/'.join((self.env['SCRIPT_NAME'], self.env['INSTANCE_NAME'], '')) now = Cookie._getdate() self.header({'Set-Cookie': 'roundup_user=deleted; Max-Age=0; expires=%s; Path=%s;'%(now, path)}) return self.index()
|
return self.index() elif not path: raise 'ValueError', 'Path not understood'
|
action = 'index' else: action = path[0]
|
def main(self, dre=re.compile(r'([^\d]+)(\d+)'), nre=re.compile(r'new(\w+)')):
|
action = path[0]
|
def main(self, dre=re.compile(r'([^\d]+)(\d+)'), nre=re.compile(r'new(\w+)')):
|
|
user = base64.encodestring('%s:%s'%(self.user, password))[:-1]
|
user = binascii.b2a_base64('%s:%s'%(self.user, password)).strip()
|
def login_action(self, message=None): if not self.form.has_key('__login_name'): return self.login(message='Username required') self.user = self.form['__login_name'].value if self.form.has_key('__login_password'): password = self.form['__login_password'].value else: password = '' print self.user, password # make sure the user exists try: uid = self.db.user.lookup(self.user) except KeyError: name = self.user self.make_user_anonymous() return self.login(message='No such user "%s"'%name)
|
user = base64.encodestring('%s:%s'%(self.user, password))[:-1]
|
user = binascii.b2a_base64('%s:%s'%(self.user, password)).strip()
|
def newuser_action(self, message=None): ''' create a new user based on the contents of the form and then set the cookie ''' # re-open the database as "admin" self.db.close() self.db = self.instance.open('admin')
|
user, password = base64.decodestring(cookie).split(':')
|
user, password = binascii.a2b_base64(cookie).split(':')
|
def main(self, dre=re.compile(r'([^\d]+)(\d+)'), nre=re.compile(r'new(\w+)')):
|
print "back_metakit.Class.set - dirty"
|
def set(self, nodeid, **propvalues): isnew = 0 if propvalues.has_key('#ISNEW'): isnew = 1 del propvalues['#ISNEW'] if not propvalues: return if propvalues.has_key('id'): raise KeyError, '"id" is reserved' if self.db.journaltag is None: raise DatabaseError, 'Database open read-only' view = self.getview(1) # node must exist & not be retired id = int(nodeid) ndx = view.find(id=id) if ndx < 0: raise IndexError, "%s has no node %s" % (self.classname, nodeid) row = view[ndx] if row._isdel: raise IndexError, "%s has no node %s" % (self.classname, nodeid) oldnode = self.uncommitted.setdefault(id, {}) changes = {} for key, value in propvalues.items(): # this will raise the KeyError if the property isn't valid # ... we don't use getprops() here because we only care about # the writeable properties. if _ALLOWSETTINGPRIVATEPROPS: prop = self.ruprops.get(key, None) if not prop: prop = self.privateprops[key] else: prop = self.ruprops[key] converter = _converters.get(prop.__class__, lambda v: v) # if the value's the same as the existing value, no sense in # doing anything oldvalue = converter(getattr(row, key)) if value == oldvalue: del propvalues[key] continue # check to make sure we're not duplicating an existing key if key == self.keyname: iv = self.getindexview(1) ndx = iv.find(k=value) if ndx == -1: iv.append(k=value, i=row.id) if not isnew: ndx = iv.find(k=oldvalue) if ndx > -1: iv.delete(ndx) else: raise ValueError, 'node with key "%s" exists'%value
|
|
print "back_metakit.Class.__getview - dirty!"
|
def __getview(self): db = self.db._db view = db.view(self.classname) if self.db.fastopen: return view.ordered(1) # is the definition the same? mkprops = view.structure() for nm, rutyp in self.ruprops.items(): for mkprop in mkprops: if mkprop.name == nm: break else: mkprop = None if mkprop is None: #print "%s missing prop %s (%s)" % (self.classname, nm, rutyp.__class__.__name__) break if _typmap[rutyp.__class__] != mkprop.type: #print "%s - prop %s (%s) has wrong mktyp (%s)" % (self.classname, nm, rutyp.__class__.__name__, mkprop.type) break else: return view.ordered(1) # need to create or restructure the mk view # id comes first, so MK will order it for us #XXX print "back_metakit.Class.__getview - dirty!" self.db.dirty = 1 s = ["%s[id:I" % self.classname] for nm, rutyp in self.ruprops.items(): mktyp = _typmap[rutyp.__class__] s.append('%s:%s' % (nm, mktyp)) if mktyp == 'V': s[-1] += ('[fid:I]') s.append('_isdel:I,activity:I,creation:I,creator:I]') v = db.getas(','.join(s)) return v.ordered(1)
|
|
hyperdb.String : 'VARCHAR(255)',
|
hyperdb.String : 'TEXT',
|
def db_exists(config): """Check if database already exists.""" kwargs = connection_dict(config) conn = MySQLdb.connect(**kwargs) try: try: conn.select_db(config.RDBMS_NAME) except MySQLdb.OperationalError: return 0 finally: conn.close() return 1
|
def install_demo(home, backend): from roundup import init, instance, password, backends, configuration
|
from roundup import configuration from roundup.scripts import roundup_server def install_demo(home, backend, template): """Install a demo tracker Parameters: home: tracker home directory path backend: database backend name template: full path to the tracker template directory """ from roundup import init, instance, password, backends
|
def install_demo(home, backend): from roundup import init, instance, password, backends, configuration # set up the config for this tracker config = configuration.CoreConfig() config['TRACKER_HOME'] = home config['MAIL_DOMAIN'] = 'localhost' config['DATABASE'] = 'db' if backend in ('mysql', 'postgresql'): config['RDBMS_HOST'] = 'localhost' config['RDBMS_USER'] = 'rounduptest' config['RDBMS_PASSWORD'] = 'rounduptest' config['RDBMS_NAME'] = 'rounduptest' # see if we have further db nuking to perform module = getattr(backends, backend) if module.db_exists(config): module.db_nuke(config) init.install(home, os.path.join('templates', 'classic')) # don't have email flying around os.remove(os.path.join(home, 'detectors', 'nosyreaction.py')) try: os.remove(os.path.join(home, 'detectors', 'nosyreaction.pyc')) except os.error, error: if error.errno != errno.ENOENT: raise init.write_select_db(home, backend) # figure basic params for server hostname = socket.gethostname() # pick a fairly odd, random port port = 8917 while 1: print 'Trying to set up web server on port %d ...'%port, s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.connect((hostname, port)) except socket.error, e: if not hasattr(e, 'args') or e.args[0] != errno.ECONNREFUSED: raise print 'should be ok.' break else: s.close() print 'already in use.' port += 100 config['TRACKER_WEB'] = 'http://%s:%s/demo/'%(hostname, port) # write the config config['INSTANT_REGISTRATION'] = 1 config.save() # open the tracker and initialise tracker = instance.open(home) tracker.init(password.Password('admin')) # add the "demo" user db = tracker.open('admin') db.user.create(username='demo', password=password.Password('demo'), realname='Demo User', roles='User') db.commit() db.close()
|
init.install(home, os.path.join('templates', 'classic'))
|
init.install(home, template)
|
def install_demo(home, backend): from roundup import init, instance, password, backends, configuration # set up the config for this tracker config = configuration.CoreConfig() config['TRACKER_HOME'] = home config['MAIL_DOMAIN'] = 'localhost' config['DATABASE'] = 'db' if backend in ('mysql', 'postgresql'): config['RDBMS_HOST'] = 'localhost' config['RDBMS_USER'] = 'rounduptest' config['RDBMS_PASSWORD'] = 'rounduptest' config['RDBMS_NAME'] = 'rounduptest' # see if we have further db nuking to perform module = getattr(backends, backend) if module.db_exists(config): module.db_nuke(config) init.install(home, os.path.join('templates', 'classic')) # don't have email flying around os.remove(os.path.join(home, 'detectors', 'nosyreaction.py')) try: os.remove(os.path.join(home, 'detectors', 'nosyreaction.pyc')) except os.error, error: if error.errno != errno.ENOENT: raise init.write_select_db(home, backend) # figure basic params for server hostname = socket.gethostname() # pick a fairly odd, random port port = 8917 while 1: print 'Trying to set up web server on port %d ...'%port, s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.connect((hostname, port)) except socket.error, e: if not hasattr(e, 'args') or e.args[0] != errno.ECONNREFUSED: raise print 'should be ok.' break else: s.close() print 'already in use.' port += 100 config['TRACKER_WEB'] = 'http://%s:%s/demo/'%(hostname, port) # write the config config['INSTANT_REGISTRATION'] = 1 config.save() # open the tracker and initialise tracker = instance.open(home) tracker.init(password.Password('admin')) # add the "demo" user db = tracker.open('admin') db.user.create(username='demo', password=password.Password('demo'), realname='Demo User', roles='User') db.commit() db.close()
|
config.save()
|
config.save(os.path.join(home, config.INI_FILE))
|
def install_demo(home, backend): from roundup import init, instance, password, backends, configuration # set up the config for this tracker config = configuration.CoreConfig() config['TRACKER_HOME'] = home config['MAIL_DOMAIN'] = 'localhost' config['DATABASE'] = 'db' if backend in ('mysql', 'postgresql'): config['RDBMS_HOST'] = 'localhost' config['RDBMS_USER'] = 'rounduptest' config['RDBMS_PASSWORD'] = 'rounduptest' config['RDBMS_NAME'] = 'rounduptest' # see if we have further db nuking to perform module = getattr(backends, backend) if module.db_exists(config): module.db_nuke(config) init.install(home, os.path.join('templates', 'classic')) # don't have email flying around os.remove(os.path.join(home, 'detectors', 'nosyreaction.py')) try: os.remove(os.path.join(home, 'detectors', 'nosyreaction.pyc')) except os.error, error: if error.errno != errno.ENOENT: raise init.write_select_db(home, backend) # figure basic params for server hostname = socket.gethostname() # pick a fairly odd, random port port = 8917 while 1: print 'Trying to set up web server on port %d ...'%port, s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.connect((hostname, port)) except socket.error, e: if not hasattr(e, 'args') or e.args[0] != errno.ECONNREFUSED: raise print 'should be ok.' break else: s.close() print 'already in use.' port += 100 config['TRACKER_WEB'] = 'http://%s:%s/demo/'%(hostname, port) # write the config config['INSTANT_REGISTRATION'] = 1 config.save() # open the tracker and initialise tracker = instance.open(home) tracker.init(password.Password('admin')) # add the "demo" user db = tracker.open('admin') db.user.create(username='demo', password=password.Password('demo'), realname='Demo User', roles='User') db.commit() db.close()
|
def run_demo(): ''' Run a demo server for users to play with for instant gratification. Sets up the web service on localhost. Disables nosy lists. ''' home = os.path.abspath('demo') backend = 'anydbm' if not os.path.exists(home) or sys.argv[-1] == 'nuke': if len(sys.argv) > 2: backend = sys.argv[-2] install_demo(home, backend) cfg = ConfigParser.ConfigParser() cfg.read(os.path.join(home, 'config.ini')) url = cfg.get('tracker', 'web') hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) from roundup.scripts import roundup_server
|
def run_demo(home): """Run the demo tracker installed in ``home``"""
|
def run_demo(): ''' Run a demo server for users to play with for instant gratification. Sets up the web service on localhost. Disables nosy lists. ''' home = os.path.abspath('demo') backend = 'anydbm' if not os.path.exists(home) or sys.argv[-1] == 'nuke': if len(sys.argv) > 2: backend = sys.argv[-2] install_demo(home, backend) cfg = ConfigParser.ConfigParser() cfg.read(os.path.join(home, 'config.ini')) url = cfg.get('tracker', 'web') hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) # ok, so start up the server from roundup.scripts import roundup_server roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} success_message = '''Server running - connect to: %s
|
cfg = configuration.CoreConfig(home)
|
def run_demo(): ''' Run a demo server for users to play with for instant gratification. Sets up the web service on localhost. Disables nosy lists. ''' home = os.path.abspath('demo') backend = 'anydbm' if not os.path.exists(home) or sys.argv[-1] == 'nuke': if len(sys.argv) > 2: backend = sys.argv[-2] install_demo(home, backend) cfg = ConfigParser.ConfigParser() cfg.read(os.path.join(home, 'config.ini')) url = cfg.get('tracker', 'web') hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) # ok, so start up the server from roundup.scripts import roundup_server roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} success_message = '''Server running - connect to: %s
|
|
4. Re-initialise the server by running "python demo.py nuke".''' % url
|
4. Re-initialise the server by running "python demo.py nuke". ''' % cfg["TRACKER_WEB"]
|
def run_demo(): ''' Run a demo server for users to play with for instant gratification. Sets up the web service on localhost. Disables nosy lists. ''' home = os.path.abspath('demo') backend = 'anydbm' if not os.path.exists(home) or sys.argv[-1] == 'nuke': if len(sys.argv) > 2: backend = sys.argv[-2] install_demo(home, backend) cfg = ConfigParser.ConfigParser() cfg.read(os.path.join(home, 'config.ini')) url = cfg.get('tracker', 'web') hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) # ok, so start up the server from roundup.scripts import roundup_server roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} success_message = '''Server running - connect to: %s
|
roundup_server.run(port, success_message)
|
roundup_server.run(success_message=success_message) def demo_main(): """Run a demo server for users to play with for instant gratification. Sets up the web service on localhost. Disables nosy lists. """ home = os.path.abspath('demo') if not os.path.exists(home) or (sys.argv[-1] == 'nuke'): if len(sys.argv) > 2: backend = sys.argv[-2] else: backend = 'anydbm' install_demo(home, backend, os.path.join('templates', 'classic')) run_demo(home)
|
def run_demo(): ''' Run a demo server for users to play with for instant gratification. Sets up the web service on localhost. Disables nosy lists. ''' home = os.path.abspath('demo') backend = 'anydbm' if not os.path.exists(home) or sys.argv[-1] == 'nuke': if len(sys.argv) > 2: backend = sys.argv[-2] install_demo(home, backend) cfg = ConfigParser.ConfigParser() cfg.read(os.path.join(home, 'config.ini')) url = cfg.get('tracker', 'web') hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) # ok, so start up the server from roundup.scripts import roundup_server roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} success_message = '''Server running - connect to: %s
|
run_demo()
|
demo_main()
|
def run_demo(): ''' Run a demo server for users to play with for instant gratification. Sets up the web service on localhost. Disables nosy lists. ''' home = os.path.abspath('demo') backend = 'anydbm' if not os.path.exists(home) or sys.argv[-1] == 'nuke': if len(sys.argv) > 2: backend = sys.argv[-2] install_demo(home, backend) cfg = ConfigParser.ConfigParser() cfg.read(os.path.join(home, 'config.ini')) url = cfg.get('tracker', 'web') hostname, port = urlparse.urlparse(url)[1].split(':') port = int(port) # ok, so start up the server from roundup.scripts import roundup_server roundup_server.RoundupRequestHandler.TRACKER_HOMES = {'demo': home} success_message = '''Server running - connect to: %s
|
self.debug = 0
|
try: self.debug = int(env.get("ROUNDUP_DEBUG", 0)) except ValueError: self.debug = 0
|
def __init__(self, instance, request, env): self.instance = instance self.request = request self.env = env self.path = env['PATH_INFO'] self.split_path = self.path.split('/')
|
l = [HTMLItem(self._client, self.classname, x)
|
l = [HTMLItem(self._client, self.classname, id)
|
def filter(self, request=None, filterspec={}, sort=(None,None), group=(None,None)): ''' Return a list of items from this class, filtered and sorted by the current requested filterspec/filter/sort/group args
|
def multilinkGenerator(classname, client, values): id = -1 check = client.db.security.hasPermission userid = client.userid while 1: id += 1 if id >= len(values): raise StopIteration value = values[id] if check('View', userid, classname, itemid=value): yield HTMLItem(client, classname, value)
|
def multilinkGenerator(classname, client, values): id = -1 check = client.db.security.hasPermission userid = client.userid while 1: id += 1 if id >= len(values): raise StopIteration value = values[id] if check('View', userid, classname, itemid=value): yield HTMLItem(client, classname, value)
|
|
return multilinkGenerator(self._prop.classname, self._client, self._value)
|
return self.multilinkGenerator(self._value)
|
def __iter__(self): ''' iterate and return a new HTMLItem ''' return multilinkGenerator(self._prop.classname, self._client, self._value)
|
return multilinkGenerator(self._prop.classname, self._client, l)
|
return self.multilinkGenerator(l)
|
def reverse(self): ''' return the list in reverse order ''' l = self._value[:] l.reverse() return multilinkGenerator(self._prop.classname, self._client, l)
|
if response.find('is being accessed by other users') == -1: raise RuntimeError, response time.sleep(1) return 0
|
msgs = [ 'is being accessed by other users', 'could not serialize access due to concurrent update', ] can_retry = 0 for msg in msgs: if response.find(msg) == -1: can_retry = 1 if can_retry: time.sleep(1) return 0 raise RuntimeError, response
|
def pg_command(cursor, command): '''Execute the postgresql command, which may be blocked by some other user connecting to the database, and return a true value if it succeeds. ''' try: cursor.execute(command) except psycopg.ProgrammingError, err: response = str(err).split('\n')[0] if response.find('FATAL') != -1: raise RuntimeError, response elif response.find('ERROR') != -1: if response.find('is being accessed by other users') == -1: raise RuntimeError, response time.sleep(1) return 0 return 1
|
prefix = cmdopt['install']['prefix'][1]
|
prefix = os.path.expanduser(cmdopt['install']['prefix'][1])
|
def finalize_options(self): build_scripts.finalize_options(self) cmdopt=self.distribution.command_options
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testNewIssueAuthMsg(self): message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testSimpleFollowup(self): self.doNewIssue() message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowup(self): self.doNewIssue()
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowupTitleMatch(self): self.doNewIssue() message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowupNosyAuthor(self): self.doNewIssue() self.db.config.ADD_AUTHOR_TO_NOSY = 'yes' message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowupNosyRecipients(self): self.doNewIssue() self.db.config.ADD_RECIPIENTS_TO_NOSY = 'yes' message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowupNosyAuthorAndCopy(self): self.doNewIssue() self.db.config.ADD_AUTHOR_TO_NOSY = 'yes' self.db.config.MESSAGES_TO_AUTHOR = 'yes' message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowupNoNosyAuthor(self): self.doNewIssue() self.instance.config.ADD_AUTHOR_TO_NOSY = 'no' message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowupNoNosyRecipients(self): self.doNewIssue() self.instance.config.ADD_RECIPIENTS_TO_NOSY = 'no' message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testEnc01(self): self.doNewIssue() message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testMultipartEnc01(self): self.doNewIssue() message = cStringIO.StringIO('''Content-Type: text/plain;
|
http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1
|
<http://tracker.example/cgi-bin/roundup.cgi/bugs/issue1>
|
def testFollowupStupidQuoting(self): self.doNewIssue()
|
label = linkcl.get(self._value, k)
|
value = linkcl.get(self._value, k)
|
def field(self, showid=0, size=None): ''' Render a form edit field for the property
|
label = self._value value = cgi.escape(str(self._value))
|
value = self._value value = cgi.escape(str(value))
|
def field(self, showid=0, size=None): ''' Render a form edit field for the property
|
label, size)
|
value, size)
|
def field(self, showid=0, size=None): ''' Render a form edit field for the property
|
if not str(e).startswith('No module named %s' % _modules[name]):
|
if not str(e).startswith('No module named %s' % _modules.get(name, name)):
|
def have_backend(name): '''Is backend "name" available?''' try: get_backend(name) return 1 except ImportError, e: global _modules if not str(e).startswith('No module named %s' % _modules[name]): raise return 0
|
if num_re.match(entry): l.append(entry) else: try: l.append(cl.lookup(entry)) except (TypeError, KeyError): if fail_ok: l.append(entry)
|
try: l.append(cl.lookup(entry)) except (TypeError, KeyError): if fail_ok or num_re.match(entry): l.append(entry)
|
def lookupIds(db, prop, ids, fail_ok=0, num_re=re.compile('^-?\d+$')): ''' "fail_ok" should be specified if we wish to pass through bad values (most likely form values that we wish to represent back to the user) ''' cl = db.getclass(prop.classname) l = [] for entry in ids: if num_re.match(entry): l.append(entry) else: try: l.append(cl.lookup(entry)) except (TypeError, KeyError): if fail_ok: # pass through the bad value l.append(entry) return l
|
self.__RW = 0
|
def __init__(self, config, journaltag=None): self.config = config self.journaltag = journaltag self.classes = {} self._classes = [] self.dirty = 0 self.__RW = 0 self._db = self.__open() self.indexer = Indexer(self.config.DATABASE) os.umask(0002)
|
|
self.indexer = Indexer(self.config.DATABASE)
|
self.indexer = Indexer(self.config.DATABASE, self._db)
|
def __init__(self, config, journaltag=None): self.config = config self.journaltag = journaltag self.classes = {} self._classes = [] self.dirty = 0 self.__RW = 0 self._db = self.__open() self.indexer = Indexer(self.config.DATABASE) os.umask(0002)
|
if self.__RW: self._db.commit() for cl in self.classes.values(): cl._commit() self.indexer.save_index() else: raise RuntimeError, "metakit is open RO"
|
self._db.commit() for cl in self.classes.values(): cl._commit() self.indexer.save_index()
|
def commit(self): if self.dirty: if self.__RW: self._db.commit() for cl in self.classes.values(): cl._commit() self.indexer.save_index() else: raise RuntimeError, "metakit is open RO" self.dirty = 0
|
import time now = time.time start = now()
|
def close(self): import time now = time.time start = now() for cl in self.classes.values(): cl.db = None #self._db.rollback() #print "pre-close cleanup of DB(%d) took %2.2f secs" % (self.__RW, now()-start) self._db = None #print "close of DB(%d) took %2.2f secs" % (self.__RW, now()-start) self.classes = {} try: del _instances[id(self.config)] except KeyError: pass self.__RW = 0
|
|
try: del _instances[id(self.config)] except KeyError: pass self.__RW = 0
|
self.indexer = None
|
def close(self): import time now = time.time start = now() for cl in self.classes.values(): cl.db = None #self._db.rollback() #print "pre-close cleanup of DB(%d) took %2.2f secs" % (self.__RW, now()-start) self._db = None #print "close of DB(%d) took %2.2f secs" % (self.__RW, now()-start) self.classes = {} try: del _instances[id(self.config)] except KeyError: pass self.__RW = 0
|
else: self.__RW = 1 if not self.fastopen: self.__RW = 1 db = metakit.storage(db, self.__RW)
|
db = metakit.storage(db, 1)
|
def __open(self): self.dbnm = db = os.path.join(self.config.DATABASE, 'tracker.mk4') self.fastopen = 0 if os.path.exists(db): dbtm = os.path.getmtime(db) pkgnm = self.config.__name__.split('.')[0] schemamod = sys.modules.get(pkgnm+'.dbinit', None) if schemamod: if os.path.exists(schemamod.__file__): schematm = os.path.getmtime(schemamod.__file__) if schematm < dbtm: # found schema mod - it's older than the db self.fastopen = 1 else: # can't find schemamod - must be frozen self.fastopen = 1 else: self.__RW = 1 if not self.fastopen: self.__RW = 1 db = metakit.storage(db, self.__RW) hist = db.view('history') tables = db.view('tables') if not self.fastopen: if not hist.structure(): hist = db.getas('history[tableid:I,nodeid:I,date:I,user:I,action:I,params:B]') if not tables.structure(): tables = db.getas('tables[name:S]') self.tables = tables self.hist = hist return db
|
def isReadOnly(self): return self.__RW == 0 def getWriteAccess(self): if self.journaltag is not None and self.__RW == 0: self._db = None self._db = metakit.storage(self.dbnm, 1) self.__RW = 1 self.hist = self._db.view('history') self.tables = self._db.view('tables')
|
def isReadOnly(self): return self.__RW == 0
|
|
self.db.getWriteAccess()
|
def setkey(self, propname): if self.keyname: if propname == self.keyname: return raise ValueError, "%s already indexed on %s" % (self.classname, self.keyname) # first setkey for this run self.keyname = propname iv = self.db._db.view('_%s' % self.classname) if self.db.fastopen and iv.structure(): return # very first setkey ever self.db.getWriteAccess() self.db.dirty = 1 iv = self.db._db.getas('_%s[k:S,i:I]' % self.classname) iv = iv.ordered(1) #XXX
|
|
self.db.getWriteAccess()
|
def addprop(self, **properties): for key in properties.keys(): if self.ruprops.has_key(key): raise ValueError, "%s is already a property of %s" % (key, self.classname) self.ruprops.update(properties) self.db.getWriteAccess() self.db.fastopen = 0 view = self.__getview() self.db.commit()
|
|
self.db.getWriteAccess()
|
def __getview(self): db = self.db._db view = db.view(self.classname) mkprops = view.structure() if mkprops and self.db.fastopen: return view.ordered(1) # is the definition the same? for nm, rutyp in self.ruprops.items(): for mkprop in mkprops: if mkprop.name == nm: break else: mkprop = None if mkprop is None: print "%s missing prop %s (%s)" % (self.classname, nm, rutyp.__class__.__name__) break if _typmap[rutyp.__class__] != mkprop.type: print "%s - prop %s (%s) has wrong mktyp (%s)" % (self.classname, nm, rutyp.__class__.__name__, mkprop.type) break else: return view.ordered(1) # need to create or restructure the mk view # id comes first, so MK will order it for us self.db.getWriteAccess() self.db.dirty = 1 s = ["%s[id:I" % self.classname] for nm, rutyp in self.ruprops.items(): mktyp = _typmap[rutyp.__class__] s.append('%s:%s' % (nm, mktyp)) if mktyp == 'V': s[-1] += ('[fid:I]') s.append('_isdel:I,activity:I,creation:I,creator:I]') v = self.db._db.getas(','.join(s)) self.db.commit() return v.ordered(1)
|
|
if RW and self.db.isReadOnly(): self.db.getWriteAccess()
|
def getview(self, RW=0): if RW and self.db.isReadOnly(): self.db.getWriteAccess() return self.db._db.view(self.classname).ordered(1)
|
|
if RW and self.db.isReadOnly(): self.db.getWriteAccess()
|
def getindexview(self, RW=0): if RW and self.db.isReadOnly(): self.db.getWriteAccess() return self.db._db.view("_%s" % self.classname).ordered(1)
|
|
remove(fnm)
|
action1(fnm)
|
def undo(fnm=nm, action1=os.remove, indexer=self.db.indexer): remove(fnm)
|
''' Render a form select list for this property
|
''' Render a form <select> list for this property. "size" is used to limit the length of the list labels "height" is used to set the <select> tag's "size" attribute "showid" includes the item ids in the list labels "additional" lists properties which should be included in the label "sort_on" indicates the property to sort the list on as (direction, property) where direction is '+' or '-'. The remaining keyword arguments are used as conditions for filtering the items in the list - they're passed as the "filterspec" argument to a Class.filter() call.
|
def menu(self, size=None, height=None, showid=0, additional=[], sort_on=None, **conditions): ''' Render a form select list for this property
|
env['HTTP_ACCEPT_LANGUAGE'] = self.headers['accept-language']
|
env['HTTP_ACCEPT_LANGUAGE'] = self.headers.get('accept-language')
|
def inner_run_cgi(self): ''' This is the inner part of the CGI handling ''' rest = self.path
|
return self.getclass(classname)
|
try: return self.getclass(classname) except KeyError, msg: raise AttributeError, str(msg)
|
def __getattr__(self, classname): if classname == 'transactions': return self.dirty # fall back on the classes return self.getclass(classname)
|
self_value = display_value
|
self._value = display_value
|
def __init__(self, *args, **kwargs): HTMLProperty.__init__(self, *args, **kwargs) if self._value: display_value = lookupIds(self._db, self._prop, self._value, fail_ok=1) sortfun = make_sort_function(self._db, self._prop.classname) # sorting fails if the value contains # items not yet stored in the database # ignore these errors to preserve user input try: display_value.sort(sortfun) except: pass self_value = display_value
|
return cl.parsePropsFromForm()
|
return cl.parsePropsFromForm(create=1)
|
def parseForm(self, form, classname='test', nodeid=None): cl = client.Client(self.instance, None, {'PATH_INFO':'/'}, makeForm(form)) cl.classname = classname cl.nodeid = nodeid cl.db = self.db return cl.parsePropsFromForm()
|
self.assertEqual(cl.parsePropsFromForm(),
|
self.assertEqual(cl.parsePropsFromForm(create=1),
|
def testMixedMultilink(self): form = cgi.FieldStorage() form.list.append(cgi.MiniFieldStorage('nosy', '1,2')) form.list.append(cgi.MiniFieldStorage('nosy', '3')) cl = client.Client(self.instance, None, {'PATH_INFO':'/'}, form) cl.classname = 'issue' cl.nodeid = None cl.db = self.db self.assertEqual(cl.parsePropsFromForm(), ({('issue', None): {'nosy': ['1','2', '3']}}, []))
|
return '<a class="classhelp" href="javascript:help_window(\'%s?'\ '@startwith=0&@template=help&properties=%s%s%s\', \'%s\', \ \'%s\')">%s</a>'%(self.classname, properties, property, form, width, height, self._(label))
|
help_url = "%s?@startwith=0&@template=help&"\ "properties=%s%s%s" % \ (self.classname, properties, property, form) onclick = "javascript:help_window('%s', '%s', '%s');return false;" % \ (help_url, width, height) return '<a class="classhelp" href="%s" onclick="%s">%s</a>' % \ (help_url, onclick, self._(label))
|
def classhelp(self, properties=None, label=''"(list)", width='500', height='400', property='', form='itemSynopsis'): '''Pop up a javascript window with class help
|
return __import__('back_%s'%name, globals())
|
vars = globals() if vars.has_key(name): return vars[name] module_name = 'back_%s' % name try: module = __import__(module_name, vars) except: del sys.modules['.'.join((__name__, module_name))] del vars[module_name] raise else: vars[name] = module return module
|
def get_backend(name): '''Get a specific backend by name.''' return __import__('back_%s'%name, globals())
|
module = _modules.get(name, name)
|
def have_backend(name): '''Is backend "name" available?''' module = _modules.get(name, name) try: get_backend(name) return 1 except ImportError, e: if not str(e).startswith('No module named %s'%module): raise return 0
|
|
if not str(e).startswith('No module named %s'%module):
|
global _modules if not str(e).startswith('No module named %s' % _modules[name]):
|
def have_backend(name): '''Is backend "name" available?''' module = _modules.get(name, name) try: get_backend(name) return 1 except ImportError, e: if not str(e).startswith('No module named %s'%module): raise return 0
|
pt.pt_edit(open(src).read(), mimetypes.guess_type(filename))
|
content_type = mimetypes.guess_type(filename)[0] or 'text/html' pt.pt_edit(open(src).read(), content_type)
|
def get(self, name, extension=None): ''' Interface to get a template, possibly loading a compiled template.
|
find_template(self._db.config.TEMPLATES,
|
template = find_template(self._db.config.TEMPLATES,
|
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] current = {} comments = {} history = self._klass.history(self._nodeid) history.sort() timezone = self._db.getUserTimezone() if direction == 'descending': history.reverse() for prop_n in self._props.keys(): prop = self[prop_n] if isinstance(prop, HTMLProperty): current[prop_n] = prop.plain() # make link if hrefable if (self._props.has_key(prop_n) and isinstance(self._props[prop_n], hyperdb.Link)): classname = self._props[prop_n].classname try: find_template(self._db.config.TEMPLATES, classname, 'item') except NoTemplate: pass else: id = self._klass.get(self._nodeid, prop_n, None) current[prop_n] = '<a href="%s%s">%s</a>'%( classname, id, current[prop_n])
|
if prop is not None: if args[k] and (isinstance(prop, hyperdb.Multilink) or isinstance(prop, hyperdb.Link)): classname = prop.classname try: linkcl = self._db.getclass(classname) except KeyError: labelprop = None comments[classname] = _('''The linked class %(classname)s no longer exists''')%locals() labelprop = linkcl.labelprop(1) hrefable = os.path.exists( os.path.join(self._db.config.TEMPLATES, classname+'.item')) if isinstance(prop, hyperdb.Multilink) and args[k]: ml = [] for linkid in args[k]: if isinstance(linkid, type(())): sublabel = linkid[0] + ' ' linkids = linkid[1] else: sublabel = '' linkids = [linkid] subml = [] for linkid in linkids: label = classname + linkid try: if labelprop is not None and \ labelprop != 'id': label = linkcl.get(linkid, labelprop) except IndexError: comments['no_link'] = _('''<strike>The linked node no longer exists</strike>''') subml.append('<strike>%s</strike>'%label) else: if hrefable: subml.append('<a href="%s%s">%s</a>'%( classname, linkid, label)) else: subml.append(label) ml.append(sublabel + ', '.join(subml)) cell.append('%s:\n %s'%(k, ', '.join(ml))) elif isinstance(prop, hyperdb.Link) and args[k]: label = classname + args[k] if labelprop is not None and labelprop != 'id':
|
if prop is None: comments['no_exist'] = _('''<em>The indicated property no longer exists</em>''') cell.append('<em>%s: %s</em>\n'%(k, str(args[k]))) continue if args[k] and (isinstance(prop, hyperdb.Multilink) or isinstance(prop, hyperdb.Link)): classname = prop.classname try: linkcl = self._db.getclass(classname) except KeyError: labelprop = None comments[classname] = _('''The linked class %(classname)s no longer exists''')%locals() labelprop = linkcl.labelprop(1) try: template = find_template(self._db.config.TEMPLATES, classname, 'item') if template[1].startswith('_generic'): raise NoTemplate, 'not really...' hrefable = 1 except NoTemplate: hrefable = 0 if isinstance(prop, hyperdb.Multilink) and args[k]: ml = [] for linkid in args[k]: if isinstance(linkid, type(())): sublabel = linkid[0] + ' ' linkids = linkid[1] else: sublabel = '' linkids = [linkid] subml = [] for linkid in linkids: label = classname + linkid
|
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] current = {} comments = {} history = self._klass.history(self._nodeid) history.sort() timezone = self._db.getUserTimezone() if direction == 'descending': history.reverse() for prop_n in self._props.keys(): prop = self[prop_n] if isinstance(prop, HTMLProperty): current[prop_n] = prop.plain() # make link if hrefable if (self._props.has_key(prop_n) and isinstance(self._props[prop_n], hyperdb.Link)): classname = self._props[prop_n].classname try: find_template(self._db.config.TEMPLATES, classname, 'item') except NoTemplate: pass else: id = self._klass.get(self._nodeid, prop_n, None) current[prop_n] = '<a href="%s%s">%s</a>'%( classname, id, current[prop_n])
|
label = linkcl.get(args[k], labelprop)
|
if labelprop is not None and \ labelprop != 'id': label = linkcl.get(linkid, labelprop)
|
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] current = {} comments = {} history = self._klass.history(self._nodeid) history.sort() timezone = self._db.getUserTimezone() if direction == 'descending': history.reverse() for prop_n in self._props.keys(): prop = self[prop_n] if isinstance(prop, HTMLProperty): current[prop_n] = prop.plain() # make link if hrefable if (self._props.has_key(prop_n) and isinstance(self._props[prop_n], hyperdb.Link)): classname = self._props[prop_n].classname try: find_template(self._db.config.TEMPLATES, classname, 'item') except NoTemplate: pass else: id = self._klass.get(self._nodeid, prop_n, None) current[prop_n] = '<a href="%s%s">%s</a>'%( classname, id, current[prop_n])
|
cell.append(' <strike>%s</strike>,\n'%label) label = None if label is not None: if hrefable: old = '<a href="%s%s">%s</a>'%(classname, args[k], label)
|
subml.append('<strike>%s</strike>'%label)
|
def history(self, direction='descending', dre=re.compile('\d+')): l = ['<table class="history">' '<tr><th colspan="4" class="header">', _('History'), '</th></tr><tr>', _('<th>Date</th>'), _('<th>User</th>'), _('<th>Action</th>'), _('<th>Args</th>'), '</tr>'] current = {} comments = {} history = self._klass.history(self._nodeid) history.sort() timezone = self._db.getUserTimezone() if direction == 'descending': history.reverse() for prop_n in self._props.keys(): prop = self[prop_n] if isinstance(prop, HTMLProperty): current[prop_n] = prop.plain() # make link if hrefable if (self._props.has_key(prop_n) and isinstance(self._props[prop_n], hyperdb.Link)): classname = self._props[prop_n].classname try: find_template(self._db.config.TEMPLATES, classname, 'item') except NoTemplate: pass else: id = self._klass.get(self._nodeid, prop_n, None) current[prop_n] = '<a href="%s%s">%s</a>'%( classname, id, current[prop_n])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.