コード例 #1
0
ファイル: test_sites.py プロジェクト: evilkost/django-waffle
    def test_sample_inactive_all_sites_override(self):
        name = 'mysample'
        Sample.objects.create(name=name, percent='0.0', site=self.site1)
        self.assertFalse(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.sample_is_active(get(), name))
コード例 #2
0
ファイル: test_sites.py プロジェクト: webus/django-waffle
    def test_sample_site_default(self):
        name = "sample"
        sample = Sample.objects.create(name=name, percent="100.0")  # no site given

        self.assertTrue(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.sample_is_active(get(), name))
コード例 #3
0
ファイル: test_sites.py プロジェクト: webus/django-waffle
    def test_sample_by_site(self):
        name = "sample"
        sample1 = Sample.objects.create(name=name, percent="100.0", site=self.site1)
        sample2 = Sample.objects.create(name=name, percent="0.0", site=self.site2)

        self.assertTrue(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.sample_is_active(get(), name))
コード例 #4
0
ファイル: test_testutils.py プロジェクト: webus/django-waffle
    def test_sample_did_not_exist(self):
        assert not Sample.objects.filter(name="foo").exists()

        with override_sample("foo", active=True):
            assert waffle.sample_is_active(req(), "foo")

        with override_sample("foo", active=False):
            assert not waffle.sample_is_active(req(), "foo")

        assert not Sample.objects.filter(name="foo").exists()
コード例 #5
0
ファイル: test_testutils.py プロジェクト: webus/django-waffle
    def test_sample_existed_and_was_50(self):
        Sample.objects.create(name="foo", percent="50.0")

        with override_sample("foo", active=True):
            assert waffle.sample_is_active(req(), "foo")

        with override_sample("foo", active=False):
            assert not waffle.sample_is_active("foo")

        self.assertEquals(Decimal("50.0"), Sample.objects.get(name="foo").percent)
コード例 #6
0
    def test_sample_did_not_exist(self):
        assert not Sample.objects.filter(name='foo').exists()

        with override_sample('foo', active=True):
            assert waffle.sample_is_active('foo')

        with override_sample('foo', active=False):
            assert not waffle.sample_is_active('foo')

        assert not Sample.objects.filter(name='foo').exists()
コード例 #7
0
    def test_cache_is_flushed_by_testutils_even_in_transaction(self):
        Sample.objects.create(name='foo', percent='100.0')

        with transaction.atomic():
            with override_sample('foo', active=True):
                assert waffle.sample_is_active('foo')

            with override_sample('foo', active=False):
                assert not waffle.sample_is_active('foo')

        assert waffle.sample_is_active('foo')
コード例 #8
0
    def test_sample_existed_and_was_50(self):
        Sample.objects.create(name='foo', percent='50.0')

        with override_sample('foo', active=True):
            assert waffle.sample_is_active('foo')

        with override_sample('foo', active=False):
            assert not waffle.sample_is_active('foo')

        self.assertEquals(Decimal('50.0'),
                          Sample.objects.get(name='foo').percent)
コード例 #9
0
ファイル: test_waffle.py プロジェクト: koliber/django-waffle
    def test_read_from_write_db(self):
        sample = Sample.objects.create(name='sample', percent='100.0')

        # By default, sample_is_active should hit whatever it configured as the
        # read DB (so values will be stale if replication is lagged).
        assert not waffle.sample_is_active(sample.name)

        with override_settings(WAFFLE_READ_FROM_WRITE_DB=True):
            # Save the sample again to flush the cache.
            sample.save()

            # The next read should now be directed to the write DB, ensuring
            # the cache and DB are in sync.
            assert waffle.sample_is_active(sample.name)
