Django進階篇(二)

中間件

  解析

django 中的中間件(middleware),在django中,中間件其實就是一個類,在請求到來和結束後,html

django會根據本身的規則在合適的時機執行中間件中相應的方法。前端

在django項目的settings模塊中,有一個 MIDDLEWARE_CLASSES 變量,python

其中每個元素就是一箇中間件,數據庫

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',  # 跨站請求僞造
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

以上方法的返回值能夠是None和HttpResonse對象,若是是None,則繼續按照django定義的規則向下執行,django

若是是HttpResonse對象,則直接將該對象返回給用戶。json

  流程圖

上面的流程圖可能有些亂,爲了解流程花的草圖;緩存

上面是Django 1.9版本的流程圖,到django 1.10就變了;session

變成了request在相對應的response中找。app

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import HttpResponse


class test1Middleware(object):

    def process_request(self, request):
        print('11111111')

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print('process_view1')

    def process_response(self, request, response):
        print('response 111111')
        return response

    def process_template_response(self, request, response):
        print('template1')

        return response

    def process_exception(self, request, exception):
        print('ex1')



class test2Middleware(object):

    def process_request(self, request):

        #if request.META['REMOTE_ADDR'] in ['1.1.1.1','1.1.1.2']:
        #    return HttpResponse('SB')
        # return HttpResponse('SB')
        print('22222')

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print('process_view2')

    def process_template_response(self, request, response):
        print('template2')

        return response
    def process_exception(self, request, exception):
        print('ex2')


class test3Middleware(object):

    def process_request(self, request):
        print('33333')

    def process_response(self, request, response):
        print('response 33333')
        return response

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print('process_view3')

    def process_template_response(self, request, response):
        print('template3')
        return response

    def process_exception(self, request, exception):
        print('ex3')
        return HttpResponse('500')
test.py

 

  自定義中間件

一、建立中間件的類框架

class RequestExeute(object):
      
    def process_request(self,request):
        pass
    def process_view(self, request, callback, callback_args, callback_kwargs):
        i =1
        pass
    def process_exception(self, request, exception):
        pass
      
    def process_response(self, request, response):
        return response

二、註冊中間件

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'wupeiqi.middleware.auth.RequestExeute',
)

  

緩存

  解析

因爲Django是動態網站,通常來講須要實時地生成訪問的網頁,展現給訪問者,這樣內容能夠隨時變化,

可是從數據庫讀屢次把所須要的數據取出來,要比從內存或者硬盤中讀出來 付出的成本大不少。

最簡單解決方式是使用:緩存,緩存將一個某個views的返回值保存至內存或者Redis中,必定時間內再有人來訪問時,

則再也不去執行view中的操做,而是直接從內存或者Redis中以前緩存的內容拿到,並返回。

Django中提供6種緩存方式:

  開發調試

  內存

  文件

  數據庫

  Memcache緩存(python-memcached模塊)

  Memcache緩存(pylibmc模塊)

  配置

a、開發調試

# 此爲開始調試用,實際內部不作任何操做
    # 配置:
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.dummy.DummyCache',  # 引擎
                'TIMEOUT': 300,  # 緩存超時時間(默認300,None表示永不過時,0表示當即過時)
                'OPTIONS':{
                    'MAX_ENTRIES': 300,  # 最大緩存個數(默認300)
                    'CULL_FREQUENCY': 3,  # 緩存到達最大個數以後,剔除緩存個數的比例,即:1/CULL_FREQUENCY(默認3)
                },
                'KEY_PREFIX': '',  # 緩存key的前綴(默認空)
                'VERSION': 1,       # 緩存key的版本(默認1)
                'KEY_FUNCTION' 函數名     # 生成key的函數(默認函數會生成爲:【前綴:版本:key】)
            }
        }


    # 自定義key
    def default_key_func(key, key_prefix, version):
        """
        Default function to generate keys.

        Constructs the key used by all other methods. By default it prepends
        the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
        function with custom key making behavior.
        """
        return '%s:%s:%s' % (key_prefix, version, key)

    def get_key_func(key_func):
        """
        Function to decide which key function to use.

        Defaults to ``default_key_func``.
        """
        if key_func is not None:
            if callable(key_func):
                return key_func
            else:
                return import_string(key_func)
        return default_key_func

