├── .gitignore ├── LICENSE ├── README.rst ├── featureflipper ├── __init__.py ├── admin.py ├── context_processors.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ ├── addfeature.py │ │ ├── disablefeature.py │ │ ├── dumpfeatures.py │ │ ├── enablefeature.py │ │ ├── features.py │ │ └── loadfeatures.py ├── media │ └── featureflipper │ │ └── placeholder.txt ├── middleware.py ├── models.py ├── signals.py ├── templatetags │ ├── __init__.py │ └── feature_tag.py ├── tests.py ├── urls.py └── views.py ├── featureflipper_example ├── __init__.py ├── features.json ├── manage.py ├── settings.py ├── templates │ └── featureflipper_example │ │ └── index.html ├── urls.py └── views.py ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.db 3 | local_settings.py 4 | media/ugc 5 | docs/_build/ 6 | src/ 7 | pip-log.txt 8 | media/js/*.r*.js 9 | media/css/*.r*.css 10 | *DS_Store 11 | *.egg-info 12 | *~ 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ====================== 2 | Django Feature Flipper 3 | ====================== 4 | 5 | django-feature-flipper helps flip features of your Django site on and 6 | off, in the database or per request or session, using URL parameters. 7 | 8 | THE SOFTWARE IS ALPHA. THE API IS CHANGING AND THERE ARE NO UNIT TESTS. 9 | 10 | This will help you can deploy code and schema changes for upcoming 11 | features but hide the features from your users until you're 12 | ready. This practice is commonly used in continuous deployment. 13 | 14 | The term "feature flipper" seems to have come from Flickr, as 15 | described in this often-cited blog post: 16 | 17 | http://code.flickr.com/blog/2009/12/02/flipping-out/ 18 | 19 | Feature flags or switches are becoming more commonly used, it seems. 20 | 21 | django-feature-flipper is in part inspired by that post, along with 22 | some of the other feature flippers available, including: 23 | 24 | - https://github.com/qype/feature_flipper (for Rails, by Florian Munz at Qype) 25 | - https://github.com/grillpanda/dolphin (for Rails, by Matt Johnson) 26 | - http://dhorrigan.com/turnstiles/ (for CodeIgniter, Dan Horrigan) 27 | - https://dev.launchpad.net/LEP/FeatureFlags (for Canonical's Launchpad) 28 | 29 | A few days after I first committed django-feature-flipper to github, 30 | David Cramer at Disqus has released the "gargoyle" plugin for Django, 31 | that offers overlapping functionality. That plugin requires "Nexus", 32 | their Django front-end admin replacement. 33 | 34 | - http://justcramer.com/2010/12/21/feature-switches-in-django-with-gargoyle/ 35 | - https://github.com/disqus/gargoyle 36 | 37 | The following post is an interview with Flickr's John Allspaw, author 38 | of "The Art of Capacity Planning: Scaling Web Resources." 39 | 40 | - http://highscalability.com/blog/2009/6/29/how-to-succeed-at-capacity-planning-without-really-trying-an.html 41 | 42 | Includes this quote, which covers feature flags being used to 43 | **disable** features to help "panic gracefully.": 44 | 45 | "Of course it's easier to do those things when you have easy config 46 | flags to turn things on or off, and a list to run through of what 47 | things are acceptable to serve stale and static. We currently have 48 | about 195 'features' we can turn off at Flickr in dire 49 | circumstances. And we've used those flags when we needed to." 50 | 51 | More on feature flags/flippers: 52 | 53 | - http://old.nabble.com/Feature-Flipper-to30400696.html 54 | - http://www.alandelevie.com/2010/05/19/feature-flippers-with-rails/ 55 | - http://engineering.qype.com/2010/06/03/how-we-work-flipping-features/ (also Florian Munz) 56 | - http://www.reddit.com/r/programming/comments/aehta/flickr_dont_branch/ 57 | 58 | Continuous deployment: 59 | 60 | - http://www.startuplessonslearned.com/2009/06/why-continuous-deployment.html 61 | - http://timothyfitz.wordpress.com/2009/02/10/continuous-deployment-at-imvu-doing-the-impossible-fifty-times-a-day/ 62 | - http://radar.oreilly.com/2009/03/continuous-deployment-5-eas.html 63 | - http://en.wikipedia.org/wiki/Lean_Startup 64 | 65 | 66 | Installation 67 | ============ 68 | 69 | #. Add the ``featureflipper`` directory to your Python path. 70 | 71 | This should work:: 72 | 73 | pip install -e git+https://github.com/tobych/django-feature-flipper.git@master#egg=django-feature-flipper 74 | 75 | #. Add ``featureflipper`` to your ``INSTALLED_APPS`` setting. 76 | 77 | #. Add ``featureflipper.context_processors.features`` to your 78 | ``TEMPLATE_CONTEXT_PROCESSORS`` setting. It doesn't matter where 79 | you put it in relation to existing entries. 80 | 81 | #. Add ``featureflipper.middleware.FeaturesMiddleware`` to your 82 | ``MIDDLEWARE_CLASSES`` setting. It doesn't matter where you put it 83 | in relation to existing entries. 84 | 85 | #. Optionally, add a settings.FEATURES_FILE, and set it to the 86 | location of a features file (see below) to load after each syncdb 87 | (or whenever you'd normally expect fixtures to be loaded). 88 | 89 | #. Run ``./manage.py syncdb`` to create the database table. 90 | 91 | 92 | Limitations 93 | =========== 94 | 95 | Feature status is currently kept in the database. This is 96 | inefficient. They should probably be in Memcached instead. 97 | 98 | There is, unforgivably, poor unit test coverage. 99 | 100 | 101 | What determines a feature's status 102 | ================================== 103 | 104 | A feature's status (enabled or disabled) is determined by, in order: 105 | 106 | #. The database: the value of the attribute ``enabled`` of the 107 | ``Feature`` table. You can edit this value using the Django admin 108 | application. 109 | 110 | #. The session: if a session entry ``feature_status_myfeature`` 111 | exists, the feature will be enabled if the value is ``enabled``, 112 | and disabled otherwise. The middleware will add this entry if the 113 | ``GET`` parameter ``session_enable_myfeature`` is included, as 114 | explained below. 115 | 116 | #. The request: if a GET parameter ``enabled_myfeature`` exists, the 117 | feature will enabled for this request, as explained below. 118 | 119 | 120 | Enabling and disabling features using URLs 121 | ========================================== 122 | 123 | Users with permission ``can_flip_with_url`` can turn features on and 124 | off using URL parameters. 125 | 126 | To enable a feature for the current request:: 127 | 128 | /mypage/?enable_myfeature 129 | 130 | To enable a feature for this request and the rest of a session:: 131 | 132 | /mypage/?session_enable_myfeature 133 | 134 | To clear all the features enabled in the session:: 135 | 136 | /mypage/?session_clear_features 137 | 138 | If you want to allow anonymous users to do this, see the section 139 | "Authorization for Anonymous Users" here: 140 | 141 | http://docs.djangoproject.com/en/dev/topics/auth/ 142 | 143 | Alternatively (since that looks painful) you can allow anyone to use 144 | URLs to flip features by setting 145 | FEATURE_FLIPPER_ANONYMOUS_URL_FLIPPING to True in your settings.py. 146 | 147 | 148 | How to use the features in templates 149 | ==================================== 150 | 151 | The application registers itself with Django's admin app so you can 152 | manage the ``Features``. Each feature has a ``name`` made up of just 153 | alphanumeric characters and hyphens that you can use in templates, 154 | views, URLs and elsewhere in your code. Each feature has a boolean 155 | ``enabled`` property, which is ``False`` (disabled) by default. The 156 | app also adds a few custom actions to the change list page so you can 157 | enable, disable and flip features there. 158 | 159 | Features also have a name and description, which aren't currently used 160 | anywhere but should help you keep track. 161 | 162 | The context processor adds ``features`` to the template context, which 163 | you can use like this:: 164 | 165 | {% if feature.search %} 166 |
...
167 | {% endif %} 168 | 169 | Here, ``search`` is the name of the feature. If the feature referenced 170 | doesn't exist, it is silently treated as disabled. 171 | 172 | To save you some typing, you can also use a new block tag:: 173 | 174 | {% load feature_tag %} 175 | 176 | {% feature login %} 177 | Login 178 | {% endfeature %} 179 | 180 | You can also do this:: 181 | 182 | {% feature profile %} 183 | ... will only be output if feature 'profile' is enabled ... 184 | {% disabled %} 185 | ... will only be output if the feature is disabled ... 186 | {% endfeature %} 187 | 188 | 189 | How to use the features in views 190 | ================================ 191 | 192 | The middleware adds ``features``, a dict subclass, to each request:: 193 | 194 | if request.features['search']: 195 | ... 196 | 197 | The middleware also adds ``features_panel`` to the request. This 198 | object provides more information about the state of each feature than 199 | ``features``. 200 | 201 | ``enabled('myfeature')`` returns True if myfeature is enabled. 202 | 203 | ``source('myfeature')`` returns a string indicating the source of the 204 | final status of the feature: 205 | 206 | - ``site``: site-wide, in the Feature instance itself 207 | - ``session``: in the session, set using a URL parameter 208 | - ``url``: per request, set using a URL parameter 209 | 210 | ``source('myfeature)`` will return another value if a featureflipper 211 | plugin is being used (see below). 212 | 213 | ``features`` and ``source`` are also available. They are demonstrated in the example application. 214 | 215 | 216 | Features file 217 | ============= 218 | 219 | To make sure you can easily keep features and their default settings 220 | under version control, you can load features from a file using the 221 | ``loadfeatures`` management command (below). If you add FEATURES_FILE 222 | to your settings, pointing to a file (typically features.json), 223 | features from this file will be loaded each time you do a syncdb. Note 224 | that any existing feature of the same name will be overwritten. 225 | 226 | The file needs to look like this:: 227 | 228 | [ 229 | { 230 | "name": "profile", 231 | "enabled": true, 232 | "description": "Allow the user to view and edit their profile." 233 | }, 234 | { 235 | "name": "search", 236 | "enabled": true, 237 | "description": "Shows the search box on most pages, and the larger one on the home page." 238 | } 239 | ] 240 | 241 | Note that for ``profile`` above, we're using the ``description`` field 242 | to describe the feature in general, whereas for ``search`` we're 243 | describing how and where that feature is make visible to the user. You 244 | might end up using a mix of these. 245 | 246 | 247 | Management commands 248 | =================== 249 | 250 | - ``./manage.py features``: List the features in the database, along 251 | with their status. 252 | 253 | - ``./manage.py addfeature``: Adds one or more features to the 254 | database (leaving them disabled). 255 | 256 | - ``./manage.py loadfeatures``: Loads features from a JSON file (as 257 | above), or from the features file defined in settings.FEATURES_FILE. 258 | 259 | - ``./manage.py dumpfeatures``: Outputs features from the database in 260 | the same JSON format (although the keys aren't in the same order as the 261 | example above). 262 | 263 | - ``./manage.py enablefeature``: Enables the named feature(s). 264 | 265 | - ``./manage.py disablefeature``: Disables the named feature(s). 266 | 267 | 268 | Signals 269 | ======= 270 | 271 | Signal featureflipper.signals.feature_defaulted is sent when a feature 272 | referred to in a template or view is being defaulted to disabled. This 273 | will happen if the feature is not in the database, and hasn't been 274 | enabled using URL parameters. 275 | 276 | The example project shows how this signal can be used, in ``views.py``. 277 | 278 | Note also that featureflipper uses Django's ``post_syncdb`` to load a 279 | features file when ``syncdb`` is run. The connection to the signal is 280 | made in ``featureflipper/management/__init.py__``. 281 | 282 | 283 | Using the example project included in the source 284 | ================================================ 285 | 286 | The source tree for django-feature-flipper includes an example project 287 | created using the "App Factory" described on a post_ on the Washington 288 | Times open source blog. 289 | 290 | .. _post: http://opensource.washingtontimes.com/blog/2010/nov/28/app-centric-django-development-part-2-app-factory/ 291 | 292 | The settings.py file stipulates a sqlite3 database, so you'll need 293 | sqlite3 to be installed on your system. The database will be created 294 | automatically as necessary. 295 | 296 | To try the example project:: 297 | 298 | cd example 299 | ./manage.py syncdb 300 | ./manage.py runserver 301 | 302 | Let syncdb help you create a superuser so you can use the admin to 303 | create your own features. If you forget this step you can always run 304 | the ``createsuperuser`` command to do this. Two features (``profile`` 305 | and ``search``) will be loaded from ``features.json`` when you do the 306 | ``syncdb``. These are referenced in the example template used on the 307 | home page. There's no link bank to the home page from the admin so 308 | you'll need to hack the URL or open the admin in a separate tab in 309 | your browser. 310 | 311 | 312 | Good practice 313 | ============= 314 | 315 | - Once you no longer need to flip a feature, remove the feature from 316 | the database and all the logic from your template and views. 317 | 318 | - If you decide to remove the feature itself from your application, 319 | don't leave unused template and view code around. Just delete it. If 320 | you later decide to resurect the feature, it'll always be there in 321 | your version control repository. 322 | 323 | 324 | Extending Feature Flipper 325 | ========================= 326 | 327 | The app includes a hook to allow you to add "feature providers" that 328 | provide the state of features. On each request, the feature states are 329 | collected in turn from any plugins found (the order they're called on 330 | is undefined), just after feature states are collected from the 331 | database. To add a plugin, you need to create a subclass of 332 | featureflipper.FeatureProvider, and make sure it gets compiled along 333 | with the rest of your application. 334 | 335 | The class attribute ``source`` must be a string. This string is what 336 | the middeware makes available in request.features_panel.source(). 337 | 338 | The static method ``features`` must return a (possibly empty) list of 339 | tuples. The first member is the name of the feature, and the second 340 | True if the feature is enabled, and False otherwise. The features 341 | returned need not be defined in a Feature instance in the database. 342 | 343 | For example:: 344 | 345 | from featureflipper import FeatureProvider 346 | class UserFeatures(FeatureProvider): 347 | source = 'user' 348 | @staticmethod 349 | def features(request): 350 | return [('feature1', False), ('feature2', True)] 351 | 352 | 353 | TODOs and BUGS 354 | ============== 355 | 356 | See: https://github.com/tobych/django-feature-flipper/issues 357 | -------------------------------------------------------------------------------- /featureflipper/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | django-feature-flipper 3 | """ 4 | 5 | __version_info__ = { 6 | 'major': 0, 7 | 'minor': 1, 8 | 'micro': 0, 9 | 'releaselevel': 'alpha', 10 | 'serial': 3 11 | } 12 | 13 | def get_version(): 14 | """ 15 | Return the formatted version information 16 | """ 17 | vers = ["%(major)i.%(minor)i" % __version_info__, ] 18 | 19 | if __version_info__['micro']: 20 | vers.append(".%(micro)i" % __version_info__) 21 | if __version_info__['releaselevel'] != 'final': 22 | vers.append('%(releaselevel)s%(serial)i' % __version_info__) 23 | return ''.join(vers) 24 | 25 | __version__ = get_version() 26 | 27 | 28 | # From http://martyalchin.com/2008/jan/10/simple-plugin-framework/ 29 | class PluginMount(type): 30 | def __init__(cls, name, bases, attrs): 31 | if not hasattr(cls, 'plugins'): 32 | # This branch only executes when processing the mount point itself. 33 | # So, since this is a new plugin type, not an implementation, this 34 | # class shouldn't be registered as a plugin. Instead, it sets up a 35 | # list where plugins can be registered later. 36 | cls.plugins = [] 37 | else: 38 | # This must be a plugin implementation, which should be registered. 39 | # Simply appending it to the list is all that's needed to keep 40 | # track of it later. 41 | cls.plugins.append(cls) 42 | 43 | class FeatureProvider(type): 44 | __metaclass__ = PluginMount 45 | -------------------------------------------------------------------------------- /featureflipper/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from featureflipper.models import Feature 4 | 5 | 6 | class FeatureAdmin(admin.ModelAdmin): 7 | list_display = ('name', 'description', 'status') 8 | 9 | def enable_features(self, request, queryset): 10 | for feature in queryset: 11 | feature.enable() 12 | feature.save() 13 | self.message_user(request, "Successfully enabled %d features." % len(queryset)) 14 | enable_features.short_description = "Enable selected features" 15 | 16 | def disable_features(self, request, queryset): 17 | for feature in queryset: 18 | feature.disable() 19 | feature.save() 20 | self.message_user(request, "Successfully disabled %d features." % len(queryset)) 21 | disable_features.short_description = "Disable selected features" 22 | 23 | def flip_features(self, request, queryset): 24 | for feature in queryset: 25 | feature.flip() 26 | feature.save() 27 | self.message_user(request, "Successfully flipped %d features." % len(queryset)) 28 | flip_features.short_description = "Flip selected features" 29 | 30 | actions = [enable_features, disable_features, flip_features] 31 | 32 | admin.site.register(Feature, FeatureAdmin) 33 | -------------------------------------------------------------------------------- /featureflipper/context_processors.py: -------------------------------------------------------------------------------- 1 | from featureflipper.models import Feature 2 | 3 | # Not sure if this needs to be thread-safe, as custom tags do 4 | 5 | 6 | def features(request): 7 | """ 8 | Returns context variables required by apps that use featureflipper. 9 | """ 10 | return { 11 | 'features': request.features 12 | } 13 | -------------------------------------------------------------------------------- /featureflipper/management/__init__.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.db.models.signals import post_syncdb 3 | from django.core.management import call_command 4 | 5 | 6 | import featureflipper.models as featureflipper_app 7 | from featureflipper.models import Feature 8 | 9 | 10 | def load_data(sender, **kwargs): 11 | # This doesn't respect syncdb's verbosity option 12 | call_command('loadfeatures', interactive=False) 13 | 14 | post_syncdb.connect(load_data, sender=featureflipper_app) 15 | -------------------------------------------------------------------------------- /featureflipper/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobych/django-feature-flipper/0a82db0b456ac3b2f58634c5b2b7af585fddc13c/featureflipper/management/commands/__init__.py -------------------------------------------------------------------------------- /featureflipper/management/commands/addfeature.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | 3 | from featureflipper.models import Feature 4 | 5 | 6 | class Command(BaseCommand): 7 | args = '[feature ...]' 8 | help = 'Adds the named features to the database, as disabled.' 9 | 10 | def handle(self, *features, **options): 11 | for name in features: 12 | try: 13 | feature = Feature.objects.get(name=name) 14 | except Feature.DoesNotExist: 15 | Feature.objects.create(name=name, enabled=False) 16 | print "Added feature %s" % name 17 | else: 18 | print "Feature %s already exists, and is %s" % (feature.name, feature.status) 19 | -------------------------------------------------------------------------------- /featureflipper/management/commands/disablefeature.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | 3 | from featureflipper.models import Feature 4 | 5 | 6 | class Command(BaseCommand): 7 | args = '[feature ...]' 8 | help = 'Disables the named features in the database.' 9 | 10 | def handle(self, *features, **options): 11 | for name in features: 12 | try: 13 | feature = Feature.objects.get(name=name) 14 | except Feature.DoesNotExist: 15 | print "Feature %s is not in the database." % name 16 | return 17 | else: 18 | if not feature.enabled: 19 | print "Feature %s is already disabled." % feature 20 | else: 21 | feature.disable() 22 | feature.save() 23 | print "Disabled feature %s." % feature 24 | -------------------------------------------------------------------------------- /featureflipper/management/commands/dumpfeatures.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | from django.utils import simplejson 3 | from django.conf import settings 4 | 5 | from featureflipper.models import Feature 6 | 7 | 8 | class Command(BaseCommand): 9 | 10 | def handle(self, *args, **options): 11 | help = 'Output the features in the database in JSON format.' 12 | 13 | features = Feature.objects.all().values('name', 'description', 'enabled') 14 | 15 | # This doesn't guarantee any particular ordering of keys in each dictionary 16 | # values() doesn't do that, and simplejson's sort_keys just uses alpha sort 17 | 18 | print simplejson.dumps(list(features), indent=2) 19 | -------------------------------------------------------------------------------- /featureflipper/management/commands/enablefeature.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | 3 | from featureflipper.models import Feature 4 | 5 | 6 | class Command(BaseCommand): 7 | args = '[feature ...]' 8 | help = 'Enables the named features in the database.' 9 | 10 | def handle(self, *features, **options): 11 | for name in features: 12 | try: 13 | feature = Feature.objects.get(name=name) 14 | except Feature.DoesNotExist: 15 | print "Feature %s is not in the database." % name 16 | return 17 | else: 18 | if feature.enabled: 19 | print "Feature %s is already enabled." % feature 20 | else: 21 | feature.enable() 22 | feature.save() 23 | print "Enabled feature %s." % feature 24 | -------------------------------------------------------------------------------- /featureflipper/management/commands/features.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | 3 | from featureflipper.models import Feature 4 | 5 | 6 | class Command(BaseCommand): 7 | args = '' 8 | help = 'Lists each feature defined in the database, and its status.' 9 | 10 | def handle(self, *args, **options): 11 | for feature in Feature.objects.all(): 12 | print "%s is %s" % (feature.name, feature.status) 13 | -------------------------------------------------------------------------------- /featureflipper/management/commands/loadfeatures.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | from django.utils import simplejson 3 | from django.conf import settings 4 | 5 | from featureflipper.models import Feature 6 | 7 | import os 8 | 9 | class Command(BaseCommand): 10 | 11 | def handle(self, file='', *args, **options): 12 | help = 'Loads the features from the file, or the default if none is provided.' 13 | if file == '': 14 | if hasattr(settings, 'FEATURE_FLIPPER_FEATURES_FILE'): 15 | file = settings.FEATURE_FLIPPER_FEATURES_FILE 16 | else: 17 | print "settings.FEATURE_FLIPPER_FEATURES_FILE is not set." 18 | return 19 | 20 | verbosity = int(options.get('verbosity', 1)) 21 | 22 | stream = open(file) 23 | features = simplejson.load(stream) 24 | for json_feature in features: 25 | name = json_feature['name'] 26 | try: 27 | feature = Feature.objects.get(name=name) 28 | except Feature.DoesNotExist: 29 | feature = Feature() 30 | feature.name = name 31 | feature.description = json_feature['description'] 32 | # Django will convert to a boolean for us 33 | feature.enabled = json_feature['enabled'] 34 | feature.save() 35 | 36 | if verbosity > 0: 37 | print "Loaded %d features." % len(features) 38 | -------------------------------------------------------------------------------- /featureflipper/media/featureflipper/placeholder.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobych/django-feature-flipper/0a82db0b456ac3b2f58634c5b2b7af585fddc13c/featureflipper/media/featureflipper/placeholder.txt -------------------------------------------------------------------------------- /featureflipper/middleware.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | from featureflipper.models import Feature 4 | from featureflipper.signals import feature_defaulted 5 | from featureflipper import FeatureProvider 6 | 7 | import re 8 | 9 | # Per-request flipper in URL 10 | _REQUEST_ENABLE = re.compile("^enable_(?P\w+)$") 11 | 12 | # Per-session flipper in URL 13 | _SESSION_ENABLE = re.compile("^session_enable_(?P\w+)$") 14 | 15 | # Flipper we put in the session 16 | _FEATURE_STATUS = re.compile("^feature_status_(?P\w+)$") 17 | 18 | 19 | class FeaturesMiddleware(object): 20 | 21 | def process_request(self, request): 22 | panel = FeaturesPanel() 23 | panel.add('site', list(self.features_from_database(request))) 24 | 25 | for plugin in FeatureProvider.plugins: 26 | panel.add(plugin.source, list(plugin.features(request))) 27 | 28 | if getattr(settings, 'FEATURE_FLIPPER_ANONYMOUS_URL_FLIPPING', False) or \ 29 | request.user.has_perm('featureflipper.can_flip_with_url'): 30 | if 'session_clear_features' in request.GET: 31 | self.clear_features_from_session(request.session) 32 | for feature in dict(self.session_features_from_url(request)): 33 | self.add_feature_to_session(request.session, feature) 34 | 35 | panel.add('session', list(self.features_from_session(request))) 36 | panel.add('url', list(self.features_from_url(request))) 37 | 38 | request.features = FeatureDict(panel.states()) 39 | request.features_panel = panel 40 | 41 | return None 42 | 43 | def features_from_database(self, request): 44 | """Provides an iterator yielding tuples (feature name, True/False)""" 45 | for feature in Feature.objects.all(): 46 | yield (feature.name, feature.enabled) 47 | 48 | def features_from_session(self, request): 49 | """Provides an iterator yielding tuples (feature name, True/False)""" 50 | for key in request.session.keys(): 51 | m = re.match(_FEATURE_STATUS, key) 52 | if m: 53 | feature = m.groupdict()['feature'] 54 | if request.session[key] == 'enabled': 55 | yield (feature, True) 56 | else: # We'll assume it's disabled 57 | yield (feature, False) 58 | 59 | def features_from_url(self, request): 60 | """Provides an iterator yielding tuples (feature name, True/False)""" 61 | for parameter in request.GET: 62 | m = re.match(_REQUEST_ENABLE, parameter) 63 | if m: 64 | yield (m.groupdict()['feature'], True) 65 | 66 | def session_features_from_url(self, request): 67 | """Provides an iterator yielding tuples (feature name, True/False)""" 68 | for parameter in request.GET: 69 | m = re.match(_SESSION_ENABLE, parameter) 70 | if m: 71 | feature = m.groupdict()['feature'] 72 | yield (feature, True) 73 | 74 | def add_feature_to_session(self, session, feature): 75 | session["feature_status_" + feature] = 'enabled' 76 | 77 | def clear_features_from_session(self, session): 78 | for key in session.keys(): 79 | if re.match(_FEATURE_STATUS, key): 80 | del session[key] 81 | 82 | 83 | class FeatureDict(dict): 84 | 85 | def __getitem__(self, key): 86 | if key in self: 87 | return dict.__getitem__(self, key) 88 | else: 89 | feature_defaulted.send(sender=self, feature=key) 90 | return False 91 | 92 | class FeaturesPanel(): 93 | 94 | def __init__(self): 95 | self.features = {} 96 | self.sources = [] 97 | 98 | def add(self, source, features): 99 | self.sources.append((source, features)) 100 | for (feature, enabled) in features: 101 | self.features[feature] = {'enabled': enabled, 'source': source} 102 | 103 | def enabled(self, name): 104 | return self.features[name]['enabled'] 105 | 106 | def source(self, name): 107 | return self.features[name]['source'] 108 | 109 | def states(self): 110 | # Returns a dictionary, mapping each feature name to its (final) state. 111 | return dict([(x, y['enabled']) for x, y in self.features.items()]) 112 | -------------------------------------------------------------------------------- /featureflipper/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Feature(models.Model): 5 | name = models.CharField(max_length=40, db_index=True, unique=True, 6 | help_text="Required. Used in templates (eg {% feature search %}) and URL parameters.") 7 | description = models.TextField(max_length=400, blank=True) 8 | enabled = models.BooleanField(default=False) 9 | 10 | def enable(self): 11 | self.enabled = True 12 | 13 | def disable(self): 14 | self.enabled = False 15 | 16 | def flip(self): 17 | self.enabled = not self.enabled 18 | 19 | def __unicode__(self): 20 | return self.name 21 | 22 | class Meta: 23 | ordering = ['name'] 24 | permissions = ( 25 | ("can_flip_with_url", "Can flip features using URL parameters"), 26 | ) 27 | 28 | @property 29 | def status(self): 30 | return "enabled" if self.enabled else "disabled" 31 | -------------------------------------------------------------------------------- /featureflipper/signals.py: -------------------------------------------------------------------------------- 1 | from django.dispatch import Signal 2 | 3 | feature_defaulted = Signal(providing_args=["feature"]) 4 | -------------------------------------------------------------------------------- /featureflipper/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobych/django-feature-flipper/0a82db0b456ac3b2f58634c5b2b7af585fddc13c/featureflipper/templatetags/__init__.py -------------------------------------------------------------------------------- /featureflipper/templatetags/feature_tag.py: -------------------------------------------------------------------------------- 1 | from django import template 2 | from django.template import NodeList 3 | 4 | from featureflipper.models import Feature 5 | 6 | 7 | register = template.Library() 8 | 9 | 10 | @register.tag 11 | def feature(parser, token): 12 | 13 | try: 14 | tag_name, feature = token.split_contents() 15 | except ValueError: 16 | raise template.TemplateSyntaxError, \ 17 | "%r tag requires a single argument" % token.contents.split()[0] 18 | 19 | end_tag = 'endfeature' 20 | nodelist_enabled = parser.parse(('disabled', end_tag)) 21 | token = parser.next_token() 22 | 23 | if token.contents == 'disabled': 24 | nodelist_disabled = parser.parse((end_tag,)) 25 | parser.delete_first_token() 26 | else: 27 | nodelist_disabled = NodeList() 28 | 29 | return FeatureNode(feature, nodelist_enabled, nodelist_disabled) 30 | 31 | 32 | class FeatureNode(template.Node): 33 | 34 | def __init__(self, feature, nodelist_enabled, nodelist_disabled): 35 | self.feature = feature 36 | self.nodelist_enabled = nodelist_enabled 37 | self.nodelist_disabled = nodelist_disabled 38 | 39 | def render(self, context): 40 | if context['features'][self.feature]: 41 | return self.nodelist_enabled.render(context) 42 | else: 43 | return self.nodelist_disabled.render(context) 44 | -------------------------------------------------------------------------------- /featureflipper/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.http import HttpRequest 3 | from django.test.client import Client 4 | from django.contrib.auth.models import User 5 | from django.contrib.auth.models import Permission 6 | 7 | from featureflipper.models import Feature 8 | from featureflipper.middleware import FeaturesMiddleware 9 | 10 | class featureflipperTest(TestCase): 11 | """ 12 | Tests for django-feature-flipper 13 | """ 14 | def test_something(self): 15 | feature = Feature.objects.create(name='fftestfeature') 16 | user = User.objects.create_user('fftestuser', '', 'password') 17 | 18 | c = Client() 19 | self.assertTrue(c.login(username='fftestuser', password='password')) 20 | 21 | response = c.get('/') 22 | self.assertTrue('features' in response.context) 23 | self.assertTrue('fftestfeature' in response.context['features']) 24 | self.assertFalse(response.context['features']['fftestfeature']) 25 | 26 | response = c.get('/?enable_fftestfeature') 27 | self.assertTrue(response.context['features']['fftestfeature']) 28 | 29 | response = c.get('/') 30 | self.assertFalse(response.context['features']['fftestfeature']) 31 | 32 | response = c.get('/?session_enable_fftestfeature') 33 | self.assertFalse(response.context['features']['fftestfeature']) 34 | 35 | perm = Permission.objects.get(codename='can_flip_with_url') 36 | user.user_permissions.add(perm) 37 | 38 | self.assertTrue(user.has_perm('featureflipper.can_flip_with_url')) 39 | response = c.get('/?session_enable_fftestfeature') 40 | 41 | self.assertTrue(response.context['features']['fftestfeature']) 42 | response = c.get('/') 43 | self.assertTrue(response.context['features']['fftestfeature']) 44 | 45 | response = c.get('/?session_clear_features') 46 | self.assertFalse(response.context['features']['fftestfeature']) 47 | 48 | feature.delete() 49 | user.delete() 50 | -------------------------------------------------------------------------------- /featureflipper/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls.defaults import * 2 | -------------------------------------------------------------------------------- /featureflipper/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render_to_response 2 | from django.http import HttpResponseRedirect, HttpResponseForbidden, Http404 3 | from django.template import RequestContext 4 | from django.utils.translation import ugettext, ugettext_lazy as _ 5 | -------------------------------------------------------------------------------- /featureflipper_example/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobych/django-feature-flipper/0a82db0b456ac3b2f58634c5b2b7af585fddc13c/featureflipper_example/__init__.py -------------------------------------------------------------------------------- /featureflipper_example/features.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "profile", 4 | "enabled": true, 5 | "description": "Allow the user to view and edit their profile." 6 | }, 7 | { 8 | "name": "search", 9 | "enabled": false, 10 | "description": "Shows the search box on most pages, and the larger one on the home page." 11 | } 12 | ] 13 | -------------------------------------------------------------------------------- /featureflipper_example/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from django.core.management import execute_manager 3 | try: 4 | import settings # Assumed to be in the same directory. 5 | except ImportError: 6 | import sys 7 | sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) 8 | sys.exit(1) 9 | 10 | if __name__ == "__main__": 11 | execute_manager(settings) 12 | -------------------------------------------------------------------------------- /featureflipper_example/settings.py: -------------------------------------------------------------------------------- 1 | # Django settings for the django-feature-flipper example project. 2 | 3 | DEBUG = True 4 | TEMPLATE_DEBUG = DEBUG 5 | import os, sys 6 | APP = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) 7 | PROJ_ROOT = os.path.abspath(os.path.dirname(__file__)) 8 | sys.path.append(APP) 9 | 10 | ADMINS = ( 11 | # ('Your Name', 'your_email@domain.com'), 12 | ) 13 | 14 | MANAGERS = ADMINS 15 | 16 | DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 17 | DATABASE_NAME = 'dev.db' # Or path to database file if using sqlite3. 18 | DATABASE_USER = '' # Not used with sqlite3. 19 | DATABASE_PASSWORD = '' # Not used with sqlite3. 20 | DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. 21 | DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. 22 | 23 | # Local time zone for this installation. Choices can be found here: 24 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 25 | # although not all choices may be available on all operating systems. 26 | # If running in a Windows environment this must be set to the same as your 27 | # system time zone. 28 | TIME_ZONE = 'America/Chicago' 29 | 30 | # Language code for this installation. All choices can be found here: 31 | # http://www.i18nguy.com/unicode/language-identifiers.html 32 | LANGUAGE_CODE = 'en-us' 33 | 34 | SITE_ID = 1 35 | 36 | # If you set this to False, Django will make some optimizations so as not 37 | # to load the internationalization machinery. 38 | USE_I18N = True 39 | 40 | # Absolute path to the directory that holds media. 41 | # Example: "/home/media/media.lawrence.com/" 42 | MEDIA_ROOT = os.path.abspath(os.path.join('media')) 43 | 44 | # URL that handles the media served from MEDIA_ROOT. Make sure to use a 45 | # trailing slash if there is a path component (optional in other cases). 46 | # Examples: "http://media.lawrence.com", "http://example.com/media/" 47 | MEDIA_URL = '/static/' 48 | 49 | # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a 50 | # trailing slash. 51 | # Examples: "http://foo.com/media/", "/media/". 52 | ADMIN_MEDIA_PREFIX = '/media/' 53 | 54 | # Make this unique, and don't share it with anybody. 55 | SECRET_KEY = 'g2_39yupn*6j4p*cg2%w643jiq-1n_annua*%i8+rq0dx9p=$n' 56 | 57 | # List of callables that know how to import templates from various sources. 58 | TEMPLATE_LOADERS = ( 59 | 'django.template.loaders.filesystem.load_template_source', 60 | 'django.template.loaders.app_directories.load_template_source', 61 | # 'django.template.loaders.eggs.load_template_source', 62 | ) 63 | 64 | TEMPLATE_CONTEXT_PROCESSORS = ( 65 | 'django.contrib.auth.context_processors.auth', 66 | 'featureflipper.context_processors.features', 67 | ) 68 | 69 | MIDDLEWARE_CLASSES = ( 70 | 'django.middleware.common.CommonMiddleware', 71 | 'django.contrib.sessions.middleware.SessionMiddleware', 72 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 73 | 'featureflipper.middleware.FeaturesMiddleware', 74 | ) 75 | 76 | ROOT_URLCONF = 'featureflipper_example.urls' 77 | 78 | TEMPLATE_DIRS = ( 79 | # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 80 | # Always use forward slashes, even on Windows. 81 | # Don't forget to use absolute paths, not relative paths. 82 | os.path.abspath(os.path.dirname(__file__)) + "/templates/", 83 | ) 84 | 85 | FEATURE_FLIPPER_FEATURES_FILE = os.path.abspath(os.path.dirname(__file__)) + "/features.json" 86 | FEATURE_FLIPPER_ANONYMOUS_URL_FLIPPING = False 87 | 88 | INSTALLED_APPS = ( 89 | 'django.contrib.admin', 90 | 'django.contrib.auth', 91 | 'django.contrib.contenttypes', 92 | 'django.contrib.sessions', 93 | 'django.contrib.sites', 94 | 'featureflipper' 95 | ) 96 | -------------------------------------------------------------------------------- /featureflipper_example/templates/featureflipper_example/index.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | django-feature-flipper example 8 | 9 | 10 | 11 |

12 | {% if user.is_authenticated %} 13 | {{ user }} Logout 14 | {% else %} 15 | Login 16 | {% endif %} 17 |

18 | 19 |

django-feature-flipper example

20 | 21 |

Permissions

22 | 23 | {% if perms.featureflipper.can_flip_with_url %} 24 |

You have permission to flip features using URL parameters (see below).

25 | {% else %} 26 |

You don't have permission to flip features using URL parameters.

27 | {% endif %} 28 | 29 |

Using the 'features' context variable

30 | 31 |

32 | {% if features.profile %} 33 | Profile is enabled 34 | {% else %} 35 | Profile is disabled 36 | {% endif %} 37 |
38 | Search is {% if features.search %}enabled{% else %}disabled{% endif %} 39 |
40 | Unknown is {{ features.unknown|yesno:"enabled,disabled" }} 41 |

42 | 43 |

Using the 'feature' tag

44 | 45 | {% load feature_tag %} 46 | 47 |

48 | {% feature profile %}Profile is enabled{% disabled %}Profile is disabled{% endfeature %}
49 | {% feature search %}Search is enabled{% disabled %}Search is disabled{% endfeature %}
50 | {% feature unknown %}Unknown is enabled{% disabled %}Unknown is disabled{% endfeature %} 51 |

52 | 53 |

Feature.objects.all

54 | 55 | {% for feature in feature_list %} 56 |

{{ feature }}: {{ feature.description }}

57 | {% endfor %} 58 | 59 |

request.features_panel

60 | 61 |

All known features, their final status, and the source of that final status.

62 | 63 | 64 | 65 | {% for name, details in features_panel.features.items %} 66 | 67 | {% endfor %} 68 |
FeatureEnabledSource
{{ name }}{{ details.enabled|yesno }}{{ details.source }}
69 | 70 |

Using GET parameters to flip features

71 | 72 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /featureflipper_example/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls.defaults import * 2 | from django.conf import settings 3 | from django.contrib import admin 4 | 5 | admin.autodiscover() 6 | 7 | urlpatterns = patterns('', 8 | (r'^admin/', include(admin.site.urls)), 9 | (r'^$', 'featureflipper_example.views.index'), 10 | ) 11 | -------------------------------------------------------------------------------- /featureflipper_example/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render_to_response 2 | from django.template import RequestContext 3 | 4 | from featureflipper.models import Feature 5 | from featureflipper.signals import feature_defaulted 6 | 7 | 8 | # We use the feature_defaulted signal to print a simple message 9 | # warning that a feature has been defaulted to disabled. You might 10 | # instead raise an exception here (to help avoid bugs in templates), 11 | # or add the feature to the database. 12 | 13 | def my_callback(sender, **kwargs): 14 | print "Feature '%s' defaulted!" % kwargs['feature'] 15 | 16 | # Uncomment the following line to enable this: 17 | # feature_defaulted.connect(my_callback) 18 | 19 | 20 | def index(request): 21 | # We'll include all the features, just so we can show all the details in the page 22 | feature_list = Feature.objects.all() 23 | # Below, we'll also include the features_panel in the context. 24 | # 'features' will already be added to the context by the middleware. 25 | return render_to_response('featureflipper_example/index.html', 26 | {'features_panel': request.features_panel, 'feature_list': feature_list}, 27 | context_instance=RequestContext(request)) 28 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobych/django-feature-flipper/0a82db0b456ac3b2f58634c5b2b7af585fddc13c/requirements.txt -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup, find_packages 3 | 4 | def read_file(filename): 5 | """Read a file into a string""" 6 | path = os.path.abspath(os.path.dirname(__file__)) 7 | filepath = os.path.join(path, filename) 8 | try: 9 | return open(filepath).read() 10 | except IOError: 11 | return '' 12 | 13 | # Use the docstring of the __init__ file to be the description 14 | DESC = " ".join(__import__('featureflipper').__doc__.splitlines()).strip() 15 | 16 | setup( 17 | name = "django-feature-flipper", 18 | version = __import__('featureflipper').get_version().replace(' ', '-'), 19 | url = '', 20 | author = 'tobych', 21 | author_email = '', 22 | description = DESC, 23 | long_description = read_file('README'), 24 | packages = find_packages(), 25 | include_package_data = True, 26 | install_requires=read_file('requirements.txt'), 27 | classifiers = [ 28 | 'License :: OSI Approved :: Apache Software License', 29 | 'Framework :: Django', 30 | ], 31 | ) 32 | --------------------------------------------------------------------------------