The cache

  • Definition: Cache is a kind of media that can read data faster. It also refers to other storage methods that can speed up data reading. It is generally used to store temporary data
  • Significance: View rendering has a certain cost, and the frequent query of database is too high. Therefore, caching technology can be considered to reduce the actual rendering times for pages with low-frequency changes. The time cost for the user to get the response is lower

Cache cases:

# Case study
from django.shortcuts import render

def index(request) :
   # Extremely time-intensive rendering
   book_list = Book.objects.all(a)return render(request , 'index.html'.locals())
Copy the code

Set cache – database cache in Django

Store cached data in your database
# description:
    # Although the storage medium has not been replaced. However, when the results of a query are directly stored in the table, such as the filtering query results of a condition, repeated complex queries can be avoided and efficiency can be improved.
   CACHES= {
      'default': {'BACKEND':'django.core.cache.backends.db.DatabaseCache'.'LOCATION':'my_cache_tadle'.'TIMEOUT':300.Cache retention time in seconds. The default value is 300
         'OPTIONS': {
             'MAX_ENTRIES':300.# Maximum number of bytes cached
             'CULL_FREQUENCY':2  The number of cache entries reaches the maximum. Delete 1/x cached data}}}Copy the code

Setting cache in Django – local memory cache

Data is cached into service memory
Configuration example:
CACHES = {
     'default': {
        'BACKEEND':
        'django.core.cache,backends.locmem.LocMemCache'.'LOCATION': 'unique-snowflake'}}Copy the code

Case study:

  1. Create the mysite7 project
# create project
django-admin startproject mysite7
Copy the code

2. Create a database

Create a database named mysite7
mysql> create database mysite7 default charset utf8;
Copy the code
Connect to database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql'.'NAME': 'mysite7'.'USER': 'root'.'PASSWORD': 'aa123456'.'HOST': '127.0.0.1'.'PORT': '3306',}}Copy the code

3. Add the cache configuration


The database cache configuration requires manual execution of the create table command
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache'.'LOCATION': 'my_cache_table'.'TIMEOUT': '300'.# Cache retention time in seconds. Default value: 300
        'OPTIONS': {
            'MAX_ENTRIES': 300.# Maximum number of bytes cached
            'CULL_FREQUENCY': 2.Delete 1/x cache data when the number of cache entries reaches the maximum value}}},# Execute on terminal
python3 manage.py createcachetable
Copy the code

Viewing a Database

Overall cache strategy

Djangos use cache-view functions

Example #
from django.views.decorators.cache import cache_page


@cache_page(30) --> unit s
def my_view(request) :. .Copy the code

Django uses caching – Routing

Example #
from django.views.decorators.cache import cache_page

urlpatterns = [
    path('foo/', cache_page(60)(my_view))
]

Copy the code

Use of the cache API

The cache object is introduced first

# Method 1: Use caches['CACHE configuration key'] to import specific objects
from django.core.cache imort caches
cache1 = caches['myalias']
cache2 = caches['myalias_2']

# Method 2:
from django.core.cache importCache is directly added to the CACHES configuration'default'itemCopy the code
  1. Cache.set (key, value, timeout) – Store cache

    Key: cache key. It is a string of characters

    Value: a Python object

    Timeout: cache storage time (s), default to timeout in CACHES

    Return value: None

  2. Cache.get (key) – Gets the cache

    Key: cache key

    Return value: the specific value of key. If there is no data, None is returned

  3. Cache.add (key, value) – Stores the cache, only when the key does not exist

    Return value: True[storage cache]or False[storage failure]

  4. Cahe. get_OR_SET (key, value, timeout) – If no data is retrieved, the set operation returns value: value

  5. Cache.set_many (dict, timeout) – Batch store cache

    Dict: a dictionary of keys and values

    Timeout: Storage time (s)

    Return value: Array of unsuccessful insert keys

  6. Cache.get_many (key_list) – Fetches cached data in batches

    Key_list An array of keys

    Return value: dictionary of keys and values taken

  7. Cache.delete (key)- Deletes cached data from the key

    Return value: None

  8. Cache.delete_many (key_list) – Batch delete Return value: None

Browser Cache policy

Strong cache

1. Response header -Espires

Definition: Cache expiration time, used to specify when a resource expires. Is the point in time on the server side

