django.core.cache.cache.clear

Here are the examples of the python api django.core.cache.cache.clear taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

140 Examples 7

3 Source : admin.py
with GNU General Public License v3.0
from ajslater

    def _on_change(self, _, created=False):
        """Events for when the library has changed."""
        cache.clear()
        tasks = (BroadcastNotifierTask("LIBRARY_CHANGED"), WatchdogSyncTask())
        task = DelayedTasks(2, tasks)
        LIBRARIAN_QUEUE.put(task)

    def save_model(self, request, obj, form, change):

3 Source : admin.py
with GNU General Public License v3.0
from ajslater

    def delete_model(self, request, obj):
        """Stop watching on delete."""
        pks = set([obj.pk])
        LIBRARIAN_QUEUE.put(PurgeComicCoversLibrariesTask(pks))
        super().delete_model(request, obj)
        cache.clear()
        self._on_change(None)

    def delete_queryset(self, request, queryset):

3 Source : admin.py
with GNU General Public License v3.0
from ajslater

    def delete_queryset(self, request, queryset):
        """Bulk delete."""
        pks = set(queryset.values_list("pk", flat=True))
        LIBRARIAN_QUEUE.put(PurgeComicCoversLibrariesTask(pks))
        super().delete_queryset(request, queryset)
        cache.clear()
        self._on_change(None)

    def save_formset(self, request, form, formset, change):

3 Source : lifespan.py
with GNU General Public License v3.0
from ajslater

def codex_startup():
    """Initialize the database and start the daemons."""
    ensure_superuser()
    init_admin_flags()
    unset_update_in_progress()
    cache.clear()
    force_darwin_multiprocessing_fork()

    Notifier.startup()
    LibrarianDaemon.startup()


def codex_shutdown():

3 Source : signals.py
with GNU General Public License v3.0
from ajslater

def _user_group_change(action, instance, pk_set, model, **kwargs):  # noqa: F841
    """Clear cache and send update signals when groups change."""
    if model.__name__ == "Group" and action in (
        "post_add",
        "post_remove",
        "post_clear",
    ):
        cache.clear()
        tasks = (BroadcastNotifierTask("LIBRARY_CHANGED"),)
        task = DelayedTasks(2, tasks)
        LIBRARIAN_QUEUE.put(task)


def connect_signals():

3 Source : models.py
with GNU General Public License v3.0
from artoonie

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        # Clear the cache. Otherwise, you'll continue to get the cached result
        # of the old model.
        cache.clear()


class TextToSpeechCachedFile(models.Model):

3 Source : testRestApi.py
with GNU General Public License v3.0
from artoonie

    def _authenticate_as(self, username):
        cache.clear()
        if not username:
            self.client.force_authenticate()  # pylint: disable=no-member
        else:
            user = get_user_model().objects.get(username=username)
            self.client.force_authenticate(user=user)   # pylint: disable=no-member

    def _upload_file_for_api(self, filename):

3 Source : conftest.py
with GNU Affero General Public License v3.0
from ellisist

def cache():
    """
    Returns a django Cache instance for cache-related operations
    """
    yield django_cache
    django_cache.clear()


@pytest.fixture

3 Source : views.py
with MIT License
from enjoy-binbin

