cfg: convert types automatically based on default values

The type of the config value is string by default and we need to cast it to the
appropriate type - it is error-prone.

The swift3 middleware actually knows the correct config type from the default
value in swift3.cfg and there is no need to convert it manually.

Change-Id: I28761ed12c3bdd85cb2a80048d2abc0dd23222b3
This commit is contained in:
MORITA Kazutaka
2014-07-22 23:24:06 +09:00
parent d1805c9cfa
commit d1557c7923
3 changed files with 70 additions and 3 deletions

View File

@@ -13,9 +13,33 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from swift.common.utils import config_true_value
class Config(dict):
def __init__(self, base=None):
if base is not None:
self.update(base)
def update(self, other):
if hasattr(other, 'keys'):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
def __setitem__(self, key, value):
if isinstance(self.get(key), bool):
dict.__setitem__(self, key, config_true_value(value))
elif isinstance(self.get(key), int):
dict.__setitem__(self, key, int(value))
else:
dict.__setitem__(self, key, value)
# Global config dictionary. The default values can be defined here.
CONF = {
CONF = Config({
'location': 'US',
'max_bucket_listing': 1000,
'storage_domain': '',
}
})

View File

@@ -51,7 +51,7 @@ class BucketController(Controller):
raise InvalidArgument('max-keys', req.params['max-keys'])
max_keys = int(req.params.get('max-keys', CONF['max_bucket_listing']))
max_keys = min(max_keys, int(CONF['max_bucket_listing']))
max_keys = min(max_keys, CONF['max_bucket_listing'])
query = {
'format': 'json',

View File

@@ -0,0 +1,43 @@
# Copyright (c) 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from swift3.cfg import Config
class TestSwift3Cfg(unittest.TestCase):
def test_config(self):
conf = Config(
{
'a': 'str',
'b': 10,
'c': True,
}
)
conf.update(
{
'a': 'str2',
'b': '100',
'c': 'false',
}
)
self.assertEquals(conf['a'], 'str2')
self.assertEquals(conf['b'], 100)
self.assertEquals(conf['c'], False)
if __name__ == '__main__':
unittest.main()