コード例 #10
0
ファイル: views.py プロジェクト: gurumukhi/zamboni
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ("blocked-uri", "violated-directive", "original-policy")

    if not waffle.sample_is_active("csp-store-reports"):
        return HttpResponse()

    try:
        v = json.loads(request.body)["csp-report"]
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta["PATH_INFO"] = v.get("document-uri", meta["PATH_INFO"])
        v = [(k, v[k]) for k in report if k in v]
        log_cef(
            "CSPViolation",
            5,
            meta,
            username=request.user,
            signature="CSPREPORT",
            msg="A client reported a CSP violation",
            cs6=v,
            cs6Label="ContentPolicy",
        )
    except (KeyError, ValueError), e:
        log.debug("Exception in CSP report: %s" % e, exc_info=True)
        return HttpResponseBadRequest()
コード例 #11
0
ファイル: views.py プロジェクト: LucianU/zamboni
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ("blocked-uri", "violated-directive", "original-policy")

    if not waffle.sample_is_active("csp-store-reports"):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)["csp-report"]
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report
        # so we need to modify the meta before we pass in to the logger
        meta = request.META.copy()
        method, url = v["request"].split(" ", 1)
        meta.update({"REQUEST_METHOD": method, "PATH_INFO": url})
        v = [(k, v[k]) for k in report if k in v]
        log_cef(
            "CSP Violation",
            5,
            meta,
            username=request.user,
            signature="CSPREPORT",
            msg="A client reported a CSP violation",
            cs7=v,
            cs7Label="ContentPolicy",
        )
    except Exception, e:
        log.debug("Exception in CSP report: %s" % e, exc_info=True)
        return HttpResponseBadRequest()
コード例 #12
0
ファイル: views.py プロジェクト: vail130/django-waffle
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(FLAGS_ALL_CACHE_KEY))
    if not flags:
        flags = Flag.objects.values_list("name", flat=True)
        cache.add(keyfmt(FLAGS_ALL_CACHE_KEY), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(SWITCHES_ALL_CACHE_KEY))
    if not switches:
        switches = Switch.objects.values_list("name", "active")
        cache.add(keyfmt(SWITCHES_ALL_CACHE_KEY), switches)

    samples = cache.get(keyfmt(SAMPLES_ALL_CACHE_KEY))
    if not samples:
        samples = Sample.objects.values_list("name", flat=True)
        cache.add(keyfmt(SAMPLES_ALL_CACHE_KEY), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    flag_default = getattr(settings, "WAFFLE_FLAG_DEFAULT", False)
    switch_default = getattr(settings, "WAFFLE_SWITCH_DEFAULT", False)
    sample_default = getattr(settings, "WAFFLE_SAMPLE_DEFAULT", False)

    return loader.render_to_string(
        "waffle/waffle.js",
        {
            "flags": flag_values,
            "switches": switches,
            "samples": sample_values,
            "flag_default": flag_default,
            "switch_default": switch_default,
            "sample_default": sample_default,
        },
    )
コード例 #13
0
ファイル: views.py プロジェクト: DjangoBD/django-waffle
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(get_setting('ALL_FLAGS_CACHE_KEY')))
    if flags is None:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(get_setting('ALL_FLAGS_CACHE_KEY')), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')))
    if switches is None:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')), switches)

    samples = cache.get(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')))
    if samples is None:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    return loader.render_to_string('waffle/waffle.js', {
        'flags': flag_values,
        'switches': switches,
        'samples': sample_values,
        'flag_default': get_setting('FLAG_DEFAULT'),
        'switch_default': get_setting('SWITCH_DEFAULT'),
        'sample_default': get_setting('SAMPLE_DEFAULT'),
    })
コード例 #14
0
ファイル: views.py プロジェクト: TwigWorld/django-waffle
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(FLAGS_ALL_CACHE_KEY))
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(FLAGS_ALL_CACHE_KEY), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(SWITCHES_ALL_CACHE_KEY))
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(SWITCHES_ALL_CACHE_KEY), switches)

    samples = cache.get(keyfmt(SAMPLES_ALL_CACHE_KEY))
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(SAMPLES_ALL_CACHE_KEY), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    flag_default = getattr(settings, 'WAFFLE_FLAG_DEFAULT', False)
    switch_default = getattr(settings, 'WAFFLE_SWITCH_DEFAULT', False)
    sample_default = getattr(settings, 'WAFFLE_SAMPLE_DEFAULT', False)

    return loader.render_to_string('waffle/waffle.js',
                              {
                                'flags': flag_values,
                                'switches': switches,
                                'samples': sample_values,
                                'flag_default': flag_default,
                                'switch_default': switch_default,
                                'sample_default': sample_default,
                              })
