├── .arcconfig ├── .arclint ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docker-compose.yml ├── durabledict.sublime-project ├── durabledict ├── __init__.py ├── base.py ├── encoding.py ├── memory.py ├── models.py ├── redis.py └── zookeeper.py ├── setup.py └── tests ├── __init__.py ├── models.py ├── test_dict.py ├── test_encoding.py └── urls.py /.arcconfig: -------------------------------------------------------------------------------- 1 | { 2 | "base": "git:merge-base(origin/master), arc:upstream, git:HEAD^", 3 | "project_id": "durabledict", 4 | "conduit_uri" : "http://phabricator.local.disqus.net/", 5 | "copyright_holder": "Disqus, Inc.", 6 | "history.immutable": false, 7 | "phutil_libraries": {"disqus": "/usr/local/include/php/libdisqus/src"}, 8 | "arcanist_configuration": "DisqusConfiguration", 9 | "differential.field-selector": "DisqusDifferentialFieldSelector", 10 | "history.immutable": false, 11 | "unit.engine": "GenericXUnitTestEngine", 12 | "unit.genericxunit.script": "make test", 13 | "unit.genericxunit.result_path": "recorder/test_results/xunit" 14 | } -------------------------------------------------------------------------------- /.arclint: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "linters" : { 4 | "flake8" : { 5 | "type" : "flake8", 6 | "include" : "(\\.py$)", 7 | "exclude" : "(^.git/|^ci/|/vendor/$)", 8 | "severity.rules" : { 9 | "(^(W292|W391|E501|W602))" : "disabled" 10 | } 11 | }, 12 | "filename" : { 13 | "type" : "filename", 14 | "include" : "(.*)" 15 | }, 16 | "text" : { 17 | "type" : "text", 18 | "include" : "(\\.txt$)", 19 | "text.max-line-length": 1000 20 | }, 21 | "nolint" : { 22 | "type" : "nolint", 23 | "include" : "(.*)" 24 | }, 25 | "generated" : { 26 | "type" : "generated", 27 | "include" : "(.*)" 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - master 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v1 14 | - name: Run 15 | run: docker-compose up -d 16 | - name: Test 17 | run: docker-compose exec -T python make test 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.egg-info/ 3 | *.egg 4 | build/ 5 | dist/ 6 | *.sublime-workspace 7 | *.db 8 | venv/ 9 | .vscode/ 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2010 DISQUS 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include setup.py README.rst MANIFEST.in LICENSE 2 | global-exclude *~ -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VERSION = $(shell python setup.py --version) 2 | 3 | test: 4 | python setup.py test 5 | 6 | release: test 7 | -git tag $(VERSION) 8 | git push origin $(VERSION) 9 | git push origin master 10 | python2.6 setup.py sdist upload --repository ${PYPI} 11 | 12 | watch: 13 | bundle exec guard 14 | 15 | recorder/test_results/xunit: 16 | mkdir -p recorder/test_results/xunit 17 | 18 | .PHONY: test release watch 19 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ---------------- 2 | Durabledict 3 | ---------------- 4 | .. image:: https://github.com/disqus/durabledict/workflows/CI/badge.svg 5 | :alt: GitHub CI 6 | 7 | Durabledict contains a collection of dictionary classes backed by a durable data store (Redis, Django models, etc) suitable for use in a distributed manner. Dictionary values are cached locally in the instance of the dictionary, and only sync with their values with their durable data stores when a value in the data store has changed. 8 | 9 | Usage 10 | ----- 11 | 12 | Durabledict contains various flavors of a dictionary-like objects backed by a durable data store. All dicts classes are located in the ``durabledict`` package. At present, Durabledict offers the following dicts: 13 | 14 | 1. ``durabledict.redis.RedisDict`` - Backed by Redis. 15 | 2. ``durabledict.models.ModelDict`` - Backed by DB objects (most likely Django models). 16 | 3. ``durabledict.zookeeper.ZookeeperDict`` - Backed by Zookeeper. 17 | 18 | Each dictionary class has a different ``__init__`` method which take different arguments, so consult their documentation for specific usage detail. 19 | 20 | Once you have an instance of a durabledict, just use it like you would a normal dictionary:: 21 | 22 | from durabledict import RedisDict 23 | from redis import Redis 24 | 25 | # Construct a new RedisDict object 26 | settings = RedisDict('settings', Redis()) 27 | 28 | # Assign and retrieve a value from the dict 29 | settings['foo'] = 'bar' 30 | settings['foo'] 31 | >>> 'bar' 32 | 33 | # Assign and retrieve another value 34 | settings['buzz'] = 'foogle' 35 | settings['buzz'] 36 | >>> 'foogle' 37 | 38 | # Delete a value and access receives a KeyError 39 | del settings['foo'] 40 | settings['foo'] 41 | >>> KeyError 42 | 43 | All dict types pickle their objects inside their durable data store, so any object that is "pickleable" can be saved to those stores. 44 | 45 | Notes on Persistence, Consistency and the In-Memory Cache 46 | ----------------------------- 47 | 48 | Nearly all methods called on a Durabledict dictionary class (i.e. ``RedisDict``) are proxied to an internal dict object that serves as a cache for access to dict values. This cache is only updated with fresh values from durable storage if there actually has been a change in the values stored in durable storage. 49 | 50 | To check if the data in durable storage has changed, each durabledict backend is responsible for providing a fast ``last_updated()`` method that quickly tells the dict the last time any value in the durable storage has been updated. For instance, the ``Durabledict`` constructor requires a ``cache`` object passed in as an argument, which provides implementations of cache-line interface methods for maintaining the ``last_updated`` state. A memcache client is a good candidate for this object. 51 | 52 | Out of the box by default, all Durabledict classes will sync with their durable data store on all writes (insert, updates and deletes) as well as immediately before any read operation on the dictionary. This mode provides *high read consistency* of data at the expense of read speed. You can be guaranteed that any read operation on your dict, i.e. ``settings['cool_feature']``, will always use the most up to date data. If another consumer of your durable data store has modified a value in that store since you instantiated your object, you will immediately be able to read the new data with your dict instance. 53 | 54 | Manually Control Durable Storage Sync 55 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 56 | 57 | As mentioned above in, the downside to syncing with durable storage before each read of dict data is it lowers your read performance. If you read 100 keys from your dictionary, that means 100 accesses to check ```last_updated()``. Even with a data store as fast as memecache, that adds up quite quickly. 58 | 59 | It therefore may be advantageous for you to *not* sync with durable storage before every read from the dict and instead control that syncing manually. To do so, pass ``autosync=False`` when you construct the dict, i.e.:: 60 | 61 | from durabledict import RedisDict 62 | from redis import Redis 63 | 64 | # Construct a new RedisDict object that does not sync on reads 65 | settings = RedisDict('settings', Redis(), autosync=False) 66 | 67 | This causes the dictionary behave in the following way: 68 | 69 | 1. Like normal, the dictionary initializes from the durable data store upon instantiation. 70 | 2. Writes (both inserts and updates), along with deletes of values to the dictionary will still automatically sync with the data store each time the operation happens. 71 | 3. Any time a dictionary is read from, *only data current in the internal cache is used*. The dict *will not attempt to sync with its durable data store* before reads. 72 | 4. To force the dict to attempt to sync with its durable data store, you may call the ``sync()`` method on the dictionary. As with when ``autosync`` is false, if ``last_update`` says there are no changes, the dict will skip updating from durable storage. 73 | 74 | A good use case for manual syncing is a read-heavy web application, where you're using a durabledict for settings configuration. Very few requests actually *change* the dictionary contents - most simply read from the dictionary. In this situation, you would perhaps only ``sync()`` at the beginning of a user's web request to make sure the dict is up to date, but then not during the request in order to push the response to the user as fast as possible. 75 | 76 | Encoding 77 | -------- 78 | 79 | All ``durabledict`` implementations accept an ``encoding`` keyword argument, which defines the encoding object the dictionary should use when serializing data to and from the persistent data store. The overarching goal of the ``encoding`` is to serialize the dictionary value object into a format suitable for persisting to durable storage, and then at a later date reconstructing that object from its serialized representation into an object 80 | in memory. 81 | 82 | By default, `durabledict` uses pickle as its encoding format, which allows it to serialize complex object easily at the expense of `known security implications`:security and other limitations. See `this IBM Developerworks`:devworks article for an overview of Pickle. 83 | 84 | .. security: https://docs.python.org/release/3.0.1/library/pickle.html#pickle-restrict 85 | .. _devworks: http://www.ibm.com/developerworks/library/l-pypers/ 86 | 87 | In addition to the built in ``encoding.PickleEncoding``, ``durabledict`` also features ``encoding.JSONEncoding`` which encodes the data as JSON and ``encoding.NoOpEncoding`` which does not encode the data at all (suitable only for the ``MemoryDict`` implementation). 88 | 89 | Integration with Django 90 | ------------------------ 91 | 92 | If you would like to store your dict values in the database for your Django application, you should use the ``durabledict.models.Durabledict`` class. This class takes an instance of a model's manager, as well as ``key_col`` and ``value_col`` arguments which can be used to tell ``Durabledict`` which columns on your object it should use to store data. 93 | 94 | It's also probably most advantageous to construct your dicts with ``autosync=False`` (see "Manually Control Durable Storage Sync" above) and manually call ``sync()`` before each request. This can be accomplished most easily via the ``request_started`` signal:: 95 | 96 | django.core.signals.request_started.connect(settings.sync) 97 | 98 | Creating Your Own Durable Dict 99 | --------------------------------- 100 | 101 | Creating your own durable dict is easy. All you need to do is subclass ``durabledict.base.DurableDict`` and implement the following required interface methods. 102 | 103 | 1. ``persist(key, value)`` - Persist ``value`` at ``key`` to your data store. 104 | 2. ``depersist(key)`` - Delete the value at ``key`` from your data store. 105 | 3. ``durables()`` - Return a ``key=val`` dict of all keys in your data store. 106 | 4. ``last_updated()`` - A comparable value of when the data in your data store was last updated. 107 | 108 | You may also implement a couple optional dictionary methods, which ``durabledict.base.DurableDict`` will call when the actual non-underscored version is called on the dict. 109 | 110 | 1. ``_pop(key[,default])`` - If ``key`` is in the dictionary, remove it and return its value, else return ``default``. If ``default`` is not given and ``key`` is not in the dictionary, a ``KeyError`` is raised. 111 | 2. ``_setdefault(key[,default])`` - If key is in the dictionary, return its value. If not, insert key with a value of ``default`` and return ``default``. ``default`` defaults to ``None``. 112 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | 4 | python: 5 | image: python:2.7 6 | command: sleep infinity 7 | working_dir: /app 8 | volumes: 9 | - .:/app 10 | 11 | zookeeper: 12 | image: zookeeper:3.7 13 | 14 | redis: 15 | image: redis:6.2 16 | -------------------------------------------------------------------------------- /durabledict.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | "build_systems": 3 | [ 4 | { 5 | "name": "Anaconda Python Builder", 6 | "selector": "source.python", 7 | "shell_cmd": "python -u \"$file\"" 8 | } 9 | ], 10 | "folders": 11 | [ 12 | { 13 | "file_exclude_patterns": 14 | [ 15 | "*.egg", 16 | "*.sublime-workspace", 17 | "*_pb2.py" 18 | ], 19 | "folder_exclude_patterns": 20 | [ 21 | "*.egg", 22 | "build", 23 | "dist", 24 | "*.egg-info", 25 | "doc/_*", 26 | ".ropeproject" 27 | ], 28 | "path": "." 29 | } 30 | ], 31 | "settings": 32 | { 33 | "tab_size": 4, 34 | "translate_tabs_to_spaces": true, 35 | "trim_trailing_white_space_on_save": true 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /durabledict/__init__.py: -------------------------------------------------------------------------------- 1 | from durabledict.redis import RedisDict 2 | from durabledict.memory import MemoryDict 3 | from durabledict.models import ModelDict 4 | from durabledict.zookeeper import ZookeeperDict 5 | -------------------------------------------------------------------------------- /durabledict/base.py: -------------------------------------------------------------------------------- 1 | from durabledict.encoding import ( 2 | DefaultEncoding, 3 | EncodingError, 4 | ) 5 | 6 | 7 | class DurableDict(object): 8 | """ 9 | Dictionary that calls out to its persistant data store when items are 10 | created or deleted. Syncs with data fron the data store before every read, 11 | unless ``autosync=False`` is passed, which causes the dict to only sync 12 | data from the data store on writes and when ``sync()`` is called. 13 | 14 | By default, objects are encoded in the durable store using 15 | ``encoding.PickleEncoding``, but that can be changed by passing in another 16 | encoder in as the ``encoding`` kwarg. 17 | 18 | If you need to switch between two encodings provide the old_encoding as a fallback. 19 | """ 20 | 21 | def __init__(self, autosync=True, encoding=DefaultEncoding, old_encoding=None): 22 | self.__dict = dict() 23 | self.last_synced = 0 24 | self.autosync = autosync 25 | self.encoding = encoding 26 | self.old_encoding = old_encoding 27 | self.__sync_with_durable_storage(force=True) 28 | 29 | @property 30 | def cache_expired(self): 31 | persistance_last_updated = self.last_updated() 32 | 33 | if not self.last_synced or persistance_last_updated > self.last_synced: 34 | return persistance_last_updated 35 | 36 | def sync(self): 37 | self.__sync_with_durable_storage(force=True) 38 | 39 | def pop(self, key, default=None): 40 | result = self._pop(key, default) 41 | self.__sync_with_durable_storage(force=True) 42 | return result 43 | 44 | def setdefault(self, key, default=None): 45 | result = self._setdefault(key, default) 46 | self.__sync_with_durable_storage(force=True) 47 | return result 48 | 49 | def get(self, key, default=None): 50 | self.__sync_with_durable_storage() 51 | return self.__dict.get(key, default) 52 | 53 | def __setitem__(self, key, val): 54 | self.persist(key, val) 55 | self.__sync_with_durable_storage(force=True) 56 | 57 | def __delitem__(self, key): 58 | self.depersist(key) 59 | self.__sync_with_durable_storage(force=True) 60 | 61 | def __getitem__(self, key): 62 | self.__sync_with_durable_storage() 63 | return self.__dict.__getitem__(key) 64 | 65 | def __getattr__(self, name): 66 | self.__sync_with_durable_storage() 67 | return getattr(self.__dict, name) 68 | 69 | def __len__(self): 70 | self.__sync_with_durable_storage() 71 | return self.__dict.__len__() 72 | 73 | # NOTE: This function is unused in python 3 and should be removed. 74 | def __cmp__(self, other): 75 | self.__sync_with_durable_storage() 76 | return self.__dict.__cmp__(other) 77 | 78 | def __eq__(self, other): 79 | self.__sync_with_durable_storage() 80 | return self.__dict == other 81 | 82 | def __repr__(self): 83 | return self.__dict.__repr__() 84 | 85 | def __contains__(self, key): 86 | self.__sync_with_durable_storage() 87 | return self.__dict.__contains__(key) 88 | 89 | def __sync_with_durable_storage(self, force=False): 90 | if not self.autosync and not force: 91 | return 92 | 93 | cache_expired_at = self.cache_expired 94 | 95 | if cache_expired_at: 96 | self.__dict = self.durables() 97 | self.last_synced = cache_expired_at 98 | 99 | def _encode(self, val): 100 | try: 101 | return self.encoding.encode(val) 102 | except EncodingError: 103 | if self.old_encoding: 104 | return self.old_encoding.encode(val) 105 | else: 106 | raise 107 | 108 | def _decode(self, val): 109 | try: 110 | return self.encoding.encode(val) 111 | except EncodingError: 112 | if self.old_encoding: 113 | return self.old_encoding.encode(val) 114 | else: 115 | raise 116 | 117 | def persist(self, key, val): 118 | raise NotImplementedError 119 | 120 | def depersist(self, key): 121 | raise NotImplementedError 122 | 123 | def durables(self): 124 | raise NotImplementedError 125 | 126 | def last_updated(self): 127 | raise NotImplementedError 128 | 129 | 130 | class ConnectionDurableDict(DurableDict): 131 | """Base for Durable Dict classes that are connection oriented.""" 132 | 133 | def __init__(self, keyspace, connection, *args, **kwargs): 134 | self.keyspace = keyspace 135 | self.connection = connection 136 | 137 | self.connection_hook() 138 | 139 | super(ConnectionDurableDict, self).__init__(*args, **kwargs) 140 | 141 | def connection_hook(self): 142 | pass 143 | -------------------------------------------------------------------------------- /durabledict/encoding.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import pickle 3 | 4 | 5 | try: 6 | import simplejson as json 7 | except ImportError: 8 | import json 9 | 10 | 11 | class EncoderError(ValueError): 12 | pass 13 | 14 | 15 | class EncodingError(EncoderError): 16 | pass 17 | 18 | 19 | class DecodingError(EncoderError): 20 | pass 21 | 22 | 23 | class Encoder(object): 24 | encoding_exceptions = () 25 | decoding_exceptions = () 26 | 27 | @staticmethod 28 | def encoder(data): 29 | raise NotImplementedError() 30 | 31 | @staticmethod 32 | def decoder(data): 33 | raise NotImplementedError() 34 | 35 | @classmethod 36 | def encode(cls, *args, **kwargs): 37 | try: 38 | return cls.encoder(*args, **kwargs) 39 | except cls.encoding_exceptions as e: 40 | raise EncodingError(e) 41 | 42 | @classmethod 43 | def decode(cls, *args, **kwargs): 44 | try: 45 | return cls.decoder(*args, **kwargs) 46 | except cls.decoding_exceptions as e: 47 | raise DecodingError(e) 48 | 49 | 50 | class NoOpEncoding(Encoder): 51 | encode = staticmethod(lambda d: d) 52 | decode = staticmethod(lambda d: d) 53 | 54 | 55 | class PickleEncoding(Encoder): 56 | encoding_exceptions = (TypeError, pickle.PicklingError,) 57 | decoding_exceptions = (TypeError, pickle.UnpicklingError,) 58 | 59 | @staticmethod 60 | def encoder(data): 61 | pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL) 62 | return base64.encodestring(pickled) 63 | 64 | @staticmethod 65 | def decoder(data): 66 | pickled = base64.decodestring(data) 67 | return pickle.loads(pickled) 68 | 69 | 70 | class JSONEncoding(Encoder): 71 | encoding_exceptions = (TypeError, ValueError,) 72 | decoding_exceptions = (TypeError, ValueError,) 73 | 74 | encoder = staticmethod(json.dumps) 75 | decoder = staticmethod(json.loads) 76 | 77 | 78 | DefaultEncoding = PickleEncoding 79 | -------------------------------------------------------------------------------- /durabledict/memory.py: -------------------------------------------------------------------------------- 1 | from durabledict.base import DurableDict 2 | from durabledict.encoding import NoOpEncoding 3 | 4 | 5 | class MemoryDict(DurableDict): 6 | 7 | ''' 8 | Does not actually persist any data to a persistant storage. Instead, keeps 9 | everything in memory. This is really only useful for use in tests 10 | ''' 11 | 12 | def __init__(self, autosync=True, encoding=NoOpEncoding, *args, **kwargs): 13 | self.__storage = dict() 14 | self.__last_updated = 1 15 | 16 | super(MemoryDict, self).__init__(autosync, encoding, *args, **kwargs) 17 | 18 | def persist(self, key, val): 19 | self.__storage[key] = self.encoding.encode(val) 20 | self.__last_updated += 1 21 | 22 | def depersist(self, key): 23 | del self.__storage[key] 24 | self.__last_updated += 1 25 | 26 | def durables(self): 27 | encoded_tuples = self.__storage.items() 28 | tuples = [(k, self.encoding.decode(v)) for k, v in encoded_tuples] 29 | return dict(tuples) 30 | 31 | def last_updated(self): 32 | return self.__last_updated 33 | 34 | def _setdefault(self, key, default=None): 35 | self.__last_updated += 1 36 | val = self.__storage.setdefault(key, self.encoding.encode(default)) 37 | return self.encoding.decode(val) 38 | 39 | def _pop(self, key, default=None): 40 | self.__last_updated += 1 41 | 42 | if default: 43 | default = self.encoding.encode(default) 44 | 45 | val = self.__storage.pop(key, default) 46 | 47 | if val is None: 48 | raise KeyError 49 | 50 | return self.encoding.decode(val) 51 | -------------------------------------------------------------------------------- /durabledict/models.py: -------------------------------------------------------------------------------- 1 | from durabledict.base import DurableDict 2 | 3 | 4 | class ModelDict(DurableDict): 5 | 6 | """ 7 | Dictionary-style access to a model. Populates a cache and a local in-memory 8 | to avoid multiple hits to the database. 9 | 10 | # Given ``Model`` that has a primary key (``pk``) column that can be 11 | # strings: 12 | 13 | mydict = ModelDict(Model.manager, value_col='foo') 14 | mydict['test'] 15 | >>> 'bar' #doctest: +SKIP 16 | 17 | The first positional argument to ``ModelDict`` is ``manager``, which is an 18 | instance of a Manager which ``ModelDict`` uses to read and write to your 19 | database. Any object that conforms to the interface can work, but the 20 | expectation is that ``manager`` is a Django.model manager. 21 | 22 | The constructor also takes a 2nd positional ``cache`` argument, which is an 23 | object that responds to two methods, add and incr. The cache object is used 24 | to manage the value for last_updated. ``add`` is called on initialize to 25 | create the key if it does not exist with the default value, and ``incr`` is 26 | done to atomically update the last_updated value. 27 | 28 | By default, ``ModelDict`` will use the ``pk`` column of your model as the 29 | "key" for the dictionary. If you want to use another key besides the 30 | ``Model``s ``pk``, you may specify that in the constructor with ``key_col`` 31 | kwarg. For instance, if your ``Model`` has a column called ``id``, you can 32 | index into that column by passing ``key_col='id'`` in to the contructor: 33 | 34 | mydict = ModelDict(Model, key_col='id', value_col='foo') 35 | mydict['test'] 36 | >>> 'bar' #doctest: +SKIP 37 | 38 | Additionally, the default column used to store the values is the ``value`` 39 | column. If you'd like to use another column pass the ``value_col`` kwarg to 40 | the constructor. 41 | 42 | By default, ``ModelDict`` instances will return the decoded value present in 43 | the ``value_col``. If, instead, you would like to return the entire model 44 | instance, you can instead pass ``True`` to the ``return_instances`` kwarg. 45 | """ 46 | 47 | #: The value to increate last_updated by, in the event that the key is 48 | # missing from the cache. See the comment inside touch_last_updated for 49 | # details. 50 | LAST_UPDATED_MISSING_INCREMENT = 1000 51 | 52 | def __init__( 53 | self, 54 | manager=None, 55 | cache=None, 56 | key_col='key', 57 | value_col='value', 58 | return_instances=False, 59 | *args, 60 | **kwargs 61 | ): 62 | self.manager = manager 63 | self.cache = cache 64 | self.cache_key = 'last_updated' 65 | self.return_instances = return_instances 66 | self.key_col = key_col 67 | self.value_col = value_col 68 | 69 | self.cache.add(self.cache_key, 1) # Only adds if key does not exist 70 | 71 | super(ModelDict, self).__init__(*args, **kwargs) 72 | 73 | def persist(self, key, val): 74 | instance, created = self.get_or_create(key, val) 75 | 76 | if not created and getattr(instance, self.value_col) != val: 77 | setattr(instance, self.value_col, self.encoding.encode(val)) 78 | instance.save() 79 | 80 | self.touch_last_updated() 81 | 82 | def depersist(self, key): 83 | self.manager.get(**{self.key_col: key}).delete() 84 | self.touch_last_updated() 85 | 86 | def durables(self): 87 | if self.return_instances: 88 | return dict((i.key, i) for i in self.manager.all()) 89 | else: 90 | encoded_tuples = self.manager.values_list( 91 | self.key_col, 92 | self.value_col 93 | ) 94 | return dict((k, self.encoding.decode(v)) for k, v in encoded_tuples) 95 | 96 | def _setdefault(self, key, default=None): 97 | instance, created = self.get_or_create(key, default) 98 | 99 | if created: 100 | self.touch_last_updated() 101 | 102 | return self.encoding.decode(getattr(instance, self.value_col)) 103 | 104 | def _pop(self, key, default=None): 105 | try: 106 | instance = self.manager.get(**{self.key_col: key}) 107 | value = self.encoding.decode(getattr(instance, self.value_col)) 108 | instance.delete() 109 | self.touch_last_updated() 110 | return value 111 | except self.manager.model.DoesNotExist: 112 | if default is not None: 113 | return default 114 | else: 115 | raise KeyError 116 | 117 | def get_or_create(self, key, val): 118 | return self.manager.get_or_create( 119 | defaults={self.value_col: self.encoding.encode(val)}, 120 | **{self.key_col: key} 121 | ) 122 | 123 | def last_updated(self): 124 | return self.cache.get(self.cache_key) 125 | 126 | def touch_last_updated(self): 127 | try: 128 | self.cache.incr(self.cache_key) 129 | except ValueError: 130 | # The last_updated cache key is missing. This may be because it has 131 | # expired or been explicitly deleted. It is then necessary to 132 | # recreate the value. by synthesizing an ``incr``. This is 133 | # accomplished by adding the current ``self.last_synced`` value plus 134 | # some increment, naively "1". 135 | # 136 | # However, there is a race condition. It is entirely possible that 137 | # an instance of DurableDict which sees the key as missing may 138 | # have an out of date value for ``self.last_synced`` - such as if 139 | # multiple updates have occurred from other instances of DurableDict 140 | # (and are reflected in the cache value of last_udated), but this 141 | # instance of DurableDict has not seen those changes yet. If the 142 | # cache key is deleted before this instance hasn't seen those 143 | # changed, but this instance sees the cache as expired, then it will 144 | # update the value to what it knows to be last_synced + 1, which is 145 | # incorrect. 146 | # 147 | # A workaround to this problem is to set the new cache value to what 148 | # this instance thinks last_synced is + some non-trivial number. 149 | # This is not a perfect solution, as it's possible there could be 150 | # LAST_UPDATED_MISSING_INCREMENT changes to the dict since this 151 | # instance last checked, so LAST_UPDATED_MISSING_INCREMENT should 152 | # be set to a value high enough to where that possibility is 153 | # unlikely. 154 | added_key = self.cache.add( 155 | self.cache_key, 156 | self.last_synced + self.LAST_UPDATED_MISSING_INCREMENT 157 | ) 158 | 159 | # XXX There is still race condition here. It is possible that the 160 | # key can be deleted between the call to ``add`` and ``incr``, in 161 | # which case the ``incr`` call will fail. This is a unlikely 162 | # scenario and as such is not handled. 163 | 164 | # If the ``add`` did not succeed, it means that another instance of 165 | # DurableDict beat this one to adding the cache value back and so 166 | # this instance should do the ``incr`` like normal. 167 | if not added_key: 168 | self.cache.incr(self.cache_key) 169 | -------------------------------------------------------------------------------- /durabledict/redis.py: -------------------------------------------------------------------------------- 1 | from durabledict.base import ConnectionDurableDict 2 | 3 | 4 | class RedisDict(ConnectionDurableDict): 5 | 6 | """ 7 | Dictionary-style access to a redis hash table. Populates a cache and a local 8 | in-memory to avoid multiple hits to the database. 9 | 10 | Functions just like you'd expect it:: 11 | 12 | mydict = RedisDict('my_redis_key', Redis()) 13 | mydict['test'] 14 | >>> 'bar' #doctest: +SKIP 15 | """ 16 | 17 | def __init__(self, *args, **kwargs): 18 | super(RedisDict, self).__init__(*args, **kwargs) 19 | self.__touch_last_updated() 20 | 21 | def persist(self, key, value): 22 | encoded = self.encoding.encode(value) 23 | self.__touch_and_multi(('hset', (self.keyspace, key, encoded))) 24 | 25 | def depersist(self, key): 26 | self.__touch_and_multi(('hdel', (self.keyspace, key))) 27 | 28 | def durables(self): 29 | encoded = self.connection.hgetall(self.keyspace) 30 | tuples = [(k, self.encoding.decode(v)) for k, v in encoded.items()] 31 | return dict(tuples) 32 | 33 | def last_updated(self): 34 | return int(self.connection.get(self.__last_update_key) or 0) 35 | 36 | # TODO: setdefault always touches the last_updated value, even if the key 37 | # existed already. It should only touch last_updated if the key did not 38 | # already exist 39 | def _setdefault(self, key, default=None): 40 | encoded = self.__touch_and_multi( 41 | ('hsetnx', (self.keyspace, key, self.encoding.encode(default))), 42 | ('hget', (self.keyspace, key)), 43 | returns=-1 44 | ) 45 | return self.encoding.decode(encoded) 46 | 47 | def _pop(self, key, default=None): 48 | last_updated, encoded, key_existed = self.__touch_and_multi( 49 | ('hget', (self.keyspace, key)), 50 | ('hdel', (self.keyspace, key)) 51 | ) 52 | 53 | if key_existed: 54 | return self.encoding.decode(encoded) 55 | elif default: 56 | return default 57 | else: 58 | raise KeyError 59 | 60 | def __touch_and_multi(self, *args, **kwargs): 61 | """ 62 | Runs each tuple tuple of (redis_cmd, args) in provided inside of a Redis 63 | MULTI block, plus an increment of the last_updated value, then executes 64 | the MULTI block. If ``returns`` is specified, it returns that index 65 | from the results list. If ``returns`` is None, returns all values. 66 | """ 67 | 68 | with self.connection.pipeline() as pipe: 69 | pipe.incr(self.__last_update_key) 70 | [getattr(pipe, function)(*a) for function, a in args] 71 | results = pipe.execute() 72 | 73 | if kwargs.get('returns'): 74 | return results[kwargs.get('returns')] 75 | else: 76 | return results 77 | 78 | def __touch_last_updated(self): 79 | return self.connection.incr(self.__last_update_key) 80 | 81 | @property 82 | def __last_update_key(self): 83 | return self.keyspace + 'last_updated' 84 | -------------------------------------------------------------------------------- /durabledict/zookeeper.py: -------------------------------------------------------------------------------- 1 | from durabledict.base import ConnectionDurableDict 2 | 3 | from functools import wraps 4 | import posixpath 5 | 6 | 7 | def validate_key(func): 8 | """ 9 | Decorator to validate a key for zookeeper. 10 | """ 11 | 12 | @wraps(func) 13 | def wrapper(self, key, *args, **kwargs): 14 | if posixpath.sep in key: 15 | raise ValueError('Keys cannot contains slashes') 16 | 17 | return func(self, key, *args, **kwargs) 18 | 19 | return wrapper 20 | 21 | 22 | class ZookeeperDict(ConnectionDurableDict): 23 | 24 | """ 25 | Dictionary backed by Zookeeper. Functions just as you would expect a normal 26 | dictiony to function, except the values in the dictionary are persisted and 27 | loaed from Zookeper located at the spcified ``path`` in the constructor. 28 | 29 | Due to Zookeeper's watchers, this dictionary has the nice property that the 30 | called to its ``last_updated`` method (to check if the storage has been 31 | updated since the dict was last synced) simply returns a cached value -- it 32 | does not query Zookeeper or anything like that, so it's basically free. 33 | This means that you can run this dictionary with ``autosync=True`` and it 34 | will still be reasonably performant. 35 | 36 | Dictionary keys in a ``ZookeeperDict`` are stored at inividual nodes in the 37 | zookeeper heirarchy, with the value of the node being the value of that key. 38 | Each node for each dict key is a child of the "root" node, whose path is 39 | specified with the ``path`` argument in the constructor. 40 | 41 | >>> from durabledict.dict import ZookeeperDict 42 | >>> from kazoo.client import KazooClient 43 | >>> kazoo = KazooClient() 44 | >>> kazoo.start() 45 | >>> zkdict = ZookeeperDict(kazoo, '/app/config') 46 | >>> zkdict['exchange_rate'] = 25 47 | >>> zkdict['language'] = 'en-US' 48 | >>> zkdict['exchange_rate'] 49 | 25 50 | >>> zkdict['language'] 51 | 'en-US' 52 | >>> zkdict.pop('exchange_rate') 53 | 25 54 | >>> zkdict['exchange_rate'] 55 | Traceback (most recent call last): 56 | File "", line 1, in 57 | File "durabledict/base.py", line 53, in __getitem__ 58 | return self.__dict.__getitem__(key) 59 | KeyError: 'exchange_rate' 60 | 61 | NOTE: unlike ``RedisDict`` or ``Durabledict``, which are backed by hightly 62 | consistent backend storages, ``ZookeeperDict`` is backed with Zookeeper, 63 | which has looser consistency guarantees. 64 | 65 | Please see this page in the Zookeeper docs for details: 66 | 67 | http://zookeeper.apache.org/doc/r3.1.2/zookeeperProgrammers.html#ch_zkGuarantees 68 | 69 | The basic things to keep in mind are: 70 | 71 | Sequential Consistency: 72 | Updates from a client will be applied in the order that they were sent. 73 | 74 | Atomicity: 75 | Updates either succeed or fail -- there are no partial results. 76 | 77 | Single System Image: 78 | A client will see the same view of the service regardless of the server 79 | that it connects to. 80 | 81 | Reliability: 82 | Once an update has been applied, it will persist from that time forward 83 | until a client overwrites the update. This guarantee has two 84 | corollaries: 85 | 86 | If a client gets a successful return code, the update will have been 87 | applied. On some failures (communication errors, timeouts, etc) the 88 | client will not know if the update has applied or not. We take steps 89 | to minimize the failures, but the only guarantee is only present 90 | with successful return codes. (This is called the monotonicity 91 | condition in Paxos.) 92 | 93 | Any updates that are seen by the client, through a read request or 94 | successful update, will never be rolled back when recovering from 95 | server failures. 96 | 97 | Timeliness: 98 | The clients view of the system is guaranteed to be up-to-date within a 99 | certain time bound. (On the order of tens of seconds.) Either system 100 | changes will be seen by a client within this bound, or the client will 101 | detect a service outage. 102 | 103 | The cliff notes version of this is that a client's view of the world will 104 | always be consistent (you can read your own writes), but updates from other 105 | clients can take time to propogate to other clients. 106 | """ 107 | 108 | def __init__(self, *args, **kwargs): 109 | """ 110 | Construct a new instance of a ``ZookeeperDict``. 111 | 112 | :param connection: Zookeeper client, likely ``KazooClient`` 113 | :type connection: KazooClient 114 | :param keyspace: The path to the root config node. 115 | :type keyspace: string 116 | :param autosync: Sync with Zookeeper before each read. 117 | :type autosync: bool 118 | """ 119 | super(ZookeeperDict, self).__init__(*args, **kwargs) 120 | 121 | def connection_hook(self): 122 | if not self.connection.connected: 123 | self.connection.start() 124 | 125 | self.connection.retry(self.connection.ensure_path, self.keyspace) 126 | self._last_updated = None 127 | 128 | # TODO: The base DurableDict class updates last_updated itself 129 | # manually when adding a new key with __setattr__, as well as this watch 130 | # also incrementing the value. 131 | self.child_watch = self.connection.retry( 132 | self.connection.ChildrenWatch, 133 | self.keyspace, 134 | self.__increment_last_updated 135 | ) 136 | 137 | @property 138 | def no_node_error(self): 139 | from kazoo.exceptions import NoNodeError 140 | return NoNodeError 141 | 142 | def last_updated(self): 143 | """ 144 | Ever-increasing integer, which is bumped any time a key in Zookeeper has 145 | been changed (created, updated, deleted). 146 | 147 | The value in incremented manually by an instances when updating the 148 | dict, as well as when other instances of the dict update persistant 149 | storage, via a Zookeeper watch on the root config node. 150 | """ 151 | return self._last_updated 152 | 153 | @validate_key 154 | def persist(self, key, value): 155 | """ 156 | Encode and save ``value`` at ``key``. 157 | 158 | :param key: Key to store ``value`` at in Zookeeper. 159 | :type key: string 160 | :param value: Value to store. Encoded before being stored. 161 | :type value: value 162 | """ 163 | encoded = self.encoding.encode(value) 164 | self.__set_or_create(key, encoded) 165 | self.__increment_last_updated() 166 | 167 | @validate_key 168 | def depersist(self, key): 169 | """ 170 | Remove ``key`` from dictionary. 171 | 172 | :param key: Key to remove from Zookeeper. 173 | :type key: string 174 | """ 175 | self.connection.retry(self.connection.delete, self.__path_of(key)) 176 | self.__increment_last_updated() 177 | 178 | def durables(self): 179 | """ 180 | Dictionary of all keys and their values in Zookeeper. 181 | """ 182 | results = dict() 183 | 184 | for child in self.connection.retry(self.connection.get_children, self.keyspace): 185 | value, _ = self.connection.retry( 186 | self.connection.get, 187 | self.__path_of(child), 188 | watch=self.__increment_last_updated 189 | ) 190 | results[child] = self.encoding.decode(value) 191 | 192 | return results 193 | 194 | @validate_key 195 | def _pop(self, key, default=None): 196 | """ 197 | If ``key`` is present in Zookeeper, removes it from Zookeeper and 198 | returns the value. If key is not in Zookeper and ``default`` argument 199 | is provided, ``default`` is returned. If ``default`` argument is not 200 | provided, ``KeyError`` is raised. 201 | 202 | :param key: Key to remove from Zookeeper 203 | :type key: string 204 | :param default: Default object to return if ``key`` is not present. 205 | :type default: object 206 | """ 207 | path = self.__path_of(key) 208 | value = None 209 | 210 | try: 211 | # We need to both delete and return the value that was in ZK here. 212 | raw_value, _ = self.connection.retry(self.connection.get, path) 213 | value = self.encoding.decode(raw_value) 214 | except self.no_node_error: 215 | # The node is already gone, so if a default is given, return it, 216 | # otherwise, raise KeyError 217 | if default: 218 | return default 219 | else: 220 | raise KeyError 221 | 222 | # Made it this far, it means have a value from the node and it existed 223 | # at least by that point in time 224 | try: 225 | # Try to delete the node 226 | self.connection.retry(self.connection.delete, path) 227 | self.__increment_last_updated() 228 | except self.no_node_error: 229 | # Someone deleted the node in the mean time...how nice! 230 | pass 231 | 232 | return value 233 | 234 | @validate_key 235 | def _setdefault(self, key, default=None): 236 | """ 237 | If ``key`` is not present, set it as ``default`` and return it. If 238 | ``key`` is present, return its value. 239 | 240 | :param key: Key to add to Zookeeper 241 | :type key: string 242 | :param default: Default object to return if ``key`` is present. 243 | :type default: object 244 | 245 | Will retry trying to get or create a node based on the "retry" config 246 | from the Kazoo client. 247 | """ 248 | return self.connection.retry(self.__inner_set_default, key, default) 249 | 250 | def __path_of(self, key): 251 | return posixpath.join(self.keyspace, key) 252 | 253 | def __set_or_create(self, key, value): 254 | path = self.__path_of(key) 255 | self.connection.retry(self.connection.ensure_path, path) 256 | self.connection.retry(self.connection.set, path, value) 257 | 258 | def __increment_last_updated(self, children=None): 259 | if self._last_updated is None: 260 | self._last_updated = 0 261 | 262 | self._last_updated += 1 263 | 264 | def __inner_set_default(self, key, value): 265 | """ 266 | Tries to return the value at key. If the key does not exist, attempts 267 | to create it with the value. If the node is created in the mean time, 268 | a ``NodeExistsError`` will be raised. 269 | """ 270 | path = self.__path_of(key) 271 | 272 | try: 273 | # Try to get and return the existing node with its data 274 | value, _ = self.connection.retry(self.connection.get, path) 275 | return self.encoding.decode(value) 276 | except self.no_node_error: 277 | # Node does not exist, we have to create it 278 | self.connection.retry(self.connection.create, path, self.encoding.encode(value)) 279 | self.__increment_last_updated() 280 | return value 281 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | import glob 6 | from setuptools import setup 7 | 8 | 9 | try: 10 | import multiprocessing # Seems to fix http://bugs.python.org/issue15881 11 | except ImportError: 12 | pass 13 | 14 | setup( 15 | name='durabledict', 16 | version='0.9.4', 17 | author='DISQUS', 18 | author_email='opensource@disqus.com', 19 | url='http://github.com/disqus/durabledict/', 20 | description='Dictionary-style access to different types of models.', 21 | packages=['durabledict'], 22 | zip_safe=False, 23 | tests_require=[ 24 | 'Django<1.7', 25 | 'nose', 26 | 'mock', 27 | 'redis', 28 | 'kazoo', 29 | ], 30 | test_suite='nose.collector', 31 | include_package_data=True, 32 | classifiers=[ 33 | 'Intended Audience :: Developers', 34 | 'Intended Audience :: System Administrators', 35 | 'Operating System :: OS Independent', 36 | 'Topic :: Software Development' 37 | ], 38 | ) 39 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/disqus/durabledict/deab74684e68a31ff789d5471a0b3401aed8785d/tests/__init__.py -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | if not settings.configured: 4 | settings.configure( 5 | DATABASES={ 6 | 'default': { 7 | 'ENGINE': 'django.db.backends.sqlite3', 8 | 'NAME': 'test.db' 9 | } 10 | }, 11 | INSTALLED_APPS=[ 12 | 'tests', 13 | ], 14 | 15 | DEBUG=True, 16 | ) 17 | 18 | from django.db import models 19 | 20 | 21 | class Setting(models.Model): 22 | key = models.CharField(max_length=32, unique=True) 23 | value = models.CharField(max_length=32, default='') 24 | -------------------------------------------------------------------------------- /tests/test_dict.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | import unittest 4 | import mock 5 | 6 | from redis import Redis 7 | from durabledict import RedisDict, ModelDict, MemoryDict, ZookeeperDict 8 | from tests.models import Setting 9 | 10 | from contextlib import contextmanager 11 | 12 | import django.core.management 13 | from django.core.cache.backends.locmem import LocMemCache 14 | 15 | from kazoo.client import KazooClient 16 | 17 | import threading 18 | import thread 19 | 20 | 21 | class BaseTest(object): 22 | 23 | @property 24 | def dict_class(self): 25 | return self.dict.__class__.__name__ 26 | 27 | def setUp(self): 28 | super(BaseTest, self).setUp() 29 | self.keyspace = 'test' 30 | self.dict = self.new_dict() 31 | 32 | def mockmeth(self, method): 33 | return "durabledict.%s.%s" % (self.dict_class, method) 34 | 35 | def assertDictAndPersistantsHave(self, **kwargs): 36 | self.assertEquals(self.dict, kwargs) 37 | self.assertEquals(self.dict.durables(), kwargs) 38 | 39 | def test_acts_like_a_dictionary(self): 40 | self.dict['foo'] = 'bar' 41 | self.assertEquals(self.dict['foo'], 'bar') 42 | self.dict['foo2'] = 'bar2' 43 | self.assertEquals(self.dict['foo2'], 'bar2') 44 | 45 | def test_updates_dict_keys(self): 46 | self.dict['foo'] = 'bar' 47 | self.assertEquals(self.dict['foo'], 'bar') 48 | self.dict['foo'] = 'newbar' 49 | self.assertEquals(self.dict['foo'], 'newbar') 50 | 51 | def test_raises_keyerror_on_bad_access(self): 52 | self.dict['foo'] = 'bar' 53 | self.dict.__getitem__('foo') 54 | del self.dict['foo'] 55 | self.assertRaises(KeyError, self.dict.__getitem__, 'foo') 56 | 57 | def test_setitem_calls_persist_with_value(self): 58 | with mock.patch(self.mockmeth('persist')) as pv: 59 | self.dict['foo'] = 'bar' 60 | pv.assert_called_with('foo', 'bar') 61 | 62 | def test_can_save_and_retrieve_complex_objects(self): 63 | complex_vars = ('tuple', 'fun', 1.0, [1, 2, 3, 4], u'☃') 64 | self.dict['foo'] = complex_vars 65 | 66 | self.assertEquals(complex_vars, self.dict['foo']) 67 | self.assertEquals(dict(foo=complex_vars), self.dict.durables()) 68 | 69 | self.assertEquals(self.dict.setdefault('foo', complex_vars), complex_vars) 70 | self.assertEquals(self.dict.setdefault('bazzle', 'fuzzle'), 'fuzzle') 71 | 72 | self.assertEquals(self.dict.pop('foo'), complex_vars) 73 | 74 | def test_setdefault_works_and_persists_correctly(self): 75 | self.assertFalse(self.dict.get('foo')) 76 | 77 | self.assertTrue(self.dict.setdefault('foo', 'bar'), 'bar') 78 | self.assertTrue(self.dict.setdefault('foo', 'notset'), 'bar') 79 | 80 | self.assertDictAndPersistantsHave(foo='bar') 81 | self.assertEquals(self.dict['foo'], 'bar') 82 | 83 | def test_delitem_calls_depersist(self): 84 | self.dict['foo'] = 'bar' 85 | 86 | with mock.patch(self.mockmeth('depersist')) as dp: 87 | del self.dict['foo'] 88 | dp.assert_called_with('foo') 89 | 90 | def test_uses_existing_durables_on_initialize(self): 91 | with mock.patch(self.mockmeth('durables')) as p: 92 | p.return_value = dict(a=1, b=2, c=3) 93 | self.assertEquals(self.new_dict(), dict(a=1, b=2, c=3)) 94 | 95 | def test_last_updated_setup_on_intialize(self): 96 | self.assertTrue(self.dict.last_updated()) 97 | 98 | def test_last_updated_set_when_persisted(self): 99 | before = self.dict.last_updated() 100 | 101 | self.dict.persist('foo', 'bar') 102 | self.assertTrue(self.dict.last_updated() > before) 103 | 104 | def test_last_updated_set_when_depersisted(self): 105 | self.dict.persist('foo', 'bar') 106 | before = self.dict.last_updated() 107 | 108 | self.dict.depersist('foo') 109 | self.assertTrue(self.dict.last_updated() > before) 110 | 111 | def test_calling_update_raises_notimplemented(self): 112 | self.assertRaises(NotImplementedError, self.dict.update()) 113 | 114 | def test_pop_works_correctly(self): 115 | self.dict['foo'] = 'bar' 116 | self.dict['buz'] = 'buffle' 117 | self.assertDictAndPersistantsHave(foo='bar', buz='buffle') 118 | 119 | self.assertEquals(self.dict.pop('buz', 'keynotfound'), 'buffle') 120 | self.assertDictAndPersistantsHave(foo='bar') 121 | 122 | self.assertEquals(self.dict.pop('junk', 'keynotfound'), 'keynotfound') 123 | self.assertDictAndPersistantsHave(foo='bar') 124 | 125 | self.assertEquals(self.dict.pop('foo'), 'bar') 126 | self.assertDictAndPersistantsHave() 127 | 128 | self.assertEquals(self.dict.pop('no_more_keys', 'default'), 'default') 129 | self.assertRaises(KeyError, self.dict.pop, 'no_more_keys') 130 | 131 | def test_get_works_correctly(self): 132 | self.dict['foo'] = 'bar' 133 | self.assertEquals('bar', self.dict.get('foo')) 134 | self.assertEquals('default', self.dict.get('junk', 'default')) 135 | self.assertEquals(None, self.dict.get('junk')) 136 | 137 | def test_get_does_not_remove_element(self): 138 | self.dict['foo'] = 'bar' 139 | self.assertEquals('bar', self.dict.get('foo')) 140 | self.assertEquals('bar', self.dict.get('foo')) 141 | 142 | def test_contains_works(self): 143 | self.assertFalse('foo' in self.dict) 144 | self.dict['foo'] = 'bar' 145 | self.assertTrue('foo' in self.dict) 146 | self.assertFalse('bar' in self.dict) 147 | 148 | def test_uses_custom_encoding_passed_in(self): 149 | class SevenEncoding(object): 150 | encode = staticmethod(lambda d: '7') 151 | decode = staticmethod(lambda d: d) 152 | 153 | sevens_dict = self.new_dict(encoding=SevenEncoding) 154 | sevens_dict['key'] = 'this is not a seven' 155 | self.assertEquals('7', sevens_dict.get('key')) 156 | 157 | 158 | class AutoSyncTrueTest(object): 159 | 160 | def test_does_not_update_self_until_persistats_have_updated(self): 161 | self.dict['foo'] = 'bar' 162 | 163 | with mock.patch(self.mockmeth('last_updated')) as last_updated: 164 | # Make it like the durables have never been updated 165 | last_updated.return_value = 0 166 | 167 | with mock.patch(self.mockmeth('durables')) as durables: 168 | # But the durables have been updated to a new value 169 | durables.return_value = dict(updated='durables') 170 | self.assertEquals(self.dict, dict(foo='bar')) 171 | 172 | # Change the last updated to a high number to expire the cache, 173 | # then fetch a new value by calling len() on the dict 174 | last_updated.return_value = 8000000000 175 | len(self.dict) 176 | self.assertEquals(self.dict, dict(updated='durables')) 177 | 178 | 179 | class AutoSyncFalseTest(object): 180 | 181 | def test_does_not_update_from_durables_on_read(self): 182 | # Add a key to the dict, which will sync with durables 183 | self.assertEquals(self.dict, dict()) 184 | self.dict['foo'] = 'bar' 185 | 186 | # Manually add a value not using the public API 187 | self.dict.persist('added', 'value') 188 | 189 | # And it should not be there 190 | self.assertEquals(self.dict, dict(foo='bar')) 191 | 192 | # Now sync and see that it's updated 193 | self.dict.sync() 194 | self.assertDictAndPersistantsHave(foo='bar', added='value') 195 | 196 | 197 | class RedisTest(object): 198 | 199 | def tearDown(self): 200 | self.dict.connection.flushdb() 201 | super(RedisTest, self).tearDown() 202 | 203 | def hget(self, key): 204 | return self.dict.connection.hget(self.keyspace, key) 205 | 206 | def test_instances_different_keyspaces_do_not_share_last_updated(self): 207 | self.dict['foo'] = 'bar' 208 | self.dict['bazzle'] = 'bungie' 209 | self.assertEquals(self.dict.last_updated(), 3) 210 | 211 | new_dict = self.new_dict(keyspace='another_one') 212 | self.assertNotEquals(self.dict.last_updated(), new_dict.last_updated()) 213 | 214 | 215 | class ModelDictTest(object): 216 | 217 | def tearDown(self): 218 | django.core.management.call_command('flush', interactive=False) 219 | self.dict.cache.clear() 220 | super(ModelDictTest, self).tearDown() 221 | 222 | def setUp(self): 223 | django.core.management.call_command('syncdb') 224 | super(ModelDictTest, self).setUp() 225 | 226 | @property 227 | def cache(self): 228 | return LocMemCache(self.keyspace, {}) 229 | 230 | 231 | class ZookeeperDictTest(object): 232 | 233 | namespace = '/durabledict/test' 234 | 235 | def set_event_when_updated(self, client, value, event): 236 | while client.last_updated() is not value: 237 | pass 238 | 239 | event.set() 240 | 241 | def new_client(self): 242 | client = KazooClient(hosts='zookeeper:2181') 243 | client.start() 244 | return client 245 | 246 | @contextmanager 247 | def wait_for_update_of(self, zkdict, value): 248 | event = threading.Event() 249 | args = (zkdict, value, event) 250 | 251 | thread.start_new_thread(self.set_event_when_updated, args) 252 | 253 | event.wait(timeout=5) 254 | actual = zkdict.last_updated() 255 | format = 'Gave up waiting for last_updated value of %s, last saw %s' 256 | 257 | self.assertEquals(actual, value, format % (actual, value)) 258 | 259 | yield 260 | 261 | def test_other_cluster_in_namespace_does_not_effect_main_one(self): 262 | other_dict = ZookeeperDict(keyspace='/durabledict/other', connection=self.new_client()) 263 | 264 | self.dict['foo'] = 'dict bar' 265 | self.dict['dictkey'] = 'dict' 266 | 267 | other_dict['foo'] = 'other' 268 | other_dict['otherdictkey'] = 'otherv' 269 | 270 | # This is "5" and not "3" because of a bug. When a ZKDict object has 271 | # __setattr__, it updates the last_updated value itself, PLUS the 272 | # ZKDict's child watch sees that change and also updates the 273 | # last_updated value as well. This isn't ideal and will get changed. 274 | with self.wait_for_update_of(other_dict, 5): 275 | self.assertEquals( 276 | self.dict, 277 | dict(foo='dict bar', dictkey='dict') 278 | ) 279 | self.assertEquals( 280 | other_dict, 281 | dict(foo='other', otherdictkey='otherv') 282 | ) 283 | 284 | def test_changes_by_one_dict_are_reflected_in_another(self): 285 | other_dict = ZookeeperDict(keyspace=self.namespace, connection=self.new_client()) 286 | 287 | self.assertEquals(other_dict, {}) 288 | 289 | self.dict['foo'] = 'bar' 290 | self.dict['baz'] = 'bub' 291 | 292 | with self.wait_for_update_of(other_dict, 3): 293 | self.assertEquals(other_dict['foo'], 'bar') 294 | self.assertEquals(other_dict['baz'], 'bub') 295 | 296 | self.dict['foo'] = 'changed' 297 | 298 | with self.wait_for_update_of(other_dict, 4): 299 | self.assertEquals(other_dict['foo'], 'changed') 300 | self.assertEquals(other_dict['baz'], 'bub') 301 | 302 | def test_raises_valueerror_for_keys_with_strings(self): 303 | self.assertRaises( 304 | ValueError, 305 | self.dict.__setitem__, 306 | 'with/slash', 307 | 'value' 308 | ) 309 | 310 | def test_starts_the_zk_client_if_not_already_started(self): 311 | client = mock.Mock(connected=False) 312 | 313 | ZookeeperDict(keyspace=self.namespace, connection=client) 314 | client.start.assert_called_once_with() 315 | 316 | client.start.reset_mock() 317 | client.connected = True 318 | ZookeeperDict(keyspace=self.namespace, connection=client) 319 | self.assertFalse(client.start.called) 320 | 321 | 322 | class TestRedisDict(BaseTest, AutoSyncTrueTest, RedisTest, unittest.TestCase): 323 | 324 | def new_dict(self, keyspace=None, **kwargs): 325 | return RedisDict(keyspace=(keyspace or self.keyspace), connection=Redis(host='redis'), **kwargs) 326 | 327 | def test_persist_saves_to_redis(self): 328 | self.assertFalse(self.hget('foo')) 329 | self.dict.persist('foo', 'bar') 330 | self.assertEquals(self.dict.encoding.decode(self.hget('foo')), 'bar') 331 | 332 | def test_depersist_removes_it_from_redis(self): 333 | self.dict['foo'] = 'bar' 334 | self.assertEquals(self.dict.encoding.decode(self.hget('foo')), 'bar') 335 | self.dict.depersist('foo') 336 | self.assertFalse(self.hget('foo')) 337 | 338 | def test_durables_returns_items_in_redis(self): 339 | self.dict.persist('foo', 'bar') 340 | self.dict.persist('baz', 'bang') 341 | 342 | new_dict = self.new_dict() 343 | 344 | self.assertEquals(new_dict.durables(), dict(foo='bar', baz='bang')) 345 | 346 | def test_last_updated_set_to_1_on_initialize(self): 347 | self.assertEquals(self.dict.last_updated(), 1) 348 | 349 | def test_persists_and_last_update_writes_are_atomic(self): 350 | with mock.patch('redis.Redis.incr') as tlo: 351 | tlo.side_effect = Exception('boom!') 352 | self.assertRaisesRegexp(Exception, 'boom', 353 | self.dict.persist, 'foo', 'bar') 354 | self.assertFalse(self.hget('foo')) 355 | 356 | def test_can_instantiate_without_keywords(self): 357 | RedisDict(self.keyspace, Redis(host='redis')) 358 | 359 | 360 | class TestModelDict(BaseTest, AutoSyncTrueTest, ModelDictTest, unittest.TestCase): 361 | 362 | def new_dict(self, **kwargs): 363 | return ModelDict(manager=Setting.objects, cache=self.cache, key_col='key', **kwargs) 364 | 365 | def test_can_be_constructed_with_return_instances(self): 366 | instance = ModelDict(manager=Setting.objects, cache=self.cache, return_instances='ri') 367 | self.assertEquals( 368 | instance.return_instances, 369 | 'ri' 370 | ) 371 | 372 | def test_persist_saves_model(self): 373 | self.dict.persist('foo', 'bar') 374 | self.assertEquals(self.dict['foo'], 'bar') 375 | 376 | def test_depersist_removes_model(self): 377 | self.dict.persist('foo', 'bar') 378 | self.assertTrue(self.dict['foo'], 'bar') 379 | self.dict.depersist('foo') 380 | self.assertRaises(Setting.DoesNotExist, Setting.objects.get, key='foo') 381 | 382 | def test_durables_returns_dict_of_models_in_db(self): 383 | self.dict.persist('foo', 'bar') 384 | self.dict.persist('buzz', 'bang') 385 | self.assertEquals(self.dict.durables(), dict(foo='bar', buzz='bang')) 386 | 387 | def test_last_updated_set_to_1_on_initialize(self): 388 | self.assertEquals(self.dict.last_updated(), 1) 389 | 390 | def test_setdefault_does_not_update_last_updated_if_key_exists(self): 391 | self.dict.persist('foo', 'bar') 392 | before = self.dict.last_updated() 393 | 394 | self.dict.setdefault('foo', 'notset') 395 | self.assertEquals(before, self.dict.last_updated()) 396 | 397 | def test_instances_true_returns_the_whole_object_at_they_key(self): 398 | self.dict.persist('foo', 'bar') 399 | self.dict.return_instances = True 400 | self.assertEquals(self.dict['foo'], Setting.objects.get(key='foo')) 401 | 402 | def test_touch_last_updated_inc_cache(self): 403 | self.dict.cache = mock.Mock() 404 | self.dict.touch_last_updated() 405 | self.dict.cache.incr.assert_called_once_with(self.dict.cache_key) 406 | 407 | def test_resets_last_update_if_value_is_deleted(self): 408 | self.dict.persist('foo', 'bar') 409 | self.assertEquals(self.dict['foo'], 'bar') 410 | 411 | self.dict.cache.delete(self.dict.cache_key) 412 | 413 | self.dict.persist('baz', 'fizzle') 414 | self.assertEquals(self.dict['foo'], 'bar') 415 | self.assertEquals(self.dict['baz'], 'fizzle') 416 | self.assertEquals( 417 | self.dict.cache.get(self.dict.cache_key), 418 | self.dict.LAST_UPDATED_MISSING_INCREMENT + 2 # for 2 updates 419 | ) 420 | 421 | 422 | class TestMemoryDict(BaseTest, AutoSyncTrueTest, unittest.TestCase): 423 | 424 | def new_dict(self, *args, **kwargs): 425 | return MemoryDict(*args, **kwargs) 426 | 427 | def test_does_not_pickle_objects_when_set(self): 428 | obj = object() 429 | self.dict['foo'] = obj 430 | 431 | self.assertEquals(self.dict.values(), [obj]) 432 | 433 | 434 | class TestZookeeperDict(BaseTest, ZookeeperDictTest, unittest.TestCase): 435 | 436 | def new_dict(self, **kwargs): 437 | client = KazooClient(hosts='zookeeper:2181') 438 | client.start() 439 | client.delete(self.namespace, recursive=True) 440 | return ZookeeperDict(keyspace=self.namespace, connection=client, **kwargs) 441 | 442 | 443 | 444 | 445 | class TestRedisDictManualSync(BaseTest, RedisTest, AutoSyncFalseTest, unittest.TestCase): 446 | 447 | def new_dict(self, keyspace=None, **kwargs): 448 | return RedisDict(keyspace=(keyspace or self.keyspace), connection=Redis(host='redis'), autosync=False, **kwargs) 449 | 450 | 451 | class TestModelDictManualSync(BaseTest, ModelDictTest, AutoSyncFalseTest, unittest.TestCase): 452 | 453 | def new_dict(self, **kwargs): 454 | return ModelDict(manager=Setting.objects, cache=self.cache, key_col='key', autosync=False, **kwargs) 455 | 456 | 457 | class TestZookeeperDictManualSync(BaseTest, ZookeeperDictTest, unittest.TestCase, ): 458 | 459 | def new_dict(self, **kwargs): 460 | client = KazooClient(hosts='zookeeper:2181') 461 | client.start() 462 | client.delete(self.namespace, recursive=True) 463 | return ZookeeperDict(keyspace=self.namespace, connection=client, autosync=False, **kwargs) 464 | -------------------------------------------------------------------------------- /tests/test_encoding.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | import unittest 4 | from mock import Mock 5 | 6 | from durabledict.encoding import ( 7 | NoOpEncoding, 8 | PickleEncoding, 9 | JSONEncoding, 10 | EncodingError, 11 | DecodingError, 12 | ) 13 | 14 | 15 | class EncodingTest(object): 16 | def cycle(self, data): 17 | return self.encoding.decode(self.encoding.encode(data)) 18 | 19 | def test_encodes_basic_objects(self): 20 | self.assertEqual(7, self.cycle(7)) 21 | self.assertEqual("seven", self.cycle("seven")) 22 | self.assertEqual([1, 2, 3], self.cycle([1, 2, 3])) 23 | # XXX: The JSONEncoding converts all keys to strings, so test with a 24 | # compatable dict here. 25 | self.assertEqual({"1": 2}, self.cycle({"1": 2})) 26 | 27 | def test_raises_encoding_and_decoding_errors(self): 28 | data = Mock(side_effect=KeyError('hi')) 29 | 30 | with self.assertRaises(EncodingError): 31 | self.encoding.encode(data) 32 | 33 | with self.assertRaises(DecodingError): 34 | self.encoding.decode(data) 35 | 36 | 37 | class NoOpEncodingTest(EncodingTest, unittest.TestCase): 38 | encoding = NoOpEncoding 39 | 40 | def test_raises_encoding_and_decoding_errors(self): 41 | pass 42 | 43 | 44 | class PickleEncodingTest(EncodingTest, unittest.TestCase): 45 | encoding = PickleEncoding 46 | 47 | 48 | class JSONEncodingTest(EncodingTest, unittest.TestCase): 49 | encoding = JSONEncoding 50 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls.defaults import * 2 | 3 | 4 | def dummy_view(request): 5 | from django.http import HttpResponse 6 | return HttpResponse() 7 | 8 | urlpatterns = patterns('', 9 | url(r'^$', dummy_view, name='durabledict-home'), 10 | ) 11 | --------------------------------------------------------------------------------