I'm attempting to install Powerline http://code.google.com/p/powerline/, a computer reservation software based on CherryPy/Python using a MYSql database, at my local library and I've run up against an error that I cannot google my way out of!   The google groups for the application is inactive so I'm posting on here in the hope that I can get some pointers to get me beyond this issue. Any suggestions/pointers will be greatly appreciated.
 
 
The error message is
File "/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline/main.py", line 38, in index
   settings = settings_model(database)
TypeError: __new__() takes exactly 3 arguments (2 given)

The full text/context is below - I've been working with Linux for about 15 years but I'm not a programmer, don't know anything about python so I'm totally stuck. (From googling, I believe that the missing Application config error returned by CherryPy Checker below is informational and not a show stopper. Powerline is the only python-based application running on the server)

The output below is the terminal output when the Links text-based browser running locally attempts to the Powerline application at localhost:8080. I've attached the main.py and database.py files (I'm guessing that these are the two files involved) from the powerline directory and the ls output for the directory also. I'll be happy to post any other files needed.

Thanks!

je...@ubuntu:~$ sudo python -m powerline.main /etc/powerline.conf
[22/May/2010:19:48:56] ENGINE Listening for SIGHUP.
[22/May/2010:19:48:56] ENGINE Listening for SIGTERM.
[22/May/2010:19:48:56] ENGINE Listening for SIGUSR1.
[22/May/2010:19:48:56] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.