コード例 #15
0
ファイル: views.py プロジェクト: Kami/django-waffle
def wafflejs(request):
    flags = cache.get(keyfmt(FLAGS_ALL_CACHE_KEY))
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(FLAGS_ALL_CACHE_KEY), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(SWITCHES_ALL_CACHE_KEY))
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(SWITCHES_ALL_CACHE_KEY), switches)

    samples = cache.get(keyfmt(SAMPLES_ALL_CACHE_KEY))
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(SAMPLES_ALL_CACHE_KEY), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    flag_default = getattr(settings, 'WAFFLE_FLAG_DEFAULT', False)
    switch_default = getattr(settings, 'WAFFLE_SWITCH_DEFAULT', False)
    sample_default = getattr(settings, 'WAFFLE_SAMPLE_DEFAULT', False)

    return render_to_response('waffle/waffle.js',
                              {
                                'flags': flag_values,
                                'switches': switches,
                                'samples': sample_values,
                                'flag_default': flag_default,
                                'switch_default': switch_default,
                                'sample_default': sample_default,
                              },
                              mimetype='application/x-javascript')
コード例 #16
0
ファイル: views.py プロジェクト: makielab/django-waffle
def wafflejs(request):
    flag_values = [(f, flag_is_active(request, f)) for f in get_all_flag_names()]
    sample_values = [(s, sample_is_active(s)) for s in get_all_sample_names()]

    return render_to_response('waffle/waffle.js', {'flags': flag_values,
                                                   'switches': get_all_switch_tuples(),
                                                   'samples': sample_values},
                              mimetype='application/x-javascript')
コード例 #17
0
ファイル: signing.py プロジェクト: iamVP7/addons-server
def call_signing(file_obj):
    """Get the jar signature and send it to the signing server to be signed."""
    log.debug('Calling autograph service: {0}'.format(
        settings.AUTOGRAPH_CONFIG['server_url']))

    if waffle.sample_is_active('activate-autograph-file-signing'):
        return autograph_sign_file(file_obj)

    return autograph_sign_data(file_obj)
コード例 #18
0
ファイル: test_waffle.py プロジェクト: jsocol/django-waffle
    def assert_sample_dynamically_created_with_value(self, is_active, expected_value):
        SAMPLE_NAME = 'my_dynamically_created_sample'

        assert Sample.objects.count() == 0
        assert is_active == waffle.sample_is_active(SAMPLE_NAME)
        assert Sample.objects.count() == 1

        sample = Sample.objects.get(name=SAMPLE_NAME)

        assert sample.name == SAMPLE_NAME
        assert sample.percent == expected_value
コード例 #19
0
ファイル: test_waffle.py プロジェクト: makielab/django-waffle
    def test_active_signal(self):
        sample = Sample.objects.create(name='sample', percent='100.0')

        def handler(sender, **kwargs):
            self.evaluated = kwargs['active']
        try:
            sample_evaluated.connect(handler)
            assert waffle.sample_is_active(sample.name)
            assert self.evaluated
        finally:
            sample_evaluated.disconnect(handler)
コード例 #20
0
ファイル: views.py プロジェクト: Osmose/olympia
def search_suggestions(request):
    if waffle.sample_is_active('autosuggest-throttle'):
        return HttpResponse(status=503)
    cat = request.GET.get('cat', 'all')
    suggesterClass = {
        'all': AddonSuggestionsAjax,
        'themes': PersonaSuggestionsAjax,
    }.get(cat, AddonSuggestionsAjax)
    items = suggesterClass(request, ratings=True).items
    for s in items:
        s['rating'] = float(s['rating'])
    return {'suggestions': items}
