Use new-style classes everywhere

This commit is contained in:
Sunil Mohan Adapa 2014-06-06 18:21:54 +05:30
parent a958798769
commit ef493ae243
25 changed files with 117 additions and 86 deletions

View File

@ -10,12 +10,15 @@ import json
import UserDict import UserDict
import sqlite3 import sqlite3
class DefaultArg: class DefaultArg(object):
pass pass
class Solutions:
class Solutions(object):
Sqlite3 = 0 Sqlite3 = 0
class FileDict(UserDict.DictMixin): class FileDict(UserDict.DictMixin):
"A dictionary that stores its data persistantly in a file" "A dictionary that stores its data persistantly in a file"
@ -134,7 +137,7 @@ class FileDict(UserDict.DictMixin):
def batch(self): def batch(self):
return self._Batch(self) return self._Batch(self)
class _Batch: class _Batch(object):
def __init__(self, d): def __init__(self, d):
self.__d = d self.__d = d

View File

@ -6,7 +6,8 @@ cherrypy.log.error_file = cfg.status_log_file
cherrypy.log.access_file = cfg.access_log_file cherrypy.log.access_file = cfg.access_log_file
cherrypy.log.screen = False cherrypy.log.screen = False
class Logger():
class Logger(object):
"""By convention, log levels are DEBUG, INFO, WARNING, ERROR and CRITICAL.""" """By convention, log levels are DEBUG, INFO, WARNING, ERROR and CRITICAL."""
def log(self, msg, level="DEBUG"): def log(self, msg, level="DEBUG"):
try: try:

View File

@ -3,7 +3,7 @@ import cherrypy
import cfg import cfg
class Menu(): class Menu(object):
"""One menu item.""" """One menu item."""
def __init__(self, label="", icon="", url="#", order=50): def __init__(self, label="", icon="", url="#", order=50):
"""label is the text that is displayed on the menu. """label is the text that is displayed on the menu.

View File

@ -3,6 +3,8 @@ class User(dict):
is a bcrypt hash of the password), salt, groups, and an email address. is a bcrypt hash of the password), salt, groups, and an email address.
They can be blank or None, but the keys must exist. """ They can be blank or None, but the keys must exist. """
def __init__(self, dict=None): def __init__(self, dict=None):
super(User, self).__init__()
for key in ['username', 'name', 'passphrase', 'salt', 'email']: for key in ['username', 'name', 'passphrase', 'salt', 'email']:
self[key] = '' self[key] = ''
for key in ['groups']: for key in ['groups']:

View File

@ -6,8 +6,9 @@ import util
class Apps(PagePlugin): class Apps(PagePlugin):
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Apps, self).__init__()
self.register_page("apps") self.register_page("apps")
self.menu = cfg.main_menu.add_item("Apps", "icon-download-alt", "/apps", 80) self.menu = cfg.main_menu.add_item("Apps", "icon-download-alt", "/apps", 80)
self.menu.add_item("Chat", "icon-comment", "/../jwchat", 30) self.menu.add_item("Chat", "icon-comment", "/../jwchat", 30)

View File

@ -91,9 +91,8 @@ and must not be greater than 63 characters in length.'),
class Configuration(PagePlugin): class Configuration(PagePlugin):
"""System configuration page""" """System configuration page"""
def __init__(self, *args, **kwargs): def __init__(self):
del args # Unused super(Configuration, self).__init__()
del kwargs # Unused
self.register_page('sys.config') self.register_page('sys.config')

View File

@ -28,10 +28,11 @@ import cfg
import util import util
class diagnostics(PagePlugin): class Diagnostics(PagePlugin):
order = 30 order = 30
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Diagnostics, self).__init__()
self.register_page("sys.diagnostics") self.register_page("sys.diagnostics")
cfg.html_root.sys.menu.add_item("Diagnostics", "icon-screenshot", "/sys/diagnostics", 30) cfg.html_root.sys.menu.add_item("Diagnostics", "icon-screenshot", "/sys/diagnostics", 30)
@ -41,10 +42,11 @@ class diagnostics(PagePlugin):
return util.render_template(template='diagnostics', return util.render_template(template='diagnostics',
title=_('System Diagnostics')) title=_('System Diagnostics'))
class test(PagePlugin): class Test(PagePlugin):
order = 31 order = 31
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Test, self).__init__()
self.register_page("sys.diagnostics.test") self.register_page("sys.diagnostics.test")
@cherrypy.expose @cherrypy.expose