Example: Expires:Thu, 02 Apr 2030 05:14:08 GMT

2. Response header -cache-control

In the HTTP /1.1Cache-control is used to Control web caching. For example, when ` cache-control:max-age = 120'represents after the request was created120Second cache invalidation note: Currently the server responds to the browser with both headers. Cache-control is preferred by browsersCopy the code

Negotiate the cache

Once the data in the strong cache expires, it needs to communicate with the server to obtain the latest data.

When the strong cache expires, the browser negotiates with the server whether the current cache is available. If so, the server does not need to return data. The browser will continue to use the raw cached data and return the latest data if the file is not available

  1. Last-modified response headers and if-Modified-since request headers

    Description:

    1.1 Last-Modified is the Last time a file was Modified. If the server returns a last-Modified response header when the browser requests a static file for the first time, it indicates that the resource is a cache to be negotiated

    1.2 When the cache expires, the browser will obtain the last-Modified value as the value of the request header if-modifie-since and negotiate with the server. The server returns 304 response code [the response body is empty], indicating that the cache continues to be used, 200 impact indicates that the cache is unavailable [the response body is the latest resource]

  2. ETag response headers and if-none-match request headers

    Description:

    2.1 Etag is a unique identifier (generated by the server) returned to the current resource file when the server responds to a request. As long as the resource changes, Etag will be generated again.

    2.2 Cache Expiration. The browser uses the value of the Etag response header as the value of the if-none-mactch request header to negotiate the request to the server. After receiving the request header, the server compares the file identification. If the file identification is inconsistent, it considers the resource unavailable and returns 200 response code [the response body is the latest resource]. If available, 304 response code is returned

The middleware

define

- Middleware is Django's hook framework for request/response processing. It is a lightweight 'low-level' plug-in 'system for completely changing Djangos input or output - Middleware is represented as a class - each middleware component is responsible for doing a specific function, For example, Django includes a middleware component, AuthenticationMiddleware, that uses sessions to associate users with requests. - Middleware is Django's hook framework for request/response processing. It is a lightweight 'low-level' plug-in 'system for completely changing Djangos input or output - Middleware is represented as a class - each middleware component is responsible for doing a specific function, For example, Django includes a middleware component, AuthenticationMiddleware, that uses sessions to associate users with requests.Copy the code

Writing middleware

- middleware class must be inherited from the django. Utils. Deprecation. MiddlewareMixin class - middleware class must implement a multiple in the following five ways: - process_request(self, request) is called before performing the route, called on each request, returnsNoneOr HttpResponse object - process_view(self, request, callback, Callback_args, callback_kwargs) is called before calling the view, called on each request, and returnsNoneOr HttpResponse object - process_response(self, request, response) All responses back to the browser are called, Call on each request returns an HttpResponse object - process_exception(self, request, exception) Called when an exception is thrown during processing, returns an HttpResponse object note: Most methods in middleware return an HttpResponse objectNoneIf the HttpResponse object is returned, the request is completed and returned directly to the clientCopy the code

Registered middleware

The custom middleware needs to be registered in # setting.py
MIDDEWARE = [
  .. . . 
]
# Note: Configured as an array, middleware is called in 'top down' and then 'top up' order

Copy the code

Exercise 1

Middleware enforces an IP address to send only 5 requests to addresses starting with /testTip: request. META ['REMOTE_ADDR'] Can obtain the IP address of the remote client. Request. Path_info Can obtain the request route information of the clientCopy the code

CSRF attacks

# CSRF - Cross-site forgery request attackSome malicious sites contain links, form buttons, or JavaScript that attempt to accomplish something on your Site using the authentication information of the logged in user in the browser. This is called CROSS-site Request forgery (CSRE).Copy the code

CSRF protection

  • Django uses a ‘comparison code’ mechanism to protect against attacks

  • Password 1 is stored in Cookies, and password 2 is hidden in the form in templates. The password 2 will be submitted to the server with the form only when the user submits data under this website. Django compares the password and considers it a valid request if the comparison is successful

  • Configuration steps:

    1. Settings. The recognized in py django in MIDDLEWARE. MIDDLEWARE. CSRF. CsrViewMiddleware is on

    2. In the template, add the following tags under the form tag

      {% csrf_token %}

  • Special note:

If a view doesn’t need Django’s CSRF protection, you can use the decorator to turn off checking for that view


Example #
from django.views.dacorators.csrf import cserf_exempt

@csrf_exempt
def my_view(request) :return HttpResponse('hello')
Copy the code

paging

Paging definition

- Pagination means that a large amount of data needs to be displayed on a Web page, and part of the data is displayed on each page for ease of reading.1.Very easy to read2.Reduce the amount of data extraction and take the pressure off the server -- Django provides Paginator classes to easily do pagination -- the Paginator class is located in the 'Django.core. Paginator' moduleCopy the code

Paginator

# paginator objectPaginator = paginator (object_list, Per_page) - parameter - object_list List of objects that need to classify data - per_page Number of data per page - Return value: -paginator objectCopy the code

Paginator property

- count: indicates the total number of objects requiring paging data. - num_pages: indicates the total number of pages after paging. - page_range: indicates from1The start of therange-per_page: number of data per pageCopy the code

Paginator method

Paginator object. Page (numder) - Parameter number for page number information (from1Start) - returns the page information corresponding to the current Numder page - throws an lnvalidPage exception if the page number provided does not existCopy the code

Abnormal Paginator exception

LnvaidPage: Total exception base class, containing the following two exception subclasses - PageNotAnlnteger: thrown when a value that is not an integer is passed to page() - EmptyPage: thrown when a valid value is provided to Page (), but there are no objects on that pageCopy the code

Page object definition

Page() returns Page object Page = Paginator. Page(Page number) - Page object properties - object_List: List of all data objects on the current page - numder: serial number of the current page, from1Start -paginator: the paginator object associated with the current page object -has_next (): returns true -has_previous () if there is a next page: Returns true if there is a previous page -has_other_pages (): returns true if there is a previous or next page -next_page_number (): Returns the page number of the next page. If the next page does not exist, an lnvalidPage exception is thrown. -previous_page_number () : returns the page number of the previous page. If the previous page does not exist, throw an lnvalidPage exceptionCopy the code

Paging small cases

  • Create a view
def test_page(request) :
    page_num = request.GET.get('page'.1)
    all_data = ['a'.'b'.'c'.'d'.'e']
    # initializing Paginator
    paginator = Paginator(all_data, 2)
    Initialize the page object with a specific page number
    c_page = paginator.page(int(page_num))
    return render(request, 'test_page.html'.locals())
Copy the code
  • Configure the routing

path('test_page', views.test_page)
Copy the code
  • Create a template
Create the templates folder
Create test_page.html file<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"</title> </head> <body> {%for p  in c_page %}
   <P>
    {{ p }}
   </P>

{% endfor %}

{% if c_page.has_previous %}
   <a href="/test_page? page={{ c_page.previous_page_numder }}"> previous page </a> {%else%} previous page {% endif %} {%for p_num in paginator.page_range  %}
    {% if p_num == c_page.number %}
        {{ p_num }}
    {% else %}
        <a href="/test_page? page={{ p_num }}">{{ p_num }}</a>
    {% endif %}

{% endfor %}


{% if c_page.has_next %}
   <a href="/test_page? page={{ c_page.next_page_number }}"> Next page </a> {%else{% endif %} </body> </ HTML >Copy the code

Generating a CSV file

Generate CSV files in Python

Python provides the internal key library -csv to operate on CSV files directly. Exampleimport csv
 with opne('eggs.csv'.'w', newline=' ')as csvfile:
      writer = csv.writer(csvfile)
      writer.writerow(['a'.'b'.'c'])
Copy the code

CSV file Download

- In the website, implement the download CSV, note the following: - response Content-TypeThe type needs to be changed to text/ CSV. This tells the browser that the document is a CSV file, not an HTML file - the response gets an additional Content-Disposition header containing the name of the CSV file, which the browser will use to open the 'Save as' dialog boxCopy the code

case


# sample code
import csv
from django.http import HttpResponse
from .models import Book

def make_csv_view(requset) :
    response = HttpResponse(content_type = 'text/csv')
    response['Content-Disposition'] = 'attachment; filename = 'mybook.csv' '
    all_book = Book.objects.all()
    writer = csv.writer(response)
    writer.writerow(['id'.'title'])
    for b in all_book:
        writer.writerow[(b.id, b.title)]
        
    return response
Copy the code