コード例 #21
0
ファイル: views.py プロジェクト: ricardodani/zamboni
def recommendations(request, version, platform, limit=9):
    """
    Figure out recommended add-ons for an anonymous user based on POSTed guids.

    POST body looks like {"guids": [...]} with an optional "token" key if
    they've been here before.
    """
    try:
        POST = json.loads(request.raw_post_data)
        guids = POST['guids']
    except (ValueError, TypeError, KeyError):
        # Errors: invalid json, didn't get a dict, didn't find "guids".
        return http.HttpResponseBadRequest()

    addon_ids = get_addon_ids(guids)
    index = Collection.make_index(addon_ids)

    ids, recs = Collection.get_recs_from_ids(addon_ids, request.APP, version)
    recs = _recommendations(request, version, platform, limit,
                            index, ids, recs)

    # We're only storing a percentage of the collections we see because the db
    # can't keep up with 100%.
    if not waffle.sample_is_active('disco-pane-store-collections'):
        return recs

    # Users have a token2 if they've been here before. The token matches
    # addon_index in their SyncedCollection.
    if 'token2' in POST:
        token = POST['token2']
        if token == index:
            # We've seen them before and their add-ons have not changed.
            return recs
        elif token != index:
            # We've seen them before and their add-ons changed. Remove the
            # reference to their old synced collection.
            (SyncedCollection.objects.filter(addon_index=index)
             .update(count=F('count') - 1))

    # Try to create the SyncedCollection. There's a unique constraint on
    # addon_index so it will fail if this addon_index already exists. If we
    # checked for existence first and then created a collection there would
    # be a race condition between multiple users with the same addon_index.
    try:
        c = SyncedCollection.objects.create(addon_index=index, count=1)
        c.set_addons(addon_ids)
    except IntegrityError:
        try:
            (SyncedCollection.objects.filter(addon_index=index)
             .update(count=F('count') + 1))
        except Exception, e:
            log.error(u'Could not count++ "%s" (%s).' % (index, e))