[22/May/2010:19:48:56] ENGINE Started monitor thread '_TimeoutMonitor'.
[22/May/2010:19:48:56] ENGINE Started monitor thread 'Autoreloader'.
[22/May/2010:19:48:56] ENGINE Serving on 127.0.0.1:8080
[22/May/2010:19:48:56] ENGINE Bus STARTED
[22/May/2010:19:50:09] HTTP
Request Headers:
 HOST: localhost:8080
 ACCEPT: */*
 ACCEPT-CHARSET: us-ascii, ISO-8859-1, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO-8859-10, ISO-8859-13, ISO-8859-14, ISO-8859-15, ISO-8859-16, windows-1250, windows-1251, windows-1252, windows-1256, windows-1257, cp437, cp737, cp850, cp852, cp866, x-cp866-u, x-mac, x-mac-ce, x-kam-cs, koi8-r, koi8-u, koi8-ru, TCVN-5712, VISCII, utf-8
 USER-AGENT: Links (2.1pre32; Linux 2.6.24-23-server i686; 176x45)
 CONNECTION: Keep-Alive
 Remote-Addr: 127.0.0.1
 ACCEPT-LANGUAGE: en, *;q=0.1
 ACCEPT-ENCODING: gzip, deflate
[22/May/2010:19:50:09] HTTP Traceback (most recent call last):
 File "/usr/lib/python2.5/site-packages/CherryPy-3.1.2-py2.5.egg/cherrypy/_cprequest.py", line 606, in respond
   cherrypy.response.body = self.handler()
 File "/usr/lib/python2.5/site-packages/CherryPy-3.1.2-py2.5.egg/cherrypy/_cpdispatch.py", line 25, in __call__
   return self.callable(*self.args, **self.kwargs)
 File "/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline/web.py", line 62, in default
   return handler_func(**kwargs)
 File "/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline/web.py", line 99, in wrapper
   body.update(result)
 File "/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline/main.py", line 38, in index
   settings = settings_model(database)
TypeError: __new__() takes exactly 3 arguments (2 given)

XXXXXXXXXXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXXXXXXXXX
je...@ubuntu:/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline$ more main.py
# powerline.main - Main controllers and entry point
# (c) 2008 Pianohacker, licensed under the GPLv3

import cherrypy
from powerline import output, web, database, json, manager, xmlrpc, location, user_error
from powerline.lib import plugin
from powerline.database import user_model, system_model, session_model, settings_model, connect
import time
from sys import argv
from os import path

class root(web.controller):
       js = cherrypy.tools.staticdir.handler(section = '/js', dir = 'templates/js')
       data = "" = '/data', dir = 'templates/data')
       js._cp_config, data._cp_config = [{'tools.caching.on': True}] * 2

       def __init__(self):
               self.XMLRPC = xmlrpc.api()
               self.manager = manager.interface()

               cherrypy.config.update({
                       'tools.sessions.on': True,
                       'tools.decode.on': True,
                       'tools.encode.on': True,
                       'tools.encode.encoding': 'utf-8',
                       'tools.staticdir.root': location,
               })

               plugin.load(path.join(location, 'plugins'))

               super(root, self).__init__()

       @web.accessible_by('/', method = 'GET')
       @web.expose(template = 'index.html')
       def index(self):
               """/ - The main page. Also where reservation requests are POSTed to."""
               database = connect()
               settings = settings_model(database)

               yield 'reservation_entry_prefill', settings['reservation_entry_prefill']

               if cherrypy.session.get('logged-in', False):
                       del cherrypy.session['logged-in']

       @web.accessible_by('/', method = 'POST')
       @web.expose(template = 'index.html')
       def create(self, barcode):
               database = connect()
               user = user_model(database)
               session = session_model(database)
               system = system_model(database)
               settings = settings_model(database)

               yield 'reservation_entry_prefill', settings['reservation_entry_prefill']

               try:
                       sessions_per_user = settings['sessions_per_user']
                       if session.rows('date(timestamp) = current_date AND user = %s', barcode).select_value('count(*)') >= sessions_per_user:
                               raise user_error('You have already logged on %d times today' % sessions_per_user)
               except KeyError:
                       pass

               session.create(barcode)
               reservation = session.get(barcode)
               reservation.update(dict(open_computers = system.get_open(), line_position = user.get_line_position(barcode), open_time = session.get_open_time()))

               yield 'result', reservation

       @web.expose()
       def sessions(self):
               """/sessions - Returns the list of sessions."""
               database = connect()

               session = session_model(database)
               user = user_model(database)
               system = system_model(database)

               results = session.get_unended()
               open_computers = system.get_open()

               for i, result in enumerate(results):
                       result = results[i]
                       result.line_position = user.get_line_position(result.user)
                       if result.line_position != 0: result.line_position = output.ordinalize(result.line_position)
                       result.timestamp = time.mktime(result.timestamp.timetuple())
                       if result.end_time: result.end_time = time.mktime(result.end_time.timetuple())
                       if result.start_time: result.start_time = time.mktime(result.start_time.timetuple())
                       del result.user
                       results[i] = dict(result)

               return results

       @classmethod
       def start(klass, config_files):
               """Starts powerline, and loads up each config file in `config_files`."""
               for config_file in config_files:
                       cherrypy.config.update(config_file)

               cherrypy.quickstart(klass(), '/')


if __name__ == '__main__':
       if len(argv) == 1:
               print 'Usage: python -m powerline config_file [config_file...]'
               raise SystemExit(1)

       root.start(argv[1:])
je...@ubuntu:/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline$

XXXXXXXXXXXXXXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXXXXXXXXXXXXX


je...@ubuntu:/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline$ more database.py
# powerline.database - Database access
# (c) 2008 Pianohacker, licensed under the GPLv3

import dbwrap
from os import path
from powerline.lib.plugin import mount_point
from powerline import user_error
import datetime
from decimal import Decimal
import MySQLdb

user = ''
host = 'localhost'
password = ''
database = 'powerline'
charset = 'utf8'

def connect():
       """Returns a dbwrap'd connection to the MySQL database specified in config."""
       return dbwrap.wrapper(MySQLdb.connect(user = user, host = host, passwd = password, db = database, use_unicode = True, charset = charset), placeholder = '%s')

class user_checker(object):
       __metaclass__ = mount_point

class internal_checker(user_checker, dbwrap.table_ref):
       def __init__(self, connection):
               dbwrap.table_ref.__init__(self, connection, 'users')

       def verify(self, username = None):
               """Returns the user with `username`, and adds a key 'banned' which indicates whether the user is banned."""
               user = self.rows(username = username).select_one('*', 'allowed_after >= CURRENT_DATE AS banned')

               if not user:
                       raise KeyError(username)

               if user.banned:
                       return False, 'You are banned'
               else:
                       return True, ''

       def exists(self, username):
               return self.rows(username = username).exist()

class user_model(dbwrap.table_ref):
       def __init__(self, connection):
               dbwrap.table_ref.__init__(self, connection, 'users')
               self.checkers = [checker(connection) for checker in user_checker.plugins]

       def create(self, username):
               self.insert(username = username)
               self.con.commit()

       def exists(self, username):
               return self.rows(username = username).exist()

       def verify(self, username):
               exists = False

               for checker in self.checkers:
                       try:
                               verified, message = checker.verify(username)
                       except KeyError:
                               continue

                       exists = True

                       if not verified:
                               raise user_error(message)
               else:
                       if not exists:
                               raise user_error('User %s does not exist' % username)

       def get(self, username = None):
               """Returns the user with `username`, and adds a key 'banned' which indicates whether the user is banned."""
               user = self.rows(username = username).select_one('*', 'allowed_after >= CURRENT_DATE AS banned')

               if not user:
                       raise KeyError(user)

               return user

       def ban(self, username, until = datetime.date.max):
               """Bans `username` until `until` if specified, otherwise forever."""
               self.rows(username = username).update(allowed_after = until)
               self.con.commit()

       def delete(self, username):
               assert(self.exists(username))

               self.rows(username = username).delete()
               self.con.commit()

       def get_line_position(self, username):
               """Returns the position in line, counting from 1.

               If the user is already logged on, this returns -1. If they are ready to get on, it returns 0.
               """
               session = session_model(self.con)
               system = system_model(self.con)

               try:
                       reservation = session.get(username)

                       if reservation.start_time != None:
                               return -1

                       for i, row in enumerate(session.get_unstarted()):
                               if row.user == username:
                                       break
                       else:
                               raise user_error('fatal contradiction in get_line_position')

                       return max(0, i + 1 - system.get_num_open())
               except KeyError:
                       raise user_error('user does not have a reservation')

       __getitem__ = get


class system_model(dbwrap.table_ref):
       def __init__(self, connection):
               dbwrap.table_ref.__init__(self, connection, 'systems')

       def exists(self, system):
               return self.rows(name = system).exist()

       def create(self, name, title):
               self.insert(name = name, title = title)
               self.con.commit()

       def get(self, name):
               return self.select(name = name)

       def update(self, _name, **kwargs):
               """Update the system `_name` to the values in kwargs."""
               super(system_model, self).rows(name = _name).update(**kwargs)
               self.con.commit()

       def delete(self, name):
               super(system_model, self).rows(name = name).delete()
               self.con.commit()

       def get_open(self):
               """Returns the list of open systems."""
               return list(self.select('NOT EXISTS (SELECT session_id FROM sessions WHERE sessions.system = systems.name AND sessions.start_time IS NOT NULL AND sessions.end_t
ime IS NULL)'))

       def get_num_open(self):
               """Returns the number of open systems."""
               return self.rows('NOT EXISTS (SELECT session_id FROM sessions WHERE sessions.system = systems.name AND sessions.start_time IS NOT NULL AND sessions.end_time IS
NULL)').select_value('COUNT(*)')

       def all_open(self):
               """Returns whether all systems are open."""
               return len(self.all()) == self.get_num_open()

class session_model(dbwrap.table_ref):
       def __init__(self, connection):
               dbwrap.table_ref.__init__(self, connection, 'sessions')
               self.settings = settings_model(connection)
               self.users = user_model(connection)
               self.hours = hours_model(connection)

       def exists(self, username = None, **kwargs):
               return self.rows(**kwargs).exist() if kwargs else self.rows(user = username).exist()

       def create(self, username):
               """Creates a session from the specified `username`."""

               # A little housekeeping...
               self.rows('date(timestamp) < current_date AND start_time IS NULL').delete()

               if not self.hours.open_now():
                       raise user_error('Currently closed')

               self.users.verify(username)

               if self.rows(user = username, end_time = None).exist():
                       raise user_error('You have already reserved a computer')

               last = self.rows('date(timestamp) = current_date').select_value('max(daily_id)')
               daily_id = 1
               if last is not None:
                       daily_id = last + 1

               self.insert(user = username, daily_id = daily_id)
               self.con.commit()

       def delete(self, session_id):
               self.rows(session_id = session_id).delete()
               self.con.commit()

       def authenticate(self, session_id, system):
               """Registers the specified `session_id` on `system`."""
               self.rows(session_id = session_id).update(system = system)
               self.con.commit()

       def start(self, session_id):
               """Updates the start_time of of the session with `session_id` to the current time."""
               self.rows(session_id = session_id).update(start_time = datetime.datetime.now())
               self.con.commit()

       def end(self, session_id):
               """Updates the end_time of of the session with `session_id` to the current time."""
               self.rows(session_id = session_id).update(end_time = datetime.datetime.now())
               self.con.commit()

       def get(self, username = None, **kwargs):
               """If `username` is given, returns the first unended session for that user. Otherwise, it returns the session that matches `kwargs`."""
               results = self.select_one(**kwargs) if kwargs else self.select_one(user = username, end_time = None)

               if not results:
                       raise KeyError(username or kwargs)
               else:
                       return results

       __getitem__ = get

       def get_unstarted(self):
               """Returns the list of unstarted sessions."""
               return self.select('start_time IS NULL AND date(timestamp) = current_date ORDER BY timestamp')

       def get_unended(self):
               """Returns the list of unended sessions."""
               return self.select('end_time IS NULL AND date(timestamp) = current_date ORDER BY timestamp')

       def get_open_time(self):
               """Returns when a system is likely to open up."""
               settings = settings_model(self.con)

               last_session = self.select_one('start_time IS NOT NULL AND end_time IS NULL ORDER BY start_time DESC LIMIT 1')

               if last_session:
                       return last_session.start_time + datetime.timedelta(minutes = settings['session_time'])
               else:
                       return datetime.datetime.now()

class settings_model(dbwrap.table_ref):
       """A dict-like object that supports getting, setting and existence testing of settings.

       It also supports typed settings; if a setting is marked with a known type, then it is run through the function for that type.
       """
       types = {
               'int': int,
               'float': float,
               'decimal': lambda val: Decimal(str(val)),
               'list': lambda val: [subval.strip() for subval in val.split(',')],
       }

       def __init__(self, connection):
               dbwrap.table_ref.__init__(self, connection, 'settings')

       def __getitem__(self, key):
               result = self.select_one(name = key)
               if result:
                       if result.type in self.types:
                               return self.types[result.type](result.value)
                       else:
                               return result.value
               else:
                       raise KeyError(key)

       def __setitem__(self, key, value):
               if key in self:
                       info = self.get_info(key)
                       if info.type in self.types:
                               self.types[info.type](value)

                       self.rows(name = key).update(value = value)
               else:
                       self.insert(name = key, value = value)

               self.con.commit()

       def __contains__(self, key):
               return self.rows(name = key).exist()

       def get_info(self, key):
               """Returns the information for `key`, including its description and type."""
               result = self.select_one(name = key)

               if not result:
                       raise KeyError(key)
               else:
                       return result

       def register(self, key, value = '', type = 'none'):
               if key not in self:
                       self.insert(name = key, type = type, value = value)

       def __iter__(self):
               return ((row.name, self[row.name]) for row in self.all())

class hours_model(object):
       """A 'virtual' model, built on the 'hours' setting, that deals with hours."""
       def __init__(self, connection):
               self.settings = settings_model(connection)

       @staticmethod
       def _time_from_string(string):
               return datetime.datetime.strptime(string, '%H:%M').time()

       def all(self):
               """Returns the hours for every day of the week, as a list of 2-tuples of datetime.time's."""
               return [tuple(self._time_from_string(time) for time in day.split('-')) for day in self.settings['hours']]

       def get(self, weekday = None):
               """Returns the hours for `weekday` (specified numerically, starting from Sunday), if specified, otherwise today."""
               now = datetime.datetime.now()
               if weekday is None:
                       weekday = now.date().weekday()
                       weekday = 0 if weekday == 6 else weekday + 1

               return self.all()[weekday]

       def get_opening_time(self):
               """Returns the opening time for today."""
               return self.get()[0]

       def get_closing_time(self):
               """Returns the closing time for today."""
               return self.get()[1]

       def update(self, new_hours):
               """Updates hours from `new_hours`, a list of 2-tuples of datetime.time's."""
               assert len(new_hours) == 7 and all(len(hours) == 2 and type(hours[0]) == type(hours[1]) == datetime.time for hours in new_hours)

               self.settings['hours'] = ','.join('-'.join(hour.strftime('%H:%M') for hour in hours) for hours in new_hours)

       def open_now(self):
               """Returns whether we are currently open."""
               now = datetime.datetime.now().time()
               open, closing = self.get()

               return open <= now < closing
je...@ubuntu:/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline$

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

je...@ubuntu:/usr/lib/python2.5/site-packages/powerline-0.2.4-py2.5.egg/powerline$ ls
database.py   __init__.py   json.py   lib      main.pyc    manager.pyc  output.pyc  templates  web.py   xmlrpc.py
database.pyc  __init__.pyc  json.pyc  main.py  manager.py  output.py    plugins     tools      web.pyc  xmlrpc.pyc

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to