Commit 546dde7d authored by Fred Drake's avatar Fred Drake

Add the App.config module and use the API it exports to get configuration

values.
parent 4c346558
......@@ -8,6 +8,12 @@ Zope Changes
Features added
- New module: App.config. New API for getting a configuration
object. This should be the preferred way for all code in Zope
to get configured values for many settings. For settings made
available via this module, alternate locations are deprecated,
though will to be supported for Zope 2.7.
- Collector #435: Support for passwords encoded using MySQL's
PASSWORD() function add to lib/python/AccessControl/AuthEncoding.py.
......
......@@ -12,7 +12,7 @@
##############################################################################
"""Access control package"""
__version__='$Revision: 1.175 $'[11:-2]
__version__='$Revision: 1.176 $'[11:-2]
import Globals, socket, SpecialUsers,re
import os
......@@ -387,11 +387,13 @@ class NullUnrestrictedUser(SpecialUser):
def readUserAccessFile(filename):
'''Reads an access file from INSTANCE_HOME.
'''Reads an access file from the instance home.
Returns name, password, domains, remote_user_mode.
'''
import App.config
cfg = App.config.getConfiguration()
try:
f = open(os.path.join(INSTANCE_HOME, filename), 'r')
f = open(os.path.join(cfg.instancehome, filename), 'r')
line = f.readline()
f.close()
except IOError:
......@@ -1034,7 +1036,8 @@ class UserFolder(BasicUserFolder):
def _doChangeUser(self, name, password, roles, domains, **kw):
user=self.data[name]
if password is not None:
if self.encrypt_passwords and not self._isPasswordEncrypted(password):
if ( self.encrypt_passwords
and not self._isPasswordEncrypted(password)):
password = self._encryptPassword(password)
user.__=password
user.roles=roles
......@@ -1047,7 +1050,7 @@ class UserFolder(BasicUserFolder):
def _createInitialUser(self):
"""
If there are no users or only one user in this user folder,
populates from the 'inituser' file in INSTANCE_HOME.
populates from the 'inituser' file in the instance home.
We have to do this even when there is already a user
just in case the initial user ignored the setup messages.
We don't do it for more than one user to avoid
......@@ -1057,11 +1060,13 @@ class UserFolder(BasicUserFolder):
if len(self.data) <= 1:
info = readUserAccessFile('inituser')
if info:
import App.config
name, password, domains, remote_user_mode = info
self._doDelUsers(self.getUserNames())
self._doAddUser(name, password, ('Manager',), domains)
cfg = App.config.getConfiguration()
try:
os.remove(os.path.join(INSTANCE_HOME, 'inituser'))
os.remove(os.path.join(cfg.instancehome, 'inituser'))
except:
pass
......
......@@ -12,7 +12,7 @@
##############################################################################
__doc__="""System management components"""
__version__='$Revision: 1.85 $'[11:-2]
__version__='$Revision: 1.86 $'[11:-2]
import sys,os,time,Globals, Acquisition, os, Undo
from Globals import DTMLFile
......@@ -22,6 +22,7 @@ from CacheManager import CacheManager
from DavLockManager import DavLockManager
from DateTime.DateTime import DateTime
from OFS import SimpleItem
from App.config import getConfiguration
from App.Dialogs import MessageDialog
from Product import ProductFolder
from version_txt import version_txt
......@@ -374,7 +375,8 @@ class ApplicationManager(Folder,CacheManager):
isdir=os.path.isdir
exists=os.path.exists
product_dir=path_join(SOFTWARE_HOME,'Products')
cfg = getConfiguration()
product_dir=path_join(cfg.softwarehome,'Products')
product_names=os.listdir(product_dir)
product_names.sort()
info=[]
......@@ -424,16 +426,16 @@ class ApplicationManager(Folder,CacheManager):
REQUEST['RESPONSE'].redirect(REQUEST['URL1']+'/manage_main')
def getSOFTWARE_HOME(self):
return SOFTWARE_HOME
return getConfiguration().softwarehome
def getZOPE_HOME(self):
return ZOPE_HOME
return getConfiguration().zopehome
def getINSTANCE_HOME(self):
return INSTANCE_HOME
return getConfiguration().instancehome
def getCLIENT_HOME(self):
return CLIENT_HOME
return getConfiguration().clienthome
def objectIds(self, spec=None):
""" this is a patch for pre-2.4 Zope installations. Such
......
......@@ -14,8 +14,8 @@ __doc__='''Standard routines for handling extensions.
Extensions currently include external methods and pluggable brains.
$Id: Extensions.py,v 1.20 2003/02/10 18:26:03 fdrake Exp $'''
__version__='$Revision: 1.20 $'[11:-2]
$Id: Extensions.py,v 1.21 2003/02/11 17:17:04 fdrake Exp $'''
__version__='$Revision: 1.21 $'[11:-2]
import os, zlib, rotor, imp
import Products
......@@ -69,9 +69,9 @@ def getPath(prefix, name, checkProduct=1, suffixes=('',)):
suffixes -- a sequences of file suffixes to check.
By default, the name is used without a suffix.
The search takes on multiple homes which are INSTANCE_HOME,
the directory containing the directory containing SOFTWARE_HOME, and
possibly product areas.
The search takes on multiple homes which are the instance home,
the directory containing the directory containing the software
home, and possibly product areas.
"""
d,n = path_split(name)
if d: raise ValueError, (
......@@ -86,8 +86,10 @@ def getPath(prefix, name, checkProduct=1, suffixes=('',)):
r = _getPath(product_dir, os.path.join(p, prefix), n, suffixes)
if r is not None: return r
sw=path_split(path_split(SOFTWARE_HOME)[0])[0]
for home in (INSTANCE_HOME, sw):
import App.config
cfg = App.config.getConfiguration()
sw=os.path.dirname(os.path.dirname(cfg.softwarehome))
for home in (cfg.instancehome, sw):
r=_getPath(home, prefix, name, suffixes)
if r is not None: return r
......@@ -98,7 +100,7 @@ def getObject(module, name, reload=0,
):
# The use of modules here is not thread safe, however, there is
# no real harm in a rece condition here. If two threads
# no real harm in a race condition here. If two threads
# update the cache, then one will have simply worked a little
# harder than need be. So, in this case, we won't incur
# the expense of a lock.
......@@ -118,7 +120,6 @@ def getObject(module, name, reload=0,
__traceback_info__=p, module
base, ext = os.path.splitext(p)
if ext=='.pyc':
file = open(p, 'rb')
......
......@@ -12,23 +12,25 @@
##############################################################################
"""Image object that is stored in a file"""
__version__='$Revision: 1.18 $'[11:-2]
__version__='$Revision: 1.19 $'[11:-2]
import os
import time
from App.config import getConfiguration
from OFS.content_types import guess_content_type
from Globals import package_home
from Common import rfc1123_date
from DateTime import DateTime
from time import time
from os import stat
import Acquisition
import Globals
import os
class ImageFile(Acquisition.Explicit):
"""Image objects stored in external files."""
def __init__(self,path,_prefix=None):
if _prefix is None: _prefix=SOFTWARE_HOME
if _prefix is None:
_prefix=getConfiguration().softwarehome
elif type(_prefix) is not type(''):
_prefix=package_home(_prefix)
path = os.path.join(_prefix, path)
......@@ -50,7 +52,7 @@ class ImageFile(Acquisition.Explicit):
else:
self.content_type='image/%s' % path[path.rfind('.')+1:]
self.__name__=path[path.rfind('/')+1:]
self.lmt=float(stat(path)[8]) or time()
self.lmt=float(os.stat(path)[8]) or time.time()
self.lmh=rfc1123_date(self.lmt)
......
......@@ -47,6 +47,7 @@ import ZClasses, ZClasses.ZClass
from HelpSys.HelpSys import ProductHelp
import RefreshFuncs
from AccessControl import Unauthorized
from App.config import getConfiguration
class ProductFolder(Folder):
......@@ -207,7 +208,7 @@ class Product(Folder, PermissionManager):
# Extensions
pp=id+'.'
lpp=len(pp)
ed=os.path.join(INSTANCE_HOME,'Extensions')
ed=os.path.join(getConfiguration().instancehome,'Extensions')
if os.path.exists(ed):
for name in os.listdir(ed):
suffix=''
......
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Simple access to configuration values.
The configuration values are represented as a single object with
attributes for each bit of information.
"""
_config = None
def getConfiguration():
"""Return the global Zope configuration object.
If a configuration hasn't been set yet, generates a simple
configuration object and uses that. Once generated, it may not be
overridden by calling ``setConfiguration()``.
"""
if _config is None:
setConfiguration(DefaultConfiguration())
return _config
def setConfiguration(cfg):
"""Set the global configuration object.
Legacy sources of common configuraiton values are updated to
reflect the new configuration; this may be removed in some future
version.
"""
global _config
_config = cfg
from App import FindHomes
import __builtin__
__builtin__.CLIENT_HOME = FindHomes.CLIENT_HOME = cfg.clienthome
__builtin__.INSTANCE_HOME = FindHomes.INSTANCE_HOME = cfg.instancehome
__builtin__.SOFTWARE_HOME = FindHomes.SOFTWARE_HOME = cfg.softwarehome
__builtin__.ZOPE_HOME = FindHomes.ZOPE_HOME = cfg.zopehome
import sys
if "Globals" in sys.modules:
# XXX We *really* want to avoid this if Globals hasn't already
# been imported, due to circular imports. ;-(
import Globals
Globals.data_dir = cfg.clienthome
# Globals does not export CLIENT_HOME
Globals.INSTANCE_HOME = cfg.instancehome
Globals.SOFTWARE_HOME = cfg.softwarehome
Globals.ZOPE_HOME = cfg.zopehome
class DefaultConfiguration:
def __init__(self):
from App import FindHomes
self.clienthome = FindHomes.CLIENT_HOME
self.instancehome = FindHomes.INSTANCE_HOME
self.softwarehome = FindHomes.SOFTWARE_HOME
self.zopehome = FindHomes.ZOPE_HOME
......@@ -14,6 +14,7 @@
import DocumentTemplate, Common, Persistence, MethodObject, Globals, os, sys
from types import InstanceType
from zLOG import LOG,WARNING
from App.config import getConfiguration
class HTML(DocumentTemplate.HTML,Persistence.Persistent,):
"Persistent HTML Document Templates"
......@@ -29,7 +30,7 @@ class ClassicHTMLFile(DocumentTemplate.HTMLFile,MethodObject.Method,):
_v_last_read=0
def __init__(self,name,_prefix=None, **kw):
if _prefix is None: _prefix=SOFTWARE_HOME
if _prefix is None: _prefix=getConfiguration().softwarehome
elif type(_prefix) is not type(''):
_prefix=Common.package_home(_prefix)
args=(self, os.path.join(_prefix, name + '.dtml'))
......
......@@ -13,6 +13,8 @@
import os,sys,re
from App.config import getConfiguration
v=sys.version_info
_version_string = None
......@@ -38,7 +40,8 @@ def _prep_version_data():
global _version_string, _zope_version
if _version_string is None:
try:
s = open(os.path.join(SOFTWARE_HOME,'version.txt')).read()
cfg = getConfiguration()
s = open(os.path.join(cfg.softwarehome,'version.txt')).read()
ss = re.sub("\(.*?\)\?","",s)
ss = '%s, python %d.%d.%d, %s' % (ss,v[0],v[1],v[2],sys.platform)
_version_string = ss
......
......@@ -13,7 +13,7 @@
"""Global definitions"""
__version__='$Revision: 1.53 $'[11:-2]
__version__='$Revision: 1.54 $'[11:-2]
# Global constants: __replaceable__ flags:
NOT_REPLACEABLE = 0
......@@ -23,8 +23,8 @@ UNIQUE = 2
import Acquisition, ComputedAttribute, App.PersistentExtra, os
import TreeDisplay
from App.FindHomes import INSTANCE_HOME, SOFTWARE_HOME, ZOPE_HOME
from App.Common import package_home, attrget, Dictionary
from App.config import getConfiguration as _getConfiguration
from Persistence import Persistent, PersistentMapping
from App.special_dtml import HTML, HTMLFile, DTMLFile
from App.class_init import default__class_init__, ApplicationDefaultPermissions
......@@ -37,7 +37,14 @@ from App.ImageFile import ImageFile
VersionNameName='Zope-Version'
data_dir = os.path.join(INSTANCE_HOME, 'var')
_cfg = _getConfiguration()
data_dir = _cfg.clienthome
# backward compatibility
INSTANCE_HOME = _cfg.instancehome
SOFTWARE_HOME = _cfg.softwarehome
ZOPE_HOME = _cfg.zopehome
opened=[]
# Check,if DEBUG variables are set
......
......@@ -12,8 +12,8 @@
##############################################################################
__doc__='''Application support
$Id: Application.py,v 1.188 2002/08/20 19:37:52 jim Exp $'''
__version__='$Revision: 1.188 $'[11:-2]
$Id: Application.py,v 1.189 2003/02/11 17:17:05 fdrake Exp $'''
__version__='$Revision: 1.189 $'[11:-2]
import Globals,Folder,os,sys,App.Product, App.ProductRegistry, misc_
import time, traceback, os, Products
......@@ -373,13 +373,13 @@ def initialize(app):
# However, make sure that if the examples have been added already
# and then deleted that we don't add them again.
if not hasattr(app, 'Examples') and not \
hasattr(app, '_Zope25_examples_have_been_added'):
examples_path = os.path.join(Globals.ZOPE_HOME, \
'import', 'Examples.zexp')
import App.config
cfg = App.config.getConfiguration()
examples_path = os.path.join(cfg.zopehome, 'import',
'Examples.zexp')
if os.path.isfile(examples_path):
app._importObjectFromFile(examples_path, verify=0)
app._Zope25_examples_have_been_added=1
......
......@@ -12,9 +12,9 @@
##############################################################################
__doc__="""Object Manager
$Id: ObjectManager.py,v 1.161 2003/02/04 06:48:26 anthony Exp $"""
$Id: ObjectManager.py,v 1.162 2003/02/11 17:17:06 fdrake Exp $"""
__version__='$Revision: 1.161 $'[11:-2]
__version__='$Revision: 1.162 $'[11:-2]
import App.Management, Acquisition, Globals, CopySupport, Products
import os, App.FactoryDispatcher, re, Products
......@@ -32,6 +32,7 @@ from urllib import quote
from cStringIO import StringIO
import marshal
import App.Common
from App.config import getConfiguration
from AccessControl import getSecurityManager
from zLOG import LOG, ERROR
import sys,fnmatch,copy
......@@ -499,7 +500,8 @@ class ObjectManager(
'inline;filename=%s.%s' % (id, suffix))
return f.getvalue()
f = os.path.join(CLIENT_HOME, '%s.%s' % (id, suffix))
cfg = getConfiguration()
f = os.path.join(cfg.clienthome, '%s.%s' % (id, suffix))
if toxml:
XMLExportImport.exportXML(ob._p_jar, ob._p_oid, f)
else:
......@@ -520,8 +522,9 @@ class ObjectManager(
if dirname:
raise BadRequestException, 'Invalid file name %s' % escape(file)
instance_home = INSTANCE_HOME
zope_home = ZOPE_HOME
cfg = getConfiguration()
instance_home = cfg.instancehome
zope_home = cfg.zopehome
for impath in (instance_home, zope_home):
filepath = os.path.join(impath, 'import', file)
......
......@@ -14,29 +14,29 @@
"""
Revision information:
$Id: testExternalMethod.py,v 1.5 2002/08/14 22:14:11 mj Exp $
$Id: testExternalMethod.py,v 1.6 2003/02/11 17:17:06 fdrake Exp $
"""
import math, os
from unittest import TestCase, TestSuite, main, makeSuite
import math
import os
import unittest
import ZODB # dead goat
import Products.ExternalMethod.tests
from Products.ExternalMethod.ExternalMethod import ExternalMethod
import App.config
builtinsdict = getattr(__builtins__, '__dict__', __builtins__)
class Test(TestCase):
class TestExternalMethod(unittest.TestCase):
def setUp(self):
self._old = builtinsdict.get('INSTANCE_HOME')
builtinsdict['INSTANCE_HOME'] = os.path.split(
Products.ExternalMethod.tests.__file__)[0]
self._old = App.config.getConfiguration()
cfg = App.config.DefaultConfiguration()
cfg.instancehome = os.path.dirname(
Products.ExternalMethod.tests.__file__)
App.config.setConfiguration(cfg)
def tearDown(self):
if self._old is None:
del builtinsdict['INSTANCE_HOME']
else:
builtinsdict['INSTANCE_HOME'] = self._old
App.config.setConfiguration(self._old)
def testStorage(self):
em1 = ExternalMethod('em', 'test method', 'Test', 'testf')
......@@ -60,9 +60,7 @@ class Test(TestCase):
def test_suite():
return TestSuite((
makeSuite(Test),
))
return unittest.makeSuite(TestExternalMethod)
def package_home(globals_dict):
......@@ -71,11 +69,11 @@ def package_home(globals_dict):
if hasattr(m,'__path__'):
r=m.__path__[0]
elif "." in __name__:
r=sys.modules[__name__[:rfind(__name__,'.')]].__path__[0]
r=sys.modules[__name__.split('.',1)[0]].__path__[0]
else:
r=__name__
return os.path.join(os.getcwd(), r)
return os.path.abspath(r)
if __name__=='__main__':
main(defaultTest='test_suite')
unittest.main(defaultTest='test_suite')
......@@ -15,7 +15,7 @@
Zope object encapsulating a Page Template from the filesystem.
"""
__version__='$Revision: 1.22 $'[11:-2]
__version__='$Revision: 1.23 $'[11:-2]
import os, AccessControl, Acquisition, sys
from Globals import package_home, DevelopmentMode
......@@ -29,6 +29,7 @@ from Expressions import SecureModuleImporter
from ComputedAttribute import ComputedAttribute
from ExtensionClass import Base
from Acquisition import aq_parent, aq_inner
from App.config import getConfiguration
class PageTemplateFile(Script, PageTemplate, Traversable):
"Zope wrapper for filesystem Page Template using TAL, TALES, and METAL"
......@@ -48,7 +49,8 @@ class PageTemplateFile(Script, PageTemplate, Traversable):
def __init__(self, filename, _prefix=None, **kw):
self.ZBindings_edit(self._default_bindings)
if _prefix is None: _prefix=SOFTWARE_HOME
if _prefix is None:
_prefix = getConfiguration().softwarehome
elif type(_prefix) is not type(''):
_prefix = package_home(_prefix)
name = kw.get('__name__')
......
......@@ -12,8 +12,8 @@
##############################################################################
__doc__='''Generic Database Adapter Package Registration
$Id: __init__.py,v 1.14 2002/08/14 22:25:17 mj Exp $'''
__version__='$Revision: 1.14 $'[11:-2]
$Id: __init__.py,v 1.15 2003/02/11 17:17:07 fdrake Exp $'''
__version__='$Revision: 1.15 $'[11:-2]
import Globals, os
......@@ -78,8 +78,9 @@ __ac_permissions__=(
)
# from App.config import getConfiguration
# j=os.path.join
# d=j(j(INSTANCE_HOME,'var'),'gadfly')
# d=j(getConfiguration().clienthome,'gadfly')
# if not os.path.exists(d):
# os.mkdir(d)
# os.mkdir(j(d,'demo'))
......@@ -13,17 +13,17 @@
"""
Set up testing environment
$Id: __init__.py,v 1.7 2003/02/07 21:28:13 fdrake Exp $
$Id: __init__.py,v 1.8 2003/02/11 17:17:08 fdrake Exp $
"""
import os
# Set the INSTANCE_HOME to the Testing package directory
os.environ['INSTANCE_HOME'] = INSTANCE_HOME = os.path.dirname(__file__)
import App.config
cfg = App.config.getConfiguration()
# Set the SOFTWARE_HOME to the directory containing the Testing package
# XXX This isn't a change, so why?
os.environ['SOFTWARE_HOME'] = SOFTWARE_HOME = os.path.dirname(INSTANCE_HOME)
# Set the INSTANCE_HOME to the Testing package directory
cfg.instancehome = os.path.dirname(__file__)
# Note: we don't set os.environ['ZEO_CLIENT'] anymore because we
# really do need all the products to be initialized. Some tests
# use the product registry.
# Make sure this change is propogated to all the legacy locations for
# this information.
App.config.setConfiguration(cfg)
......@@ -20,7 +20,7 @@ from types import StringType, ListType
import Zope
from Acquisition import aq_acquire
import App.FindHomes
from App.config import getConfiguration
import ZODB
import ZODB.ZApplication
from ZODB.POSException import ConflictError
......@@ -36,7 +36,8 @@ from zLOG import LOG, WARNING, INFO, BLATHER, log_time
def startup():
global ZODB, app
Globals.BobobaseName = os.path.join(Globals.data_dir, 'Data.fs')
Globals.BobobaseName = os.path.join(getConfiguration().clienthome,
'Data.fs')
Globals.DatabaseVersion='3'
# Import products
......@@ -45,7 +46,7 @@ def startup():
# Open the database
try:
# Try to use custom storage
m=imp.find_module('custom_zodb',[INSTANCE_HOME])
m=imp.find_module('custom_zodb',[getConfiguration().instancehome])
except:
import ZODB.FileStorage
storage = ZODB.FileStorage.FileStorage(Globals.BobobaseName)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment