django-etcd-settings-0.1.13/000077500000000000000000000000001303246614500156155ustar00rootroot00000000000000django-etcd-settings-0.1.13/.gitignore000066400000000000000000000046751303246614500176210ustar00rootroot00000000000000# Created by https://www.gitignore.io/api/pycharm,osx,linux,virtualenv,python,vim ### PyCharm ### # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio *.iml ## Directory-based project format: .idea/ # if you remove the above rule, at least ignore the following: # User-specific stuff: # .idea/workspace.xml # .idea/tasks.xml # .idea/dictionaries # Sensitive or high-churn files: # .idea/dataSources.ids # .idea/dataSources.xml # .idea/sqlDataSources.xml # .idea/dynamic.xml # .idea/uiDesigner.xml # Gradle: # .idea/gradle.xml # .idea/libraries # Mongo Explorer plugin: # .idea/mongoSettings.xml ## File-based project format: *.ipr *.iws ## Plugin-specific files: # IntelliJ /out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties ### OSX ### .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ### Linux ### *~ # KDE directory preferences .directory # Linux trash folder which might appear on any partition or disk .Trash-* ### VirtualEnv ### # Virtualenv # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ .Python [Bb]in [Ii]nclude [Ll]ib [Ss]cripts pyvenv.cfg pip-selfcheck.json ### Python ### # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg .python-version # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ ### Vim ### [._]*.s[a-w][a-z] [._]s[a-w][a-z] *.un~ Session.vim .netrwhist *~ # Project files unittest.sqlite /setup.py django-etcd-settings-0.1.13/.pypirc000066400000000000000000000006301303246614500171230ustar00rootroot00000000000000[distutils] # this tells distutils what package indexes you can push to index-servers = pypi pypitest [pypi] repository: https://pypi.python.org/pypi username: {{your_username}} # FIXME Set Username password: {{your_password}} # FIXME Set Password [pypitest] repository: https://testpypi.python.org/pypi username: {{your_username}} # FIXME Set Username password: {{your_password}} # FIXME Set Password django-etcd-settings-0.1.13/.travis.yml000066400000000000000000000017011303246614500177250ustar00rootroot00000000000000language: python sudo: required services: - docker script: - make docker/build before_install: - pip install codecov after_success: - codecov deploy: provider: pypi user: kpn-digital skip_cleanup: true on: tags: true all_branches: true password: secure: gbKikNWaUoKbMjs1IL0PUQaYfqG00TQsIFJwIZq8Ri7wS6dBB9QXZIiUw2uhVrGV6/nXOkqijyxlHsC6Boan6sDgZ3joT9cSlcIq7zur3lT13R28B7uvwIPLaMnz5O+j3KAhB7kSUiJw44Eob9DYmQ0quwwS7V15dKOc49XlxQY6i8qP1KWJ1epkmmgJZIJ2JZNCVy3zAXdRiYD3+yxyLVbbtnl7cLTz7KmmLpnQwAjMV8bD1DqrkLHlWLoIuU+hG9bPlJkLSt749dusBrP2aezEesSPXCWig9g0raBgS7K8MpI2yThztnN1QZFtYoHSdmF8uMSaZ59vwV2tn6yoRC+cOhmHehCmo7QmBXhldk8XhnhCaZvj9R2Ajw+XB5xu1fqHlG89UZKPFVZqTUWuGBmiDb3yeadVeuLJ9EKSSroAHjjyA151hmZ1G4v20nnvuKaJ3TmWzWVHynoWe/jBNkta1kPSJ42g+e9re6V6Hus6euwh+raZQVEj5pAlg86Par8fR9JnsJsuktHDM1OVEF+54FKfLQYUuuiDBGZ/6okK3FCH6DYjQp2Y62iIIwS6EflM8N/2aEmyevXN6j51l+UGpSKCzJz3VjU5b5OGsUV777+KDxaIJNhfy5gFZiFZDV1yB1bCqxNWuWaRj4/vITxx7SQtWvfoAJT3BJZK9aQ= django-etcd-settings-0.1.13/Dockerfile000066400000000000000000000000661303246614500176110ustar00rootroot00000000000000FROM kpndigital/tox:latest WORKDIR /app CMD ["tox"] django-etcd-settings-0.1.13/LICENSE000066400000000000000000000010571303246614500166250ustar00rootroot00000000000000Copyright 2015 KPN Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this application 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. django-etcd-settings-0.1.13/MANIFEST.in000066400000000000000000000003021303246614500173460ustar00rootroot00000000000000include README.md include VERSION include LICENSE recursive-include tests * recursive-exclude * __pycache__ recursive-exclude * *.py[co] recursive-include docs *.rst conf.py Makefile make.bat django-etcd-settings-0.1.13/Makefile000066400000000000000000000024161303246614500172600ustar00rootroot00000000000000# This Makefile requires the following commands to be available: # * virtualenv-2.7 # * python2.7 # * docker # * docker-compose DEPS:=requirements.txt DOCKER_COMPOSE:=$(shell which docker-compose) PIP:="venv/bin/pip" CMD_FROM_VENV:=". venv/bin/activate; which" TOX=$(shell "$(CMD_FROM_VENV)" "tox") PYTHON=$(shell "$(CMD_FROM_VENV)" "python") TOX_PY_LIST="$(shell $(TOX) -l | grep ^py | xargs | sed -e 's/ /,/g')" .PHONY: clean docsclean pyclean test lint isort docs docker setup.py tox: clean venv $(TOX) pyclean: @find . -name *.pyc -delete @rm -rf *.egg-info build @rm -rf coverage.xml .coverage docsclean: @rm -fr docs/_build/ @rm -fr docs/api/ clean: pyclean docsclean @rm -rf venv venv: @virtualenv -p python2.7 venv @$(PIP) install -U "pip>=7.0" -q @$(PIP) install -r $(DEPS) test: venv pyclean $(TOX) -e $(TOX_PY_LIST) test/%: venv pyclean $(TOX) -e $(TOX_PY_LIST) -- $* lint: venv @$(TOX) -e lint @$(TOX) -e isort-check isort: venv @$(TOX) -e isort-fix docs: venv docsclean @$(TOX) -e docs docker: $(DOCKER_COMPOSE) run --rm app bash docker/%: $(DOCKER_COMPOSE) run --rm app make $* setup.py: venv $(PYTHON) setup_gen.py $(PYTHON) setup.py check --restructuredtext publish: setup.py $(PYTHON) setup.py sdist upload build: clean venv tox setup.py django-etcd-settings-0.1.13/README.rst000066400000000000000000000104421303246614500173050ustar00rootroot00000000000000Django ETCD Settings ===================== .. image:: https://secure.travis-ci.org/kpn-digital/django-etcd-settings.svg?branch=master :target: http://travis-ci.org/kpn-digital/django-etcd-settings?branch=master .. image:: https://img.shields.io/codecov/c/github/kpn-digital/django-etcd-settings/master.svg :target: http://codecov.io/github/kpn-digital/django-etcd-settings?branch=master .. image:: https://img.shields.io/pypi/v/django-etcd-settings.svg :target: https://pypi.python.org/pypi/django-etcd-settings .. image:: https://readthedocs.org/projects/django-etcd-settings/badge/?version=latest :target: http://django-etcd-settings.readthedocs.org/en/latest/?badge=latest Features -------- This application allows you to extend the Django settings as configured in the ``settings.py`` file with: * Environment dependent values * Values in different config sets, identified by name, which can be selected on a 'per request' basis using the ``X-DYNAMIC-SETTINGS`` HTTP header Both the added configuration values and config sets would live at ETCD, which will be continuously monitored by this library in order to transparently update your app settings upon changes. Backends -------- - ETCD 2.2.1 Installation ------------ .. code-block:: bash $ pip install django-etcd-settings Usage ----- This Django application uses the following configuration keys: * ``DJES_ETCD_DETAILS``: a dict with 'host', 'port', 'protocol', 'prefix', 'long_polling_timeout' and 'long_polling_safety_delay' (both in seconds). 'prefix' is a string to be used as base path for all configuration managed by this app. i.e. '/config/api' will result in '/config/api/' and '/config/api/extensions/' to be used for environment defaults and config_sets respectively Timeouts default to 50 and 5 seconds respectively. If ``DJES_ETCD_SETTINGS`` is None, this app will start with no errors and etcd_settings.settings will resolve to django.conf.settings plus your DJES_DEV_PARAMS overwrites i.e. .. code-block:: python ETCD_DETAILS = dict( host='localhost', port=4000, protocol='http', long_polling_timout=50, long_polling_safety_delay=5 ) * ``DJES_DEV_PARAMS``: A module with local overwrites, generally used for development. The overwrites must be capitalized module attributes. These overwrites will have preference over development settings on ETCD, but not over configset overwrites indicated by the ``X-DYNAMIC-SETTINGS`` HTTP header * ``DJES_ENV``: A string with the name of the environment in which the code is running. This will be used for accessing the env_defaults in ETCD in a directory with that name i.e. 'test', 'staging', 'prod'... * ``DJES_REQUEST_GETTER``: path to a function which accesses the HTTP request object being handled. Ensuring access to this value can be implemented with, for instance, middleware. This settings is only used to allow config overwrites on runtime based on predifined config_sets. In case you don't want to use this functionality, just set this setting to None i.e. 'middleware.thread_local.get_current_request' * ``DJES_WSGI_FILE``: path to the ``wsgi.py`` file for the django project. If not None, the monitoring of environment configuration will perform a ``touch`` of the file everytime the env_defaults are updated, so that all processes consuming settings from ``django.conf`` can consume the latest settings available as well The path can be absolute or relative to the 'manage.py' file. i.e. /project/src/wsgi.py, wsgi.py Then, add ``etcd_settings`` to the list of ``INSTALLED_APPS`` before any other that requires dynamic settings. From your code, just do ``from etcd_settings import settings`` instead of ``from django.conf import settings``. In case you want to use ``etcd_settings`` to modify some values in your standard Django settings.py file (i.e. Database config), you can use the following snippet in your settings file, as high as possible in the file and immediately under the ``DJES_*`` settings definition: .. code-block:: python import etcd_settings.loader extra_settings = etcd_settings.loader.get_overwrites( DJES_ENV, DJES_DEV_PARAMS, DJES_ETCD_DETAILS) locals().update(extra_settings) django-etcd-settings-0.1.13/docker-compose.yml000066400000000000000000000002111303246614500212440ustar00rootroot00000000000000etcd: image: elcolio/etcd ports: - "2379:2379" app: build: . volumes: - .:/app command: make build links: - etcd django-etcd-settings-0.1.13/docs/000077500000000000000000000000001303246614500165455ustar00rootroot00000000000000django-etcd-settings-0.1.13/docs/Makefile000066400000000000000000000164511303246614500202140ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-etcd-settings.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-etcd-settings.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/django-etcd-settings" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-etcd-settings" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." django-etcd-settings-0.1.13/docs/_static/000077500000000000000000000000001303246614500201735ustar00rootroot00000000000000django-etcd-settings-0.1.13/docs/_static/.gitignore000066400000000000000000000000001303246614500221510ustar00rootroot00000000000000django-etcd-settings-0.1.13/docs/conf.py000077500000000000000000000234021303246614500200500ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # django-etcd-settings documentation build configuration file, created by # sphinx-quickstart on Thu Oct 29 14:40:33 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'sphinxcontrib.plantuml', ] plantuml_jar_path = os.path.abspath('./_plantuml/plantuml.jar') plantuml = 'java -Djava.awt.headless=true -jar {0}'.format(plantuml_jar_path) # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django-etcd-settings' copyright = u'KPN' author = u'Enrique Paz' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '' # The full version, including alpha/beta/rc tags. release = ' ' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'django-etcd-settingsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', # Latex figure (float) alignment # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'django-etcd-settings.tex', u'django-etcd-settings Documentation', u'Enrique Paz', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'django-etcd-settings', u'django-etcd-settings Documentation', [author], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'django-etcd-settings', u'django-etcd-settings Documentation', author, 'django-etcd-settings', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'https://docs.python.org/': None, 'django': ( 'http://docs.djangoproject.com/en/1.8/', 'http://docs.djangoproject.com/en/1.8/_objects/' ) } django-etcd-settings-0.1.13/docs/index.rst000066400000000000000000000010001303246614500203750ustar00rootroot00000000000000.. django-etcd-settings documentation master file, created by sphinx-quickstart on Tue Jul 9 22:26:36 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. A dynamic settings management solution for django using ETCD ============================================================ Contents: .. toctree:: :maxdepth: 2 installation usage Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` django-etcd-settings-0.1.13/docs/installation.rst000066400000000000000000000002161303246614500217770ustar00rootroot00000000000000============ Installation ============ At the command line:: $ pip install ssh://git@stash.kpnnl.local:7999/de/django-etcd-settings.git django-etcd-settings-0.1.13/docs/make.bat000066400000000000000000000155411303246614500201600ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-etcd-settings.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-etcd-settings.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end django-etcd-settings-0.1.13/docs/usage.rst000066400000000000000000000001271303246614500204030ustar00rootroot00000000000000======== Usage ======== To use etcd_settings in a project:: import etcd_settings django-etcd-settings-0.1.13/etcd_settings/000077500000000000000000000000001303246614500204545ustar00rootroot00000000000000django-etcd-settings-0.1.13/etcd_settings/__init__.py000066400000000000000000000001421303246614500225620ustar00rootroot00000000000000from .proxy import proxy settings = proxy default_app_config = 'etcd_settings.apps.EtcdMonitor' django-etcd-settings-0.1.13/etcd_settings/apps.py000066400000000000000000000004001303246614500217630ustar00rootroot00000000000000from django.apps import AppConfig from etcd_settings.proxy import proxy class EtcdMonitor(AppConfig): name = 'etcd_settings' verbose_name = 'EtcdMonitor starting the threads for long polling' def ready(self): proxy.start_monitors() django-etcd-settings-0.1.13/etcd_settings/loader.py000066400000000000000000000005361303246614500223000ustar00rootroot00000000000000from .manager import EtcdConfigManager def get_overwrites(env, dev_params, etcd_details): overwrites = {} if etcd_details is not None: mgr = EtcdConfigManager(dev_params, **etcd_details) overwrites = mgr.get_env_defaults(env) else: overwrites = EtcdConfigManager.get_dev_params(dev_params) return overwrites django-etcd-settings-0.1.13/etcd_settings/manager.py000066400000000000000000000172531303246614500224500ustar00rootroot00000000000000import json import logging import re import time from importlib import import_module from os import utime from etcd import Client, EtcdException, EtcdKeyNotFound from .utils import ( CustomJSONEncoder, attrs_to_dir, byteify, custom_json_decoder_hook, threaded, ) class EtcdConfigInvalidValueError(Exception): def __init__(self, key, raw_value, value_error): self.key = key self.raw_value = raw_value self.value_error = value_error super(EtcdConfigInvalidValueError, self).__init__( "Invalid value for key '{}'. Raising '{}', because of value: '{}'" .format(key, value_error, raw_value)) class EtcdClusterState(object): etcd_index = 0 class EtcdConfigManager(object): def __init__( self, dev_params=None, prefix='config', protocol='http', host='localhost', port=2379, username=None, password=None, long_polling_timeout=50, long_polling_safety_delay=5): self._client = Client( host=host, port=port, protocol=protocol, allow_redirect=True, username=username, password=password) # Overriding retries for urllib3.PoolManager.connection_pool_kw self._client.http.connection_pool_kw['retries'] = 0 self._base_config_path = prefix self._dev_params = dev_params self._base_config_set_path = "{}/extensions" \ .format(self._base_config_path) r = ('^(?P{}/(?:extensions/)?' '(?P[\w\-\.]+))/(?P.+)$') self._key_regex = re.compile(r.format(self._base_config_path)) self.long_polling_timeout = long_polling_timeout self.long_polling_safety_delay = long_polling_safety_delay self._init_logger() def _init_logger(self): self.logger = logging.getLogger('etcd_config_manager') logger_console_handler = logging.StreamHandler() logger_console_handler.setLevel(logging.ERROR) self.logger.addHandler(logger_console_handler) def _env_defaults_path(self, env='test'): return "{}/{}".format(self._base_config_path, env) def _config_set_path(self, set_name): return "{}/{}".format(self._base_config_set_path, set_name) def _encode_config_key(self, k): return k.lower().replace('_', '/') def _decode_config_key(self, k): [env_or_set, key_path] = re.sub( self._key_regex, '\g|\g', k).split('|') return env_or_set, key_path.upper().replace('/', '_') def _encode_config_value(self, val): return json.dumps(val, cls=CustomJSONEncoder) def _decode_config_value(self, val): decoded = json.loads(val, object_hook=custom_json_decoder_hook) return byteify(decoded) def _process_response_set(self, rset, env_defaults=True): d = {} EtcdClusterState.etcd_index = rset.etcd_index for leaf in rset.leaves: try: config_set, key = self._decode_config_key(leaf.key) except ValueError: info = "An error occurred when processing an EtcdResponse" if not env_defaults: info += " (is '{}' a directory?)".format( self._base_config_set_path) self.logger.warning(info) else: if leaf.value is not None: try: value = self._decode_config_value(leaf.value) except ValueError as e: raise EtcdConfigInvalidValueError( leaf.key, leaf.value, e) if env_defaults: d[key] = value else: if config_set not in d: d[config_set] = {} d[config_set][key] = value return d @staticmethod def get_dev_params(mod): params = {} if mod: params = attrs_to_dir(import_module(mod)) return params def get_env_defaults(self, env): res = self._client.read( self._env_defaults_path(env), recursive=True) conf = self._process_response_set(res) conf.update(EtcdConfigManager.get_dev_params(self._dev_params)) return conf def get_config_sets(self): conf = {} try: res = self._client.read( self._base_config_set_path, recursive=True) conf = self._process_response_set(res, env_defaults=False) except EtcdKeyNotFound: self.logger.warning( "Unable to find config sets at '{}' (expected a dict)", self._base_config_set_path) return conf @threaded(daemon=True) def monitor_env_defaults( self, env, conf={}, wsgi_file=None, max_events=None): processed_events = 0 for event in self._watch( self._env_defaults_path(env), conf, wsgi_file, max_events): if event is not None: conf.update(self._process_response_set(event)) conf.update(EtcdConfigManager.get_dev_params(self._dev_params)) if wsgi_file: with open(wsgi_file, 'a'): utime(wsgi_file, None) processed_events += 1 return processed_events @threaded(daemon=True) def monitor_config_sets(self, conf={}, max_events=None): processed_events = 0 for event in self._watch( self._base_config_set_path, conf=conf, max_events=max_events): if event is not None: conf.update( self._process_response_set(event, env_defaults=False)) processed_events += 1 return processed_events def _watch(self, path, conf={}, wsgi_file=None, max_events=None): i = 0 while (max_events is None) or (i < max_events): try: i += 1 index = EtcdClusterState.etcd_index if index > 0: index = index + 1 res = self._client.watch( path, index=index, recursive=True, timeout=self.long_polling_timeout) else: res = self._client.read(path, recursive=True) yield res except Exception as e: if not (isinstance(e, EtcdException) and ('timed out' in str(e))): self.logger.error("Long Polling Error: {}".format(e)) time.sleep(self.long_polling_safety_delay) yield None def set_env_defaults(self, env, conf={}): path = self._env_defaults_path(env) errors = {} for k, v in conf.items(): if k.isupper(): try: encoded_key = self._encode_config_key(k) self._client.write( "{}/{}".format(path, encoded_key), self._encode_config_value(v)) except Exception as e: errors[k] = str(e) return errors def set_config_sets(self, config_sets={}): errors = {} for set_name, config_set in config_sets.items(): path = self._config_set_path(set_name) for k, v in config_set.items(): if k.isupper(): try: self._client.write( "{}/{}".format(path, self._encode_config_key(k)), self._encode_config_value(v)) except Exception as e: errors[k] = str(e) return errors django-etcd-settings-0.1.13/etcd_settings/proxy.py000066400000000000000000000067151303246614500222200ustar00rootroot00000000000000import os import re from importlib import import_module from django.conf import settings as django_settings from .manager import EtcdConfigManager from .utils import ( attrs_to_dir, copy_if_mutable, dict_rec_update, find_project_root, ) class EtcdSettingsProxy(object): def __init__(self): self.env = getattr(django_settings, 'DJES_ENV', None) dev_params = getattr(django_settings, 'DJES_DEV_PARAMS', None) etcd_details = getattr(django_settings, 'DJES_ETCD_DETAILS', None) self._init_req_getter( getattr(django_settings, 'DJES_REQUEST_GETTER', None)) self._locate_wsgi_file( getattr(django_settings, 'DJES_WSGI_FILE', None)) if etcd_details is not None: self._etcd_mgr = EtcdConfigManager(dev_params, **etcd_details) self._config_sets = self._etcd_mgr.get_config_sets() self._env_defaults = self._etcd_mgr.get_env_defaults(self.env) else: self._etcd_mgr = None self._config_sets = dict() self._env_defaults = EtcdConfigManager.get_dev_params(dev_params) def _locate_wsgi_file(self, wsgi_file): if wsgi_file is None: self._wsgi_file = None elif wsgi_file.startswith(os.path.sep): self._wsgi_file = wsgi_file else: self._wsgi_file = os.path.join( find_project_root('manage.py'), wsgi_file) def _init_req_getter(self, s): if s is not None: r = re.compile('(?P.*)\.(?P[\w_]+)') m = re.match(r, s) mod_s = m.group('module') fun_s = m.group('f') mod = import_module(mod_s) self._req_getter = getattr(mod, fun_s) else: self._req_getter = None def _parse_req_config_sets(self): sets = [] if self._req_getter is not None: request = self._req_getter() if request and getattr(request, "META", None): sets = request.META.get('HTTP_X_DYNAMIC_SETTING', '').split() return sets def start_monitors(self): if self._etcd_mgr is not None: self._etcd_mgr.monitor_env_defaults( env=self.env, conf=self._env_defaults, wsgi_file=self._wsgi_file) self._etcd_mgr.monitor_config_sets(conf=self._config_sets) def __getattr__(self, attr): try: dj_value = getattr(django_settings, attr) dj_value_exists = True except AttributeError: dj_value_exists = False dj_value = None try: value = self._env_defaults[attr] value_exists = True except KeyError: value_exists = dj_value_exists value = dj_value for override_set in self._parse_req_config_sets(): config_set = self._config_sets.get(override_set, {}) if attr in config_set: new_value = config_set[attr] value = copy_if_mutable(value) if isinstance(value, dict) and isinstance(new_value, dict): dict_rec_update(value, new_value) else: value = new_value if value or value_exists: return value else: raise AttributeError(attr) def as_dict(self): items = attrs_to_dir(django_settings) items.update(self._env_defaults) return items proxy = EtcdSettingsProxy() django-etcd-settings-0.1.13/etcd_settings/utils.py000066400000000000000000000074111303246614500221710ustar00rootroot00000000000000import copy import datetime import json import logging import os import sys from collections import Mapping from functools import wraps from threading import Thread import six from dateutil.parser import parse as parse_date def attrs_to_dir(mod): data = {} for attr in dir(mod): if attr == attr.upper(): data[attr] = getattr(mod, attr) return data def dict_rec_update(d, u): """Nested update of a dict, handy for overriding settings""" # https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth for k, v in u.items(): if isinstance(v, Mapping): r = dict_rec_update(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d class Task(Thread): """ The Threaded object returned by the @threaded decorator below """ def __init__(self, method, *args, **kwargs): super(Task, self).__init__() self.method = method self.args = args self.kwargs = kwargs self._result = None self.__exc_info = None def run(self): try: self._result = self.method(*self.args, **self.kwargs) except: self.__exc_info = sys.exc_info() @property def result(self): self.join() if self.__exc_info is not None: six.reraise(*self.__exc_info) return self._result def threaded(function=None, daemon=False): def wrapper_factory(func): @wraps(func) def get_thread(*args, **kwargs): t = Task(func, *args, **kwargs) if daemon: t.daemon = True t.start() return t return get_thread if function: return wrapper_factory(function) else: return wrapper_factory class CustomJSONEncoder(json.JSONEncoder): custom_type_key = '_custom_type' custom_type_value_key = 'value' DECODERS = {'datetime': parse_date} def default(self, obj): if isinstance(obj, datetime.datetime): return {self.custom_type_key: 'datetime', self.custom_type_value_key: obj.isoformat()} else: return super(CustomJSONEncoder, self).default(obj) def custom_json_decoder_hook(obj): ct = obj.get(CustomJSONEncoder.custom_type_key, None) if ct is not None: value = obj.get(CustomJSONEncoder.custom_type_value_key) return CustomJSONEncoder.DECODERS[ct](value) else: return obj def find_project_root(root_indicator='manage.py', current=os.getcwd()): parent = os.path.dirname(current) if root_indicator in os.listdir(current): return current elif current == parent: # We are at '/' already! raise IOError('Not found: {}'.format(root_indicator)) else: return find_project_root(root_indicator, parent) def copy_if_mutable(value): """ Copy function handling mutable values (only dicts and lists). """ if type(value) in (dict, list): return copy.deepcopy(value) return value def byteify(input): if isinstance(input, dict): return {byteify(key): byteify(value) for key, value in input.items()} elif isinstance(input, list): return [byteify(element) for element in input] elif (sys.version_info.major == 2) and (isinstance(input, unicode)): return input.encode('utf-8') else: return input class IgnoreMaxEtcdRetries(logging.Filter): """ Skip etcd.client MaxRetryError on timeout """ def __init__(self, name='etcd.client'): super(IgnoreMaxEtcdRetries, self).__init__(name) def filter(self, record): msg = '{}'.format(record.args) return not ( 'MaxRetryError' in msg and 'Read timed out' in msg ) django-etcd-settings-0.1.13/requirements.txt000066400000000000000000000001451303246614500211010ustar00rootroot00000000000000# Additional packages -r requirements/requirements-base.txt -r requirements/requirements-testing.txt django-etcd-settings-0.1.13/requirements/000077500000000000000000000000001303246614500203405ustar00rootroot00000000000000django-etcd-settings-0.1.13/requirements/requirements-base.txt000066400000000000000000000001111303246614500245250ustar00rootroot00000000000000Django>=1.7.5 python-etcd>=0.4.1 python-dateutil>=2.2 six>=1.10.0,<2.0.0 django-etcd-settings-0.1.13/requirements/requirements-testing.txt000066400000000000000000000002041303246614500252730ustar00rootroot00000000000000tox isort flake8 mock==1.3.0 py-pkgversion # PyTest for running the tests. pytest pytest-cov # docs sphinx sphinxcontrib-plantuml django-etcd-settings-0.1.13/setup.cfg000066400000000000000000000004721303246614500174410ustar00rootroot00000000000000[flake8] exclude = build,.git ignore = E902,W503 max-line-length = 79 [isort] combine_as_imports = true default_section = THIRDPARTY include_trailing_comma = true known_first_party = de multi_line_output = 5 sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER not_skip = __init__.py [wheel] universal = 1 django-etcd-settings-0.1.13/setup_gen.py000077500000000000000000000021001303246614500201540ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from pkgversion import list_requirements, pep440_version, write_setup_py from setuptools import find_packages write_setup_py( name='django-etcd-settings', version=pep440_version(), description="A dynamic settings management solution for Django using ETCD", long_description=open('README.rst').read(), author="Enrique Paz", author_email='quiquepaz@gmail.com', url='https://github.com/kpn-digital/django-etcd-settings', install_requires=list_requirements('requirements/requirements-base.txt'), packages=find_packages(exclude=['tests*']), tests_require=['tox'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', ] ) django-etcd-settings-0.1.13/tests/000077500000000000000000000000001303246614500167575ustar00rootroot00000000000000django-etcd-settings-0.1.13/tests/__init__.py000066400000000000000000000013341303246614500210710ustar00rootroot00000000000000import django from django.conf import global_settings, settings settings.configure( # Minimal django settings DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'unittest.sqlite', 'TEST_NAME': ':memory:', }, }, MIDDLEWARE_CLASSES=global_settings.MIDDLEWARE_CLASSES, ROOT_URLCONF=None, INSTALLED_APPS=['etcd_settings'], DJES_DEV_PARAMS=None, DJES_REQUEST_GETTER=None, DJES_ENV='dev', DJES_ETCD_DETAILS=None, DJES_WSGI_FILE=None # DJES_ETCD_DETAILS=dict(host='localhost', port=4000, protocol='http', # prefix='/config/my-django-app') ) if hasattr(django, 'setup'): django.setup() django-etcd-settings-0.1.13/tests/conftest.py000066400000000000000000000005731303246614500211630ustar00rootroot00000000000000class TestSettings(object): ETCD_PREFIX = '/config/etcd_settings' ETCD_ENV = 'test' ETCD_HOST = 'etcd' ETCD_PORT = 2379 ETCD_USERNAME = 'test' ETCD_PASSWORD = 'test' ETCD_DETAILS = dict( host='etcd', port=2379, prefix='/config/etcd_settings', username='test', password='test' ) settings = TestSettings() django-etcd-settings-0.1.13/tests/loader_dev_params.py000066400000000000000000000000751303246614500230020ustar00rootroot00000000000000# Sample of dev_params used at tests.test_loader FOO = 'bar' django-etcd-settings-0.1.13/tests/test_loader.py000066400000000000000000000004611303246614500216370ustar00rootroot00000000000000from django.test import TestCase from etcd_settings.loader import get_overwrites class TestLoader(TestCase): def test_get_overwrites_without_etcd(self): overwrites = get_overwrites( 'unittest', 'tests.loader_dev_params', None) self.assertEqual('bar', overwrites['FOO']) django-etcd-settings-0.1.13/tests/test_manager.py000066400000000000000000000225341303246614500220100ustar00rootroot00000000000000import datetime import json import logging import os import time from django.test import TestCase from etcd import EtcdKeyNotFound from etcd_settings.manager import ( EtcdClusterState, EtcdConfigInvalidValueError, EtcdConfigManager, ) from .conftest import settings class TestEtcdConfigManager(TestCase): longMessage = True def _dataset_with_empty_dir(self): key = os.path.join(self.mgr._env_defaults_path(self.env), 'dir/empty') self.mgr._client.write(key, None, dir=True) value = self.mgr._client.get(key) return key, value def _dataset_with_invalid_json(self): key = os.path.join( self.mgr._env_defaults_path(self.env), 'json/invalid') self.mgr._client.set(key, '{') value = self.mgr._client.get(key) return key, value def _dataset_for_defaults(self): dataset = {} k1 = os.path.join(self.mgr._env_defaults_path(self.env), 'foo/bar') dataset[k1] = '"baz"' k2 = os.path.join(self.mgr._env_defaults_path(self.env), 'foo/baz') dataset[k2] = '"bar"' k3 = os.path.join(self.mgr._env_defaults_path(self.env), 'foobarbaz') dataset[k3] = '"superbaz"' expected_env = { 'FOO_BAR': 'baz', 'FOO_BAZ': 'bar', 'FOOBARBAZ': 'superbaz', } for k, v in dataset.items(): self.mgr._client.set(k, v) return dataset.keys(), expected_env def _dataset_for_configsets(self): dataset = {} k1 = os.path.join(self.mgr._config_set_path('foo'), 'bar') dataset[k1] = '1' k2 = os.path.join(self.mgr._config_set_path('foo'), 'baz') dataset[k2] = '2' k3 = os.path.join(self.mgr._config_set_path('foo.bar'), 'baz') dataset[k3] = '1' k4 = os.path.join(self.mgr._config_set_path('foo.bar'), 'bazbaz') dataset[k4] = '2' k5 = os.path.join(self.mgr._config_set_path('foo.bar-zoo'), 'bar') dataset[k5] = '1' expected_sets = { 'foo': {'BAR': 1, 'BAZ': 2}, 'foo.bar': {'BAZ': 1, 'BAZBAZ': 2}, 'foo.bar-zoo': {'BAR': 1}, } for k, v in dataset.items(): self.mgr._client.set(k, v) return dataset.keys(), expected_sets def setUp(self): self.env = 'unittest' EtcdClusterState.etcd_index = 0 self.mgr = EtcdConfigManager( dev_params=None, prefix=settings.ETCD_PREFIX, protocol='http', host=settings.ETCD_HOST, port=settings.ETCD_PORT, username=settings.ETCD_USERNAME, password=settings.ETCD_PASSWORD, long_polling_timeout=0.1, long_polling_safety_delay=0.1 ) for l in self.mgr.logger.handlers: l.setLevel(logging.CRITICAL) def tearDown(self): def try_unless_not_found(f): try: f() except EtcdKeyNotFound: pass def clean_env(): self.mgr._client.delete( self.mgr._env_defaults_path(self.env), recursive=True) def clean_extensions(): self.mgr._client.delete( self.mgr._base_config_set_path, recursive=True) try_unless_not_found(clean_extensions) try_unless_not_found(clean_env) def test_init_logger(self): self.assertIsNotNone(self.mgr.logger) def test_encode_config_key(self): self.assertEqual( 'foo/bar/baz', self.mgr._encode_config_key('FOO_BAR_BAZ')) def test_decode_env_config_key(self): key = 'FOO_BAR' s = '{}/{}/foo/bar'.format(self.mgr._base_config_path, self.env) self.assertEqual((self.env, key), self.mgr._decode_config_key(s)) def test_decode_set_config_key(self): key = 'FOO_BAR' configset = 'unit.test' s = '{}/{}/foo/bar'.format(self.mgr._base_config_set_path, configset) self.assertEqual((configset, key), self.mgr._decode_config_key(s)) def test_encode_config_value(self): self.assertEqual( '"abcde"', self.mgr._encode_config_value('abcde')) self.assertEqual( '112', self.mgr._encode_config_value(112)) self.assertEqual( # Tuples are lost in encoding, should be avoided as config values '[1, "b"]', self.mgr._encode_config_value((1, 'b'))) encoded_config = self.mgr._encode_config_value(dict(foo=1, bar='baz')) self.assertEqual( json.loads('{"foo": 1, "bar": "baz"}'), json.loads(encoded_config)) def test_process_response_set_empty(self): key, value = self._dataset_with_empty_dir() self.assertEqual({}, self.mgr._process_response_set(value)) def test_process_response_exception_handling(self): with self.assertRaises(EtcdConfigInvalidValueError) as excContext: key, value = self._dataset_with_invalid_json() self.mgr._process_response_set(value) exc = excContext.exception self.assertEqual(key, exc.key) self.assertEqual(value.value, exc.raw_value) self.assertIn(key, str(exc), "Expect key in message") self.assertIn( "Expecting", str(exc), msg="Expect detailed error message") self.assertIn( "line", str(exc), msg="Expect line number in error message") self.assertIn( "column", str(exc), msg="Expect column number in error message") self.assertIn(value.value, str(exc), msg="Expect invalid value") def test_decode_config_value(self): self.assertEqual( 'abcde', self.mgr._decode_config_value('"abcde"')) self.assertEqual( 112, self.mgr._decode_config_value('112')) self.assertEqual( dict(foo=1, bar='baz'), self.mgr._decode_config_value('{"foo": 1, "bar": "baz"}')) self.assertEqual( [1, 'b'], self.mgr._decode_config_value('[1, "b"]')) def test_custom_encoding_decoding_values(self): d = datetime.datetime(2015, 10, 9, 8, 7, 6) encoded_d = self.mgr._encode_config_value(d) decoded_d = self.mgr._decode_config_value(encoded_d) self.assertEqual(True, isinstance(decoded_d, datetime.datetime)) self.assertEqual(d.isoformat(), decoded_d.isoformat()) self.assertEqual(d, decoded_d) def test_get_env_defaults(self): keys, expected = self._dataset_for_defaults() self.assertEqual(expected, self.mgr.get_env_defaults(self.env)) def test_get_config_sets(self): keys, expected_sets = self._dataset_for_configsets() self.assertEqual(expected_sets, self.mgr.get_config_sets()) def test_monitor_env_defaults(self): keys, expected_env = self._dataset_for_defaults() d = {} old_etcd_index = EtcdClusterState.etcd_index t = self.mgr.monitor_env_defaults(env=self.env, conf=d, max_events=1) self.assertEqual(1, t.result) self.assertEqual(expected_env, d) self.assertGreater(EtcdClusterState.etcd_index, old_etcd_index) def test_monitor_config_sets(self): keys, expected_sets = self._dataset_for_configsets() d = {} old_etcd_index = EtcdClusterState.etcd_index t = self.mgr.monitor_config_sets(conf=d, max_events=1) self.assertEqual(1, t.result) self.assertEqual(expected_sets, d) self.assertGreater(EtcdClusterState.etcd_index, old_etcd_index) def test_monitors_delay_and_continue_on_exception(self): d = {} max_events = 2 lambdas = [ lambda: self.mgr.monitor_env_defaults( self.env, conf=d, max_events=max_events), lambda: self.mgr.monitor_config_sets( conf=d, max_events=max_events), ] try: self.mgr._base_config_path = 'Unknown' for l in lambdas: t0 = time.time() t = l() self.assertEqual(max_events, t.result) self.assertEqual( True, (time.time() - t0) > (max_events * self.mgr.long_polling_safety_delay) ) self.assertEqual(False, t.is_alive()) finally: self.mgr._base_config_path = settings.ETCD_PREFIX def test_monitors_continue_on_etcd_exception(self): d = {} max_events = 2 lambdas = [ lambda: self.mgr.monitor_env_defaults( self.env, conf=d, max_events=max_events), lambda: self.mgr.monitor_config_sets( conf=d, max_events=max_events), ] try: old_etcd_index = EtcdClusterState.etcd_index self.mgr._etcd_index = 999990 for l in lambdas: t0 = time.time() t = l() self.assertEqual(max_events, t.result) net_time = time.time() - t0 self.assertGreater( net_time, (max_events * self.mgr.long_polling_timeout) ) self.assertLess( net_time, (max_events * (self.mgr.long_polling_safety_delay + self.mgr.long_polling_timeout)) ) self.assertEqual(False, t.is_alive()) finally: EtcdClusterState.etcd_index = old_etcd_index django-etcd-settings-0.1.13/tests/test_proxy.py000066400000000000000000000105051303246614500215520ustar00rootroot00000000000000import json import os import re import sys from django.http import HttpRequest from django.test import TestCase from django.test.utils import override_settings from etcd_settings.loader import get_overwrites from etcd_settings.manager import EtcdClusterState, EtcdConfigManager from etcd_settings.proxy import EtcdSettingsProxy from mock import MagicMock from .conftest import settings @override_settings( DJES_ETCD_DETAILS=settings.ETCD_DETAILS, DJES_ENV=settings.ETCD_ENV, DJES_REQUEST_GETTER='etcd_settings.utils.threaded', E=0 ) class TestEtcdSettingsProxy(TestCase): def setUp(self): s = '' with open('tests/unicode.txt', 'rb+') as f: if sys.version_info.major == 3: s = f.read().decode() else: s = f.read() self.mgr = EtcdConfigManager( prefix=settings.ETCD_PREFIX, host=settings.ETCD_HOST, port=settings.ETCD_PORT, username=settings.ETCD_USERNAME, password=settings.ETCD_PASSWORD ) self.env_config = { "A": 1, "B": "c", "D": {"e": "f"}, "E": 1, "C": {'c2': 1}, 'ENCODING': s } self.mgr.set_env_defaults('test', self.env_config) self.mgr.set_config_sets({ 'foo': {'A': 11}, 'bar': {'C': {'c3': 2}}}) self.proxy = EtcdSettingsProxy() with open('manage.py', 'w') as f: f.write("testing artifact") def tearDown(self): try: os.remove('manage.py') except: pass def test_loader_etcd_index_in_manager(self): env = get_overwrites(settings.ETCD_ENV, None, settings.ETCD_DETAILS) self.assertIsNotNone(env) self.assertGreater(EtcdClusterState.etcd_index, 0) def test_username_password(self): self.assertEquals({'authorization': u'Basic dGVzdDp0ZXN0'}, self.mgr._client._get_headers()) def test_proxy_starts_without_extensions(self): self.mgr._client.delete(self.mgr._base_config_set_path, recursive=True) p = EtcdSettingsProxy() self.assertIsNotNone(p) def test_proxy_starts_when_extensions_is_not_a_dir(self): self.mgr._client.delete(self.mgr._base_config_set_path, recursive=True) self.mgr._client.write( self.mgr._base_config_set_path, json.dumps('not_a_dict')) p = EtcdSettingsProxy() self.assertIsNotNone(p) def test_proxy_reads_initial_blob(self): self.assertEquals(1, self.proxy.A) self.assertEquals("c", self.proxy.B) def test_proxy_raises_attribute_errors_on_not_found(self): with self.assertRaises(AttributeError): self.proxy.KEY_THAT_IS_NOT_THERE def test_proxy_reads_django_settings(self): self.assertEquals('test', self.proxy.DJES_ENV) def test_proxy_gives_prio_to_env_over_django_settings(self): self.assertEquals(1, self.proxy.E) def test_proxy_can_be_viewed_as_dict(self): d = self.proxy.as_dict() for k, v in self.env_config.items(): self.assertEqual(v, d[k]) def test_proxy_uses_dynamic_settings(self): r = HttpRequest() r.META = {'HTTP_X_DYNAMIC_SETTING': 'foo'} self.proxy._req_getter = MagicMock(return_value=r) self.assertEqual(11, self.proxy.A) def test_proxy_dynamic_settings_handle_dict_overwrites(self): r = HttpRequest() r.META = {'HTTP_X_DYNAMIC_SETTING': 'bar'} self.proxy._req_getter = MagicMock(return_value=r) c = self.proxy.C self.assertEqual(1, c.get('c2')) self.assertEqual(2, c.get('c3')) def test_proxy_locates_uwsgi_file(self): self.proxy._locate_wsgi_file(None) self.assertEqual(None, self.proxy._wsgi_file) self.proxy._locate_wsgi_file(__file__) self.assertEqual(__file__, self.proxy._wsgi_file) self.proxy._locate_wsgi_file('etcd_settings/proxy.py') self.assertIsNotNone( re.match("^/(.*)/etcd_settings/proxy.py", self.proxy._wsgi_file)) os.remove('manage.py') with self.assertRaises(IOError): self.proxy._locate_wsgi_file('file_that_cannot_exist.py') def test_loader_gets_overwrites(self): self.assertEqual( self.env_config, get_overwrites(settings.ETCD_ENV, None, settings.ETCD_DETAILS) ) django-etcd-settings-0.1.13/tests/test_utils.py000066400000000000000000000017631303246614500215370ustar00rootroot00000000000000import logging import unittest from etcd_settings import utils class TestLoggingFilter(unittest.TestCase): def setUp(self): self.logger_filter = utils.IgnoreMaxEtcdRetries() def test_log_record_without_args(self): self.assertTrue( self.logger_filter.filter( logging.LogRecord( 'etcd.client', logging.ERROR, '/', 0, 'Read timed out', tuple(), None ) ) ) def test_log_record_match(self): self.assertFalse( self.logger_filter.filter( logging.LogRecord( 'etcd.client', logging.ERROR, '/', 0, 'Error %s exception %s', ('Read timed out', 'MaxRetryError'), None ) ) ) django-etcd-settings-0.1.13/tests/unicode.txt000066400000000000000000000000131303246614500211400ustar00rootroot00000000000000éá᳤ django-etcd-settings-0.1.13/tox.ini000066400000000000000000000013161303246614500171310ustar00rootroot00000000000000[pytest] addopts=--tb=short [tox] envlist = py27,py35,isort-check,isort-fix,lint,docs skipsdist = true [testenv] commands = py.test tests --cov-report=term-missing --cov-report=html --cov-report=xml --cov-append --cov=etcd_settings -s {posargs} deps = -rrequirements/requirements-base.txt -rrequirements/requirements-testing.txt [testenv:lint] commands = flake8 etcd_settings tests deps = flake8 [testenv:docs] commands = sphinx-build -W -b html {toxinidir}/docs {toxinidir}/docs/_build/html deps = -rrequirements/requirements-testing.txt [testenv:isort-check] commands = isort -rc -c etcd_settings tests deps = isort [testenv:isort-fix] commands = isort -rc etcd_settings tests deps = isort