b、內存

# 此緩存將內容保存至內存的變量中
    # 配置:
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
                'LOCATION': 'unique-snowflake',
            }
        }

    # 注:其餘配置同開發調試版本

c、文件

# 此緩存將內容保存至文件
    # 配置:

        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
                'LOCATION': '/var/tmp/django_cache',
            }
        }
    # 注:其餘配置同開發調試版本

d、數據庫

# 此緩存將內容保存至數據庫

    # 配置:
        CACHES = {
            'default': {
                'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
                'LOCATION': 'my_cache_table', # 數據庫表
            }
        }

    # 注:執行建立表命令 python manage.py createcachetable

e、Memcache緩存(python-memcached模塊)

# 此緩存使用python-memcached模塊鏈接memcache

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': '127.0.0.1:11211',
        }
    }

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': 'unix:/tmp/memcached.sock',
        }
    }   

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': [
                '172.19.26.240:11211',
                '172.19.26.242:11211',
            ]
        }
    }

f、Memcache緩存(pylibmc模塊)

# 此緩存使用pylibmc模塊鏈接memcache
    
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
            'LOCATION': '127.0.0.1:11211',
        }
    }

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
            'LOCATION': '/tmp/memcached.sock',
        }
    }   

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
            'LOCATION': [
                '172.19.26.240:11211',
                '172.19.26.242:11211',
            ]
        }
    }

  應用 

a. 全站使用

使用中間件,通過一系列的認證等操做,若是內容在緩存中存在,則使用FetchFromCacheMiddleware獲取內容並返回給用戶,
當返回給用戶以前,判斷緩存中是否已經存在,若是不存在則UpdateCacheMiddleware會將緩存保存至緩存,從而實現全站緩存 MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', # 其餘中間件... 'django.middleware.cache.FetchFromCacheMiddleware', ] CACHE_MIDDLEWARE_ALIAS = "" CACHE_MIDDLEWARE_SECONDS = "" CACHE_MIDDLEWARE_KEY_PREFIX = ""

b. 單獨視圖緩存

方式一:
        from django.views.decorators.cache import cache_page

        @cache_page(60 * 15)
        def my_view(request):
            ...

    方式二:
        from django.views.decorators.cache import cache_page

        urlpatterns = [
            url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
        ]

  示例:

from django.shortcuts import render,HttpResponse,HttpResponseRedirect
import time
# from django_nanian import pizza_done
from django.views.decorators.cache import cache_page


class Response:
    def __init__(self, request, html, *args, **kwargs):
        self.request = request
        self.args = args
        self.html = html
        self.kwargs = kwargs

    def render(self, *args, **kwargs):
        return render(self.request, self.html, *self.args, **self.kwargs)
# Create your views here.


def index(request):
    print('views')
    return Response(request, 'index.html')


@cache_page(10)  # 使用裝飾器進行局部緩存,生效時間十秒
def cache1(request, page):
    t = time.time()
    return render(request, 'cache.html', {'t': t})


def cache2(request):
    t = time.time()
    # pizza_done.send(sender='cache2', toppings=1, size=3)
    return render(request, 'cache.html', {'t': t})
Views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ t }}
</body>
</html>
cache.html

c、局部模板使用

在前端頁面

a. 引入TemplateTag

        {% load cache %}

b. 使用緩存

        {% cache 5000 緩存key %}
            緩存內容
        {% endcache %}

  示例:

def cache3(request):  # 局部視圖緩存
    print(type(request))
    t = time.time()
    from app01 import models
    print('before')
    # models.UserInfo.objects.create(name='test')
    print('after')
    # pizza_done.send(sender='cache3', toppings=123, size=456)
    return render(request, 'cache3.html', {'t': t})
