搜尋
首頁後端開發Python教學透過視圖上適當的「快取控制」來提高 Django 專案的安全性

Boost your Django projects

快取顯著提高了 Django 應用程式效能,但保護敏感資料至關重要。 本文示範如何有效管理 Django 視圖中的快取控制,防止敏感資訊被快取。 這對於登入畫面或顯示使用者特定詳細資訊的頁面至關重要。

快取控制的重要性

不正確的快取配置會使敏感資料面臨安全風險。 如果沒有正確的設置,這些資訊可能會儲存在使用者的瀏覽器或中間代理中,從而產生漏洞。

在 Django 實現快取控制

@never_cache 裝飾器,如 Django 官方文件中所述,可防止基於函數的視圖被快取:

from django.views.decorators.cache import never_cache

@never_cache
def my_secure_view(request):
    # Secure view logic here
    return HttpResponse("This page is protected from caching!")

為了增強跨多個基於類別的視圖的可重複使用性,自訂 mixin 提供了更清晰的解決方案:

# myproject/views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache

@method_decorator(never_cache, name="dispatch")
class PrivateAreaMixin(LoginRequiredMixin):
    """Extends LoginRequiredMixin with Cache-Control directives."""

這個 mixin 簡化了保護基於類別的視圖:

# myapp/views.py

from django.views.generic import TemplateView
from myproject.views import PrivateAreaMixin

class IndexView(PrivateAreaMixin, TemplateView):
    """Example index view."""
    template_name = "index.html"

徹底的安全測試

全面的測試對於驗證PrivateAreaMixin的功能至關重要。 以下範例示範了一個強大的測試套件:

# myproject/tests/test_views.py

from django.test import TestCase, RequestFactory
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_user_model
from django.http import HttpResponse
from django.views import View
from myproject.views import PrivateAreaMixin

class PrivateAreaMixinTest(TestCase):
    """Tests the PrivateAreaMixin's Cache-Control implementation."""

    factory = RequestFactory()

    @classmethod
    def setUpTestData(cls):
        cls.user = get_user_model().objects.create_user(
            username="testuser",
            email="user@test.xyz",
            password="5tr0ngP4ssW0rd",
        )

    def test_login_required_with_cache_control(self):
        class AView(PrivateAreaMixin, View):
            def get(self, request, *args, **kwargs):
                return HttpResponse()

        view = AView.as_view()

        # Test redirection for unauthenticated users
        request = self.factory.get("/")
        request.user = AnonymousUser()
        response = view(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual("/accounts/login/?next=/", response.url)

        # Test authenticated user and Cache-Control headers
        request = self.factory.get("/")
        request.user = self.user
        response = view(request)
        self.assertEqual(response.status_code, 200)
        self.assertIn("Cache-Control", response.headers)
        self.assertEqual(
            response.headers["Cache-Control"],
            "max-age=0, no-cache, no-store, must-revalidate, private",
        )

最佳實務

@never_cache 與可重複使用的 mixin(如 PrivateAreaMixin)結合會產生乾淨、可維護的程式碼。 結合嚴格的測試,這種方法可確保敏感視圖的安全性並遵守最佳實踐。 您如何解決 Django 專案中的快取和敏感資料問題?

以上是透過視圖上適當的「快取控制」來提高 Django 專案的安全性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

了解python的' for”和' then”循環之間的差異了解python的' for”和' then”循環之間的差異May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串聯列表與重複Python串聯列表與重複May 08, 2025 am 12:09 AM

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

Python列表串聯性能:速度比較Python列表串聯性能:速度比較May 08, 2025 am 12:09 AM

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

您如何將元素插入python列表中?您如何將元素插入python列表中?May 08, 2025 am 12:07 AM

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

Python是否列表動態陣列或引擎蓋下的鏈接列表?Python是否列表動態陣列或引擎蓋下的鏈接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何從python列表中刪除元素?如何從python列表中刪除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器