Commit 0361d11d authored by Eliot Berriot's avatar Eliot Berriot

initial commit

parents
*.pyc
# Project settings and static files
.idea/*
.sublime*
.idea
fab_settings.py
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
*.sql
*.py[cod]
*~
docs/_*
*.sq3
*.sqlite*
*.sb
*egg-info
dist
\ No newline at end of file
Changelog
=========
Copyright (c) Eliot Berriot and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of django-dynamic-preferences nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include COPYING
include CHANGES
include README.md
include runtests.py
recursive-include docs
recursive-include dynamic_preferences/templates *
recursive-include dynamic_preferences/static *
\ No newline at end of file
# License
The project is licensed under BSD licence.
\ No newline at end of file
from collections import OrderedDict
import inspect
class Registry(OrderedDict):
def register_decorator_factory(self, **kwargs):
"""
Return an actual decorator for registering objects into registry
"""
name = kwargs.get('name')
def decorator(decorated):
self.register_func(obj=decorated, name=name)
return decorated
return decorator
def register(self, obj=None, name=None, **kwargs):
"""
Use this method as a decorator on class/funciton you want to register:
@registry.register(name="test")
class Test:
pass
:param:obj: An object to register in the registry
:param:name: The name of the object to register. If none, the obj class name will be used
"""
if obj is None:
return self.register_decorator_factory(obj=obj, name=name, **kwargs)
else:
self.register_func(obj=obj, name=name, **kwargs)
return obj
def get_object_name(self, obj):
"""
Return a name from an element (object, class, function...)
"""
if callable(obj):
return obj.__name__
elif inspect.isclass(obj):
return obj.__class__.__name__
else:
raise ValueError("Cannot deduce name from given object ({0}). Please user registry.register() with a 'name' argument.".format(obj))
def register_func(self, obj, name=None, **kwargs):
"""
Register an object, class, function... into the registry
"""
if name is None:
name = self.get_object_name(obj)
self[name] = obj
def autodiscover(self, apps, force_reload=True):
"""
Iterate throught every installed apps, trying to import `look_into` package
:param apps: an iterable of string, refering to python modules the registry will try to import via autodiscover
"""
for app in apps:
try:
package = '{0}.{1}'.format(app, self.look_into) # try to import self.package inside current app
#print(package)
module = __import__(package)
if force_reload:
reload(module)
except ImportError, e:
# Module does not exist
pass
print(e)
class MetaRegistry(Registry):
"""
Keep a reference to all registries
"""
look_into = "registries"
def autodiscover(self, apps, cascade=True, **kwargs):
"""
:param cascade: If true, will trigger autodiscover on discovered registries
"""
super(MetaRegistry, self).autodiscover(apps, **kwargs)
if cascade:
self.autodiscover_registries(apps)
def autodiscover_registries(self, apps):
for key, registry in self.iteritems():
registry.autodiscover(apps)
meta_registry = MetaRegistry()
\ No newline at end of file
from test_registries import awesome_people
@awesome_people.register
class AlainDamasio:
pass
print("imported", awesome_people)
\ No newline at end of file
from test_registries import vegetable_registry
@vegetable_registry.register
class Potato:
pass
from test_registries import awesome_people
@awesome_people.register
class FrederikPeeters:
pass
\ No newline at end of file
from test_registries import vegetable_registry
@vegetable_registry.register
class Ketchup:
warning = "ketchup is not a vegetable"
\ No newline at end of file
from registries import Registry, meta_registry
class AwesomePeopleRegistry(Registry):
look_into = "awesome_people"
awesome_people = AwesomePeopleRegistry()
meta_registry.register(awesome_people, name="awesome_people")
class VegetableRegistry(Registry):
look_into = "vegetables"
vegetable_registry = VegetableRegistry()
meta_registry.register(vegetable_registry, name="vegetable_registry")
\ No newline at end of file
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import unittest
import test_registries
import registries
registries.meta_registry.look_into = "test_registries"
TEST_APPS = (
"app1",
"app2",
)
class RegistryTest(unittest.TestCase):
def test_can_infer_name_from_class_function_and_instance(self):
registry = registries.Registry()
def something():
pass
class MyClass:
pass
self.assertEqual(registry.get_object_name(something), "something")
self.assertEqual(registry.get_object_name(MyClass), "MyClass")
with self.assertRaises(ValueError):
self.assertEqual(registry.get_object_name(MyClass()), "MyClass")
def test_can_register_data_to_registry(self):
data = "something"
registry = registries.Registry()
registry.register(data, name="key")
self.assertEqual(len(registry), 1)
self.assertEqual(registry.get("key"), data)
def test_can_register_class_and_function_via_decorator(self):
registry = registries.Registry()
@registry.register
class ToRegister:
pass
self.assertEqual(registry.get('ToRegister'), ToRegister)
@registry.register
def something():
pass
self.assertEqual(registry.get('something'), something)
def test_can_register_via_decorator_using_custom_name(self):
registry = registries.Registry()
@registry.register(name="custom_name")
def something():
pass
self.assertEqual(registry.get('custom_name'), something)
def test_registry_can_autodiscover(self):
registry = test_registries.awesome_people
registry.autodiscover(apps=TEST_APPS)
self.assertEqual(len(registry), 2)
self.assertNotEqual(registry.get('AlainDamasio', None), None)
self.assertNotEqual(registry.get('FrederikPeeters', None), None)
registry.clear()
def test_meta_registry_can_autodiscovering_registries_and_trigger_their_autodiscover_method(self):
registry = registries.meta_registry
registry.autodiscover(apps=TEST_APPS)
self.assertEqual(len(registry), 2)
self.assertEqual(registry.get('awesome_people'), test_registries.awesome_people)
self.assertEqual(registry.get('vegetable_registry'), test_registries.vegetable_registry)
registry = test_registries.awesome_people
self.assertEqual(len(registry), 2)
self.assertNotEqual(registry.get('AlainDamasio', None), None)
self.assertNotEqual(registry.get('FrederikPeeters', None), None)
registry = test_registries.vegetable_registry
self.assertEqual(len(registry), 2)
self.assertNotEqual(registry.get('Potato', None), None)
self.assertNotEqual(registry.get('Ketchup', None), None)
def test_reload_autodiscover(self):
fail
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
import os
from setuptools import setup, find_packages
import dynamic_preferences
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-dynamic-preferences',
version=dynamic_preferences.__version__,
packages=find_packages(),
include_package_data=True,
license='BSD', # example license
description='A django app for registering dynamic global, site and user preferences',
long_description=README,
url='http://code.eliotberriot.com/eliotberriot/django-dynamic-preferences',
author='Eliot Berriot',
author_email='contact@eliotberriot.com',
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
# Replace these appropriately if you are stuck on Python 2.
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=[
"django",
],
)
\ No newline at end of file
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