def refresh_cache(request):
    """ 清空缓存 """
    if request.user.is_superuser:
        from django.core.cache import cache
        if cache and cache is not None:
            cache.clear()

        messages.success(request, '缓存刷新成功')
        return redirect(reverse('blog:index'))
    else:
        return HttpResponseForbidden()  # 403封装的HttpResponse

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_ignores_non_cache_files(self):
        fname = os.path.join(self.dirname, 'not-a-cache-file')
        with open(fname, 'w'):
            os.utime(fname, None)
        cache.clear()
        self.assertTrue(os.path.exists(fname),
                        'Expected cache.clear to ignore non cache files')
        os.remove(fname)

    def test_clear_does_not_remove_cache_dir(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_clear_does_not_remove_cache_dir(self):
        cache.clear()
        self.assertTrue(os.path.exists(self.dirname),
                        'Expected cache.clear to keep the cache dir')

    def test_creates_cache_dir_if_nonexistent(self):

3 Source : base.py
with Apache License 2.0
from gethue

    def setUp(self):
        self.base_url = '%s://%s' % (self.protocol, self.domain)
        cache.clear()
        # Create an object for sitemap content.
        TestModel.objects.create(name='Test Object')
        self.i18n_model = I18nTestModel.objects.create(name='Test Object')

    @classmethod

3 Source : tests.py
with Apache License 2.0
from gethue

    def setUp(self):
        cache.clear()

        self.mockldap.start()
        self.ldapobj = self.mockldap['ldap://localhost']

        self.backend = backend.LDAPBackend()
        self.backend.ldap  # Force global configuration

    def tearDown(self):

3 Source : conftest.py
with GNU Affero General Public License v3.0
from kubeportal

def run_around_tests():
    """
    A PyTest fixture with activities to happen before and after each test run.
    """
    cache.clear()   # using the settings fixture to change to dummy cache did not work
    yield


@pytest.fixture

3 Source : clear_cache.py
with MIT License
from LibrePhotos

    def handle(self, *args, **kwargs):
        try:
            assert settings.CACHES
            cache.clear()
            self.stdout.write("Your cache has been cleared!\n")
        except AttributeError:
            raise CommandError("You have no cache configured!\n")

3 Source : photo.py
with MIT License
from LibrePhotos

    def manual_delete(self):
        for path in self.image_paths:
            if os.path.isfile(path):
                logger.info("Removing photo {}".format(path))
                os.remove(path)

        cache.clear()
        return self.delete()

3 Source : serializers.py
with MIT License
from LibrePhotos

    def create(self, validated_data):
        name = validated_data.pop("name")
        qs = Person.objects.filter(name=name)
        if qs.count() > 0:
            return qs[0]
        else:
            new_person = Person()
            new_person.name = name
            new_person.save()
            logger.info("created person {}" % new_person.id)
            cache.clear()
            return new_person

    def update(self, instance, validated_data):

3 Source : serializers.py
with MIT License
from LibrePhotos

    def update(self, instance, validated_data):
        if "newPersonName" in validated_data.keys():
            new_name = validated_data.pop("newPersonName")
            instance.name = new_name
            instance.save()
            cache.clear()
            return instance
        if "cover_photo" in validated_data.keys():
            image_hash = validated_data.pop("cover_photo")
            photo = Photo.objects.filter(image_hash=image_hash).first()
            instance.cover_photo = photo
            instance.save()
            cache.clear()
            return instance
        return instance

    def delete(self, validated_data, id):

3 Source : user.py
with MIT License
from LibrePhotos

    def create(self, validated_data):
        if "scan_directory" in validated_data.keys():
            validated_data.pop("scan_directory")
        # make sure username is always lowercase
        if "username" in validated_data.keys():
            validated_data["username"] = validated_data["username"].lower()
        user = User.objects.create_user(**validated_data)
        logger.info("Created user {}".format(user.id))
        cache.clear()
        return user

    def update(self, instance, validated_data):

3 Source : user.py
with MIT License
from LibrePhotos

    def update(self, instance, validated_data):
        if "scan_directory" in validated_data:
            new_scan_directory = validated_data.pop("scan_directory")
            if os.path.exists(new_scan_directory):
                instance.scan_directory = new_scan_directory
                instance.save()
                logger.info(
                    "Updated scan directory for user {}".format(instance.scan_directory)
                )
            else:
                raise ValidationError("Scan directory does not exist")
        cache.clear()
        return instance

3 Source : photos.py
with MIT License
from LibrePhotos

    def post(self, request, format=None):
        data = dict(request.data)
        image_hash = data["image_hash"]

        photo = Photo.objects.get(image_hash=image_hash)
        if photo.owner != request.user:
            return Response(
                {"status": False, "message": "you are not the owner of this photo"},
                status_code=400,
            )
        cache.clear()
        res = photo._generate_captions_im2txt()
        return Response({"status": res})


class DeletePhotos(APIView):

3 Source : user.py
with MIT License
from LibrePhotos

    def get_permissions(self):
        if self.action == "create":
            self.permission_classes = (IsRegistrationAllowed,)
            cache.clear()
        elif self.action == "list":
            self.permission_classes = (AllowAny,)
        elif self.request.method == "GET" or self.request.method == "POST":
            self.permission_classes = (AllowAny,)
        else:
            self.permission_classes = (IsUserOrReadOnly,)
        return super(UserViewSet, self).get_permissions()

    @cache_response(CACHE_TTL, key_func=CustomObjectKeyConstructor())

3 Source : base.py
with Apache License 2.0
from lumanjiao

    def setUp(self):
        self.base_url = '%s://%s' % (self.protocol, self.domain)
        self.old_Site_meta_installed = Site._meta.installed
        cache.clear()
        # Create an object for sitemap content.
        TestModel.objects.create(name='Test Object')

    def tearDown(self):

3 Source : test_v1.py
with MIT License
from mangadventure

    def teardown_method(self):
        super().teardown_method()
        cache.clear()


class TestReleases(APIViewTestBase):

3 Source : test_v2.py
with MIT License
from mangadventure

    def teardown_method(self):
        super().teardown_method()
        cache.clear()


class TestOpenAPI(APIViewTestBase):

3 Source : test_views.py
with MIT License
from mangadventure

    def teardown_method(self):
        super().teardown_method()
        cache.clear()


class TestIndex(MangadvViewTestBase):

3 Source : test_views.py
with MIT License
from mangadventure

    def _test_filter(self, params: Dict[str, str] = {},
                     results: List[str] = []):
        cache.clear()
        r = self.client.get(self.URL, params)
        assert r.status_code == 200
        if bool(params and results):
            values = map(attrgetter('title'), r.context['results'])
            assert natsort(values) == results

    def test_get_simple(self):

3 Source : test_views.py
with MIT License
from mangadventure

    def teardown_method(self):
        super().teardown_method()
        cache.clear()


class TestDirectory(ReaderViewTestBase):

3 Source : utils.py
with GNU Affero General Public License v3.0
from openedx

    def dangerous_clear_all_tiers():
        """
        This clears both the default request cache and the entire django
        backing cache.

        Important: This should probably only be called for testing purposes.

        TODO: Move CacheIsolationMixin from edx-platform to edx-django-utils
        and kill this method.

        """
        DEFAULT_REQUEST_CACHE.clear()
        django_cache.clear()

    @staticmethod

3 Source : test_views.py
with GNU Affero General Public License v3.0
from openedx

    def setUp(self):
        super().setUp()
        cache.clear()
        self.programs = [
            self.cs_program,
            self.mech_program,
            self.phil_program,
            self.english_program,
        ]
        for program in self.programs:
            cache.set(PROGRAM_CACHE_KEY_TPL.format(uuid=program.discovery_uuid), program)
        self.assert_programs_in_cache()

    def tearDown(self):

3 Source : test_api_livesession.py
with MIT License
from openfun

    def setUp(self):
        """
        Reset the cache so that no throttles will be active
        """
        cache.clear()

    def checkRegistrationEmailSent(self, email, video, username, livesession):

3 Source : test_api_video_live_pairing.py
with MIT License
from openfun

    def setUp(self):
        """
        Reset the cache so that no throttles will be active
        """
        cache.clear()

    def test_api_video_pairing_secret_anonymous_user(self):

3 Source : clear_db.py
with GNU Lesser General Public License v3.0
from OpenHistoricalDataMap

def clear_mapnik_tables():
    """
    Clear all mapnik (osm2pgsql) data & tile cache
    """
    print("clear mapnik data & cache")

    # clear database
    PlanetOsmLine.objects.all().delete()
    PlanetOsmPoint.objects.all().delete()
    PlanetOsmPolygon.objects.all().delete()
    PlanetOsmRoads.objects.all().delete()

    # clear cache
    cache.clear()

3 Source : clear_cache.py
with GNU Lesser General Public License v3.0
from OpenHistoricalDataMap

    def handle(self, *args, **options):
        print("All cache files will be deleted, this can be undo!")
        print("You have 15 seconds to stop this process with pressing ctrl + c")

        for seconds in range(15, 0, -5):
            print("{}s remaining ...".format(seconds))
            sleep(5)

        print("Cache will be delete!")
        cache.clear()
        print("Cache is now clean")

3 Source : test_views.py
with GNU Lesser General Public License v3.0
from OpenHistoricalDataMap

    def test_invalid_url(self, test_tile: Dict[str, dict]):
        # clear cache
        cache.clear()

        request: WSGIRequest = RequestFactory().get(
            self.get_path(kwargs=test_tile["data"])
        )
        response: HttpResponse = generate_tile(
            request=request,
            year=test_tile["data"]["year"],
            month=test_tile["data"]["month"],
            day=test_tile["data"]["day"],
            zoom=test_tile["data"]["zoom"],
            x_pixel=test_tile["data"]["x_pixel"],
            y_pixel=9999,
        )

        if response.status_code != 405:
            raise AssertionError

3 Source : test_freeradius_api.py
with GNU General Public License v3.0
from openwisp

    def setUp(self):
        cache.clear()
        logging.disable(logging.WARNING)
        super().setUp()

    def test_invalid_token(self):

3 Source : test_models.py
with MIT License
from organizerconnect

    def test_get_moderation_tasks_has_no_group_moderation_tasks(self):
        """groups_to_mod in response dict should be false."""
        self.unapproved_request.delete()
        cache.clear()
        response = self.group_owner.get_moderation_tasks()
        self.assertFalse(response['groups_to_mod'])


class UserGroupManagementTest(ConnectTestMixin, TestCase):

3 Source : test_models.py
with MIT License
from organizerconnect

    def test_get_moderation_tasks_has_messages_to_moderate(self):
        """messages_to_mod should be True."""
        Thread.objects.all().delete()
        thread = self.create_thread()
        thread.first_message.status = 'pending'
        thread.first_message.save()

        user = self.create_superuser()
        cache.clear()
        response = user.get_moderation_tasks()
        self.assertTrue(response['messages_to_mod'])

    def test_get_moderation_tasks_no_messages_to_moderate(self):

3 Source : test_models.py
with MIT License
from organizerconnect

    def test_get_moderation_tasks_no_messages_to_moderate(self):
        """messages_to_mod should be False."""
        Thread.objects.all().delete()
        self.create_thread()
        user = self.create_superuser()
        cache.clear()
        response = user.get_moderation_tasks()
        self.assertFalse(response['messages_to_mod'])

    def test_groups_moderating(self):

3 Source : analysedirty.py
with GNU General Public License v3.0
from privacymail

    def handle(self, *args, **kwargs):

        cache.clear()
        self.stdout.write("Analysing dirty Services\n")

        # create_summary_cache(force=True)
        
        analyse_dirty_services()

        print("Done")

3 Source : redocache.py
with GNU General Public License v3.0
from privacymail

    def handle(self, *args, **kwargs):
        t1 = time.time()
        cache.clear()
        self.stdout.write("Cleared cache\n")

        # create_summary_cache(force=True)
        if multiprocessing.cpu_count() > 3:
            cpus = multiprocessing.cpu_count() - 3
        else:
            cpus = 1

        with multiprocessing.Pool(cpus) as p:
            p.map(multiprocessing_create_service_cache, Service.objects.all())
            p.map(multiprocessing_create_thirdparty_cache, Thirdparty.objects.all())
        t2 = time.time()
        print(t2 - t1)
        print("Done")

3 Source : __init__.py
with MIT License
from professor-l

    def teardown(self):
        cache.clear()

        for patch in self._patches:
            patch.stop()

        self._setting_override.__exit__(None, None, None)

    @lazy

3 Source : test_worker_cache.py
with Apache License 2.0
from project-koku

    def setUp(self):
        """Set up the test."""
        super().setUp()
        cache.clear()

    def tearDown(self):

3 Source : test_worker_cache.py
with Apache License 2.0
from project-koku

    def tearDown(self):
        """Tear down the test."""
        super().tearDown()
        cache.clear()

    @patch("masu.processor.worker_cache.CELERY_INSPECT")

3 Source : test_view.py
with Apache License 2.0
from project-koku

    def test_source_list_zerror(self, _):
        """Test provider_linked is False in list when Provider does not exist."""
        cache.clear()
        url = reverse("sources-list")
        response = self.client.get(url, content_type="application/json", **self.request_context["request"].META)
        body = response.json()
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(body)
        self.assertTrue(body.get("data"))
        self.assertFalse(body.get("data")[0]["provider_linked"])

    @patch("sources.api.view.ProviderManager")

3 Source : test_cache_decorator.py
with GNU General Public License v3.0
from projectcaluma

def test_set_cache(info):
    cache.clear()
    ds = MyDataSource()
    result = ds.get_data_test_string(info)
    assert result == "test string"
    assert cache.get("data_source_MyDataSource") == "test string"


def test_get_from_cache(info):

3 Source : test_cache_decorator.py
with GNU General Public License v3.0
from projectcaluma

def test_get_from_cache(info):
    cache.clear()
    ds = MyDataSource()
    ds.get_data_uuid(info)
    cached_result = cache.get("data_source_MyDataSource")
    new_result = ds.get_data_uuid(info)
    assert cached_result == new_result


def test_expired_cache(info):

3 Source : test_cache_decorator.py
with GNU General Public License v3.0
from projectcaluma

def test_expired_cache(info):
    cache.clear()
    ds = MyDataSource()
    ds.get_data_expire(info)
    cached_result = cache.get("data_source_MyDataSource")

    sleep(1.1)
    new_result = ds.get_data_uuid(info)

    assert not cached_result == new_result

3 Source : test_views.py
with GNU General Public License v3.0
from projectcaluma

def test_no_client_id(rf, requests_mock, settings):
    cache.clear()
    authentication_header = "Bearer Token"
    userinfo = {"sub": "1"}
    requests_mock.get(
        settings.OIDC_USERINFO_ENDPOINT, text=json.dumps(userinfo), status_code=401
    )
    requests_mock.post(settings.OIDC_INTROSPECT_ENDPOINT, text=json.dumps(userinfo))

    request = rf.get("/graphql", HTTP_AUTHORIZATION=authentication_header)
    response = views.AuthenticationGraphQLView.as_view()(request)
    assert response.status_code == status.HTTP_401_UNAUTHORIZED

3 Source : models.py
with GNU General Public License v2.0
from puncoder

    def cache_set(cls, key, value):
        cache = cls._get_cache()
        if len(cache) > 1000:  # Prevent overflow
            cache.clear()
        cache[key] = value
        return value

    def save(self, *args, **kwargs):

See More Examples