コード例 #22
0
def sample(parser, token):
    try:
        tag, sample_name = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, \
              "%r tag requires an argument" % token.contents.split()[0]

    sample_name = sample_name.strip('\'"')
    condition = lambda r, n: sample_is_active(n)

    nodelist_true = parser.parse(('else', 'endsample'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endsample',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return WaffleNode(nodelist_true, nodelist_false, condition, sample_name)
コード例 #23
0
ファイル: mixins.py プロジェクト: arbrandes/edx-ecommerce
    def handle_successful_order(self, order):
        """Send a signal so that receivers can perform relevant tasks (e.g., fulfill the order)."""
        audit_log(
            'order_placed',
            amount=order.total_excl_tax,
            basket_id=order.basket.id,
            currency=order.currency,
            order_number=order.number,
            user_id=order.user.id
        )

        if waffle.sample_is_active('async_order_fulfillment'):
            # Always commit transactions before sending tasks depending on state from the current transaction!
            # There's potential for a race condition here if the task starts executing before the active
            # transaction has been committed; the necessary order doesn't exist in the database yet.
            # See http://celery.readthedocs.org/en/latest/userguide/tasks.html#database-transactions.
            fulfill_order.delay(order.number)
        else:
            post_checkout.send(sender=self, order=order)

        return order
コード例 #24
0
ファイル: views.py プロジェクト: bhavyaj/zamboni
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.body)['csp-report']
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta['PATH_INFO'] = v.get('document-uri', meta['PATH_INFO'])
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSP Violation', 5, meta, username=request.user,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs6=v, cs6Label='ContentPolicy')
    except (KeyError, ValueError), e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
コード例 #25
0
ファイル: views.py プロジェクト: MechanisM/django-waffle
def wafflejs(request):
    flags = cache.get(FLAGS_ALL_CACHE_KEY)
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(FLAGS_ALL_CACHE_KEY, flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(SWITCHES_ALL_CACHE_KEY)
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(SWITCHES_ALL_CACHE_KEY, switches)

    samples = cache.get(SAMPLES_ALL_CACHE_KEY)
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(SAMPLES_ALL_CACHE_KEY, samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]
    return render_to_response('waffle/waffle.js', {'flags': flag_values,
                                                   'switches': switches,
                                                   'samples': sample_values},
                              mimetype='application/x-javascript')
コード例 #26
0
ファイル: views.py プロジェクト: CenterForOpenScience/osf.io
def root(request, format=None, **kwargs):
    """
    The documentation for the Open Science Framework API can be found at [developer.osf.io](https://developer.osf.io).
    The contents of this endpoint are variable and subject to change without notification.
    """
    if request.user and not request.user.is_anonymous:
        user = request.user
        current_user = UserSerializer(user, context={'request': request}).data
    else:
        current_user = None

    flags = [name for name in Flag.objects.values_list('name', flat=True) if flag_is_active(request, name)]
    samples = [name for name in Sample.objects.values_list('name', flat=True) if sample_is_active(name)]
    switches = list(Switch.objects.filter(active=True).values_list('name', flat=True))

    kwargs = request.parser_context['kwargs']
    return_val = {
        'meta': {
            'message': 'Welcome to the OSF API.',
            'version': request.version,
            'current_user': current_user,
            'active_flags': flags + samples + switches,
        },
        'links': {
            'nodes': utils.absolute_reverse('nodes:node-list', kwargs=kwargs),
            'users': utils.absolute_reverse('users:user-list', kwargs=kwargs),
            'collections': utils.absolute_reverse('collections:collection-list', kwargs=kwargs),
            'registrations': utils.absolute_reverse('registrations:registration-list', kwargs=kwargs),
            'institutions': utils.absolute_reverse('institutions:institution-list', kwargs=kwargs),
            'licenses': utils.absolute_reverse('licenses:license-list', kwargs=kwargs),
            'schemas': utils.absolute_reverse('schemas:registration-schema-list', kwargs=kwargs),
            'addons': utils.absolute_reverse('addons:addon-list', kwargs=kwargs),
        },
    }

    if utils.has_admin_scope(request):
        return_val['meta']['admin'] = True

    return Response(return_val)
コード例 #27
0
ファイル: views.py プロジェクト: jbuck/zamboni
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)['csp-report']
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report
        # so we need to modify the meta before we pass in to the logger
        meta = request.META.copy()
        method, url = v['request'].split(' ', 1)
        meta.update({'REQUEST_METHOD': method, 'PATH_INFO': url})
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSP Violation', 5, meta, username=request.user,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs7=v, cs7Label='ContentPolicy')
    except Exception, e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
コード例 #28
0
ファイル: views.py プロジェクト: MechanisM/zamboni
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)['csp-report']
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report.
        meta = request.META.copy()
        method, url = v['request'].split(' ', 1)
        meta.update({'REQUEST_METHOD': method, 'PATH_INFO': url})
        v = [(k, v[k]) for k in report if k in v]
        # This requires you to use the cef.formatter to get something nice out.
        csp_log.warning('Violation', dict(environ=meta,
                                          product='addons',
                                          username=request.user,
                                          data=v))
    except Exception:
        return HttpResponseBadRequest()

    return HttpResponse()
コード例 #29
0
ファイル: test_waffle.py プロジェクト: ntoll/django-waffle
 def test_undefined_default(self):
     assert waffle.sample_is_active('foo')
コード例 #30
0
ファイル: test_waffle.py プロジェクト: ntoll/django-waffle
 def test_undefined(self):
     assert not waffle.sample_is_active('foo')