Views.py
{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ t }}
    <hr />
     {% cache 10 nnn %}  {# 緩存十秒 #}
         {{ t }}
     {% endcache %}

</body>
</html>
cache3.html

 

信號

 Django中提供了「信號調度」,用於在框架執行操做時解耦。通俗來說,就是一些動做發生的時候,信號容許特定的發送者去提醒一些接受者。

  Django內置信號

Model signals
    pre_init                    # django的modal執行其構造方法前,自動觸發
    post_init                   # django的modal執行其構造方法後,自動觸發
    pre_save                    # django的modal對象保存前,自動觸發
    post_save                   # django的modal對象保存後,自動觸發
    pre_delete                  # django的modal對象刪除前,自動觸發
    post_delete                 # django的modal對象刪除後,自動觸發
    m2m_changed                 # django的modal中使用m2m字段操做第三張表(add,remove,clear)先後,自動觸發
    class_prepared              # 程序啓動時,檢測已註冊的app中modal類,對於每個類,自動觸發
Management signals
    pre_migrate                 # 執行migrate命令前,自動觸發
    post_migrate                # 執行migrate命令後,自動觸發
Request/response signals
    request_started             # 請求到來前,自動觸發
    request_finished            # 請求結束後,自動觸發
    got_request_exception       # 請求異常後,自動觸發
Test signals
    setting_changed             # 使用test測試修改配置文件時,自動觸發
    template_rendered           # 使用test測試渲染模板時,自動觸發
Database Wrappers
    connection_created          # 建立數據庫鏈接時,自動觸發

對於Django內置的信號,僅需註冊指定信號,當程序執行相應操做時,自動觸發註冊函數:

from django.core.signals import request_finished
    from django.core.signals import request_started
    from django.core.signals import got_request_exception

    from django.db.models.signals import class_prepared
    from django.db.models.signals import pre_init, post_init
    from django.db.models.signals import pre_save, post_save
    from django.db.models.signals import pre_delete, post_delete
    from django.db.models.signals import m2m_changed
    from django.db.models.signals import pre_migrate, post_migrate

    from django.test.signals import setting_changed
    from django.test.signals import template_rendered

    from django.db.backends.signals import connection_created


    def callback(sender, **kwargs):
        print("xxoo_callback")
        print(sender,kwargs)

    xxoo.connect(callback)
    # xxoo指上述導入的內容
from django.core.signals import request_finished
from django.dispatch import receiver

@receiver(request_finished)
def my_callback(sender, **kwargs):
    print("Request finished!")

  自定義信號

a. 定義信號

import django.dispatch
pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])

b. 註冊信號

def callback(sender, **kwargs):
    print("callback")
    print(sender,kwargs)
 
pizza_done.connect(callback)

c. 觸發信號

from 路徑 import pizza_done
 
pizza_done.send(sender='seven',toppings=123, size=456)

因爲內置信號的觸發者已經集成到Django中,因此其會自動調用,而對於自定義信號則須要開發者在任意位置觸發。

 

上傳文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload_file/" enctype="multipart/form-data" method="POST">
        {% csrf_token %}
        <input type="file" name="fafafa" />

        <input type="submit" value="提交" />
    </form>
</body>
</html>
file.html
from django.shortcuts import render,HttpResponse

# Create your views here.


def upload_file(request):
    if request.method == "POST":  # 以POST 的方式
        file_name = request.FILES
        file_obj = file_name.get("file_name_1")  # 獲取到封裝了文件操做的對象
        f = open(file_obj.name, "wb")
        for line in file_obj.chunks():   # 循環取數據
            f.write(line)
        f.close()
        return HttpResponse("上傳成功")
    else:
        return render(request, "upload.html")
Views.py

 

序列化

關於Django中的序列化主要應用在將數據庫中檢索的數據返回給客戶端用戶,特別的Ajax請求通常返回的爲Json格式。

一、serializers

from django.core import serializers
 
ret = models.BookType.objects.all()
 
data = serializers.serialize("json", ret)

二、json.dumps

import json
 
#ret = models.BookType.objects.all().values('caption')
ret = models.BookType.objects.all().values_list('caption')
 
ret=list(ret)
 
result = json.dumps(ret)

因爲json.dumps時沒法處理datetime日期,因此能夠經過自定義處理器來作擴展,如:

import json 
from datetime import date 
from datetime import datetime 
   
class JsonCustomEncoder(json.JSONEncoder): 
    
    def default(self, field): 
     
        if isinstance(field, datetime): 
            return o.strftime('%Y-%m-%d %H:%M:%S') 
        elif isinstance(field, date): 
            return o.strftime('%Y-%m-%d') 
        else: 
            return json.JSONEncoder.default(self, field) 

  

更多詳見:http://www.cnblogs.com/wupeiqi/articles/5246483.html

相關文章
相關標籤/搜索