View File

@ -22,8 +22,9 @@ class Experts(PagePlugin):
"""Expert forms page""" """Expert forms page"""
order = 60 order = 60
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Experts, self).__init__()
self.register_page('sys.expert') self.register_page('sys.expert')
cfg.html_root.sys.menu.add_item(_('Expert Mode'), 'icon-cog', cfg.html_root.sys.menu.add_item(_('Expert Mode'), 'icon-cog',

View File

@ -34,8 +34,8 @@ class Firewall(PagePlugin):
"""Firewall menu entry and introduction page""" """Firewall menu entry and introduction page"""
order = 40 order = 40
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Firewall, self).__init__()
self.register_page('sys.firewall') self.register_page('sys.firewall')
cfg.html_root.sys.menu.add_item(_('Firewall'), 'icon-flag', cfg.html_root.sys.menu.add_item(_('Firewall'), 'icon-flag',

View File

@ -69,8 +69,8 @@ FreedomBox!'))
class FirstBoot(PagePlugin): class FirstBoot(PagePlugin):
"""First boot wizard""" """First boot wizard"""
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(FirstBoot, self).__init__()
# this is the url this page will hang off of (/firstboot) # this is the url this page will hang off of (/firstboot)
self.register_page('firstboot') self.register_page('firstboot')

View File

@ -8,15 +8,17 @@ import util
class Help(PagePlugin): class Help(PagePlugin):
order = 20 # order of running init in PagePlugins order = 20 # order of running init in PagePlugins
def __init__(self, *args, **kwargs):
PagePlugin.__init__(self, *args, **kwargs) def __init__(self):
super(Help, self).__init__()
self.register_page("help") self.register_page("help")
self.menu = cfg.main_menu.add_item(_("Documentation"), "icon-book", "/help", 101) self.menu = cfg.main_menu.add_item(_("Documentation"), "icon-book", "/help", 101)
self.menu.add_item(_("Where to Get Help"), "icon-search", "/help/index", 5) self.menu.add_item(_("Where to Get Help"), "icon-search", "/help/index", 5)
self.menu.add_item(_("Developer's Manual"), "icon-info-sign", "/help/view/plinth", 10) self.menu.add_item(_("Developer's Manual"), "icon-info-sign", "/help/view/plinth", 10)
self.menu.add_item(_("FAQ"), "icon-question-sign", "/help/view/faq", 20) self.menu.add_item(_("FAQ"), "icon-question-sign", "/help/view/faq", 20)
self.menu.add_item(_("%s Wiki" % cfg.box_name), "icon-pencil", "http://wiki.debian.org/FreedomBox", 30) self.menu.add_item(_("%s Wiki" % cfg.box_name), "icon-pencil", "http://wiki.debian.org/FreedomBox", 30)
self.menu.add_item(_("About"), "icon-star", "/help/about", 100) self.menu.add_item(_("About"), "icon-star", "/help/about", 100)
@cherrypy.expose @cherrypy.expose
def index(self): def index(self):
@ -31,8 +33,9 @@ class Help(PagePlugin):
class View(PagePlugin): class View(PagePlugin):
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(View, self).__init__()
self.register_page("help.view") self.register_page("help.view")
@cherrypy.expose @cherrypy.expose

View File

@ -36,8 +36,8 @@ class LoginForm(forms.Form): # pylint: disable-msg=W0232
class AuthController(PagePlugin): class AuthController(PagePlugin):
"""Login and logout pages""" """Login and logout pages"""
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(AuthController, self).__init__()
self.register_page('auth') self.register_page('auth')

View File

@ -4,8 +4,11 @@ from model import User
from plugin_mount import UserStoreModule from plugin_mount import UserStoreModule
from withsqlite.withsqlite import sqlite_db from withsqlite.withsqlite import sqlite_db
class UserStore(UserStoreModule, sqlite_db): class UserStore(UserStoreModule, sqlite_db):
def __init__(self): def __init__(self):
super(UserStore, self).__init__()
self.db_file = cfg.user_db self.db_file = cfg.user_db
sqlite_db.__init__(self, self.db_file, autocommit=True, check_same_thread=False) sqlite_db.__init__(self, self.db_file, autocommit=True, check_same_thread=False)
self.__enter__() self.__enter__()

View File

@ -22,8 +22,9 @@ class OwnCloud(PagePlugin):
"""ownCloud configuration page""" """ownCloud configuration page"""
order = 90 order = 90
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(OwnCloud, self).__init__()
self.register_page('apps.owncloud') self.register_page('apps.owncloud')
cfg.html_root.apps.menu.add_item('Owncloud', 'icon-picture', cfg.html_root.apps.menu.add_item('Owncloud', 'icon-picture',

View File

@ -48,8 +48,9 @@ class Packages(PagePlugin):
"""Package page""" """Package page"""
order = 20 order = 20
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Packages, self).__init__()
self.register_page('sys.packages') self.register_page('sys.packages')
cfg.html_root.sys.menu.add_item('Package Manager', 'icon-gift', cfg.html_root.sys.menu.add_item('Package Manager', 'icon-gift',

View File

@ -35,8 +35,8 @@ class PageKite(PagePlugin):
"""PageKite menu entry and introduction page""" """PageKite menu entry and introduction page"""
order = 60 order = 60
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(PageKite, self).__init__()
self.register_page("apps.pagekite") self.register_page("apps.pagekite")
cfg.html_root.apps.menu.add_item( cfg.html_root.apps.menu.add_item(
@ -109,8 +109,8 @@ class Configure(PagePlugin): # pylint: disable-msg=C0103
"""Main configuration form""" """Main configuration form"""
order = 65 order = 65
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Configure, self).__init__()
self.register_page("apps.pagekite.configure") self.register_page("apps.pagekite.configure")

View File

@ -23,14 +23,15 @@ santiago_port = 52854
# return True # return True
class Santiago(PagePlugin): class Santiago(PagePlugin):
order = 90 # order of running init in PagePlugins order = 90 # order of running init in PagePlugins
def __init__(self, *args, **kwargs): def __init__(self):
super(Santiago, self).__init__()
self.register_page("santiago") self.register_page("santiago")
self.santiago_address = self.get_santiago_address() #TODO: multiple santiago ports self.santiago_address = self.get_santiago_address() #TODO: multiple santiago ports
#set a listener on the santiago address #set a listener on the santiago address
def get_santiago_address(self): def get_santiago_address(self):
if 'santiago' in cfg.users['admin'] and 'address' in cfg.users['admin']['santiago']: if 'santiago' in cfg.users['admin'] and 'address' in cfg.users['admin']['santiago']:
return cfg.users['admin']['santiago']['address'] return cfg.users['admin']['santiago']['address']
else: else:
@ -54,11 +55,11 @@ class Santiago(PagePlugin):
print "Need to add these two lines to /etc/torrc:\n%s" % hidden_service_config print "Need to add these two lines to /etc/torrc:\n%s" % hidden_service_config
return "" return ""
def check_for_hidden_service(self): def check_for_hidden_service(self):
pass pass
@cherrypy.expose @cherrypy.expose
def index(self, *args, **kw): def index(self, *args, **kw):
""" """
A request is a dict with some required keys: A request is a dict with some required keys:
@ -111,12 +112,13 @@ class Santiago(PagePlugin):
## Plinth page to config santiago ## Plinth page to config santiago
class santiago(PagePlugin): class santiago(PagePlugin):
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Santiago, self).__init__(self)
self.menu = cfg.html_root.privacy.menu.add_item("Santiago", "icon-leaf", "/privacy/santiago", 10)
self.register_page("privacy.santiago")
@cherrypy.expose self.menu = cfg.html_root.privacy.menu.add_item("Santiago", "icon-leaf", "/privacy/santiago", 10)
@require() self.register_page("privacy.santiago")
def index(self):
return "Santiago's config goes here." @cherrypy.expose
@require()
def index(self):
return "Santiago's config goes here."

View File

@ -4,16 +4,16 @@ from plugin_mount import PagePlugin
import cfg import cfg
import util import util
sys_dir = "modules/installed/sys"
class Sys(PagePlugin): class Sys(PagePlugin):
order = 10 order = 10
def __init__(self, *args, **kwargs):
PagePlugin.__init__(self, *args, **kwargs) def __init__(self):
super(Sys, self).__init__()
self.register_page("sys") self.register_page("sys")
self.menu = cfg.main_menu.add_item(_("System"), "icon-cog", "/sys", 100) self.menu = cfg.main_menu.add_item(_("System"), "icon-cog", "/sys", 100)
self.menu.add_item(_("Users and Groups"), "icon-user", "/sys/users", 15) self.menu.add_item(_("Users and Groups"), "icon-user", "/sys/users", 15)
@cherrypy.expose @cherrypy.expose
def index(self): def index(self):

View File

@ -28,10 +28,12 @@ import cfg
import util import util
class tor(PagePlugin): class Tor(PagePlugin):
order = 60 # order of running init in PagePlugins order = 60 # order of running init in PagePlugins
def __init__(self, *args, **kwargs):
PagePlugin.__init__(self, *args, **kwargs) def __init__(self):
super(Tor, self).__init__()
self.register_page("apps.tor") self.register_page("apps.tor")
cfg.html_root.apps.menu.add_item("Tor", "icon-eye-close", "/apps/tor", cfg.html_root.apps.menu.add_item("Tor", "icon-eye-close", "/apps/tor",
30) 30)

View File

@ -11,8 +11,10 @@ import util
class Users(PagePlugin): class Users(PagePlugin):
order = 20 # order of running init in PagePlugins order = 20 # order of running init in PagePlugins
def __init__(self, *args, **kwargs):
PagePlugin.__init__(self, *args, **kwargs) def __init__(self):
super(Users, self).__init__()
self.register_page("sys.users") self.register_page("sys.users")
@staticmethod @staticmethod
@ -52,8 +54,8 @@ class UserAdd(PagePlugin):
"""Add user page""" """Add user page"""
order = 30 order = 30
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(UserAdd, self).__init__()
self.register_page('sys.users.add') self.register_page('sys.users.add')
@ -112,8 +114,8 @@ class UserEdit(PagePlugin):
"""User edit page""" """User edit page"""
order = 35 order = 35
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(UserEdit, self).__init__()
self.register_page('sys.users.edit') self.register_page('sys.users.edit')

View File

@ -20,11 +20,12 @@ class XMPP(PagePlugin):
"""XMPP Page""" """XMPP Page"""
order = 60 order = 60
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(XMPP, self).__init__()
self.register_page('apps.xmpp') self.register_page('apps.xmpp')
cfg.html_root.apps.menu.add_item('XMPP', 'icon-comment', cfg.html_root.apps.menu.add_item('XMPP', 'icon-comment',
'/apps/xmpp', 40) '/apps/xmpp', 40)
self.client_service = service.Service( self.client_service = service.Service(
'xmpp-client', _('Chat Server - client connections'), 'xmpp-client', _('Chat Server - client connections'),
@ -66,9 +67,10 @@ class Configure(PagePlugin):
"""Configuration page""" """Configuration page"""
order = 65 order = 65
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Configure, self).__init__()
self.register_page("apps.xmpp.configure")
self.register_page('apps.xmpp.configure')
@cherrypy.expose @cherrypy.expose
@require() @require()
@ -148,8 +150,9 @@ class Register(PagePlugin):
"""User registration page""" """User registration page"""
order = 65 order = 65
def __init__(self, *args, **kwargs): def __init__(self):
PagePlugin.__init__(self, *args, **kwargs) super(Register, self).__init__()
self.register_page('apps.xmpp.register') self.register_page('apps.xmpp.register')
@cherrypy.expose @cherrypy.expose

View File

@ -18,10 +18,14 @@ class PluginMount(type):
def get_plugins(cls, *args, **kwargs): def get_plugins(cls, *args, **kwargs):
return cls.init_plugins(*args, **kwargs) return cls.init_plugins(*args, **kwargs)
class MultiplePluginViolation:
class MultiplePluginViolation(Exception):
"""Multiple plugins found for a type where only one is expected"""
pass pass
class PluginMountSingular(PluginMount): class PluginMountSingular(PluginMount):
"""Plugin mounter that allows only one plugin of this meta type"""
def __init__(cls, name, bases, attrs): def __init__(cls, name, bases, attrs):
if not hasattr(cls, 'plugins'): if not hasattr(cls, 'plugins'):
cls.plugins = [] cls.plugins = []
@ -29,7 +33,7 @@ class PluginMountSingular(PluginMount):
if len(cls.plugins) > 0: if len(cls.plugins) > 0:
raise MultiplePluginViolation raise MultiplePluginViolation
cls.plugins.append(cls) cls.plugins.append(cls)
def _setattr_deep(obj, path, value): def _setattr_deep(obj, path, value):
"""If path is 'x.y.z' or ['x', 'y', 'z'] then perform obj.x.y.z = value""" """If path is 'x.y.z' or ['x', 'y', 'z'] then perform obj.x.y.z = value"""
@ -42,7 +46,7 @@ def _setattr_deep(obj, path, value):
setattr(obj, path[-1], value) setattr(obj, path[-1], value)
class PagePlugin: class PagePlugin(object):
""" """
Mount point for page plugins. Page plugins provide display pages Mount point for page plugins. Page plugins provide display pages
in the interface (one menu item, for example). in the interface (one menu item, for example).
@ -53,18 +57,20 @@ class PagePlugin:
order = 50 order = 50
__metaclass__ = PluginMount __metaclass__ = PluginMount
def __init__(self, *args, **kwargs):
def __init__(self):
"""If cfg.html_root is none, then this is the html_root.""" """If cfg.html_root is none, then this is the html_root."""
if not cfg.html_root: if not cfg.html_root:
cfg.log('Setting html root to %s' % self.__class__.__name__) cfg.log('Setting html root to %s' % self.__class__.__name__)
cfg.html_root = self cfg.html_root = self
def register_page(self, url): def register_page(self, url):
"""Add a page to the page tree structure"""
cfg.log.info("Registering page: %s" % url) cfg.log.info("Registering page: %s" % url)
_setattr_deep(cfg.html_root, url, self) _setattr_deep(cfg.html_root, url, self)
class UserStoreModule: class UserStoreModule(object):
""" """
Mount Point for plugins that will manage the user backend storage, Mount Point for plugins that will manage the user backend storage,
where we keep a hash for each user. where we keep a hash for each user.
@ -79,5 +85,5 @@ class UserStoreModule:
compatibility with third party software. A future version of compatibility with third party software. A future version of
Plinth is likely to require LDAP. Plinth is likely to require LDAP.
""" """
__metaclass__ = PluginMountSingular # singular because we can only use one user store at a time # Singular because we can only use one user store at a time
__metaclass__ = PluginMountSingular

View File

@ -5,7 +5,6 @@ from actions import superuser_run, run
import os import os
import shlex import shlex
import subprocess import subprocess
import sys
import unittest import unittest
class TestPrivileged(unittest.TestCase): class TestPrivileged(unittest.TestCase):

View File

@ -1,18 +1,18 @@
#! /usr/bin/env python #! /usr/bin/env python
# -*- mode: python; mode: auto-fill; fill-column: 80 -*- # -*- mode: python; mode: auto-fill; fill-column: 80 -*-
import user_store, auth import auth
from logger import Logger from logger import Logger
import cfg import cfg
import unittest import unittest
import cherrypy import cherrypy
import plugin_mount import plugin_mount
import os import os
from model import User
cfg.log = Logger() cfg.log = Logger()
cherrypy.log.access_file = None cherrypy.log.access_file = None
class Auth(unittest.TestCase): class Auth(unittest.TestCase):
"""Test check_credentials function of auth to confirm it works as expected""" """Test check_credentials function of auth to confirm it works as expected"""

View File

@ -1,7 +1,6 @@
#! /usr/bin/env python #! /usr/bin/env python
# -*- mode: python; mode: auto-fill; fill-column: 80 -*- # -*- mode: python; mode: auto-fill; fill-column: 80 -*-
import user_store
from logger import Logger from logger import Logger
import cfg import cfg
import unittest import unittest
@ -13,6 +12,7 @@ cfg.log = Logger()
cherrypy.log.access_file = None cherrypy.log.access_file = None
class UserStore(unittest.TestCase): class UserStore(unittest.TestCase):
"""Test each function of user_store to confirm they work as expected""" """Test each function of user_store to confirm they work as expected"""
@ -83,4 +83,4 @@ class UserStore(unittest.TestCase):
return user return user
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()