djangoform表單插件,中間件,緩存,信號(hào)-創(chuàng)新互聯(lián)

一、form插件
django form表單類的字段和插件,字段用于表單驗(yàn)證獲取數(shù)據(jù),插件用來生成html代碼
Field
    required=True,               是否允許為空
    widget=None,                 HTML插件
    label=None,                  用于生成Label標(biāo)簽或顯示內(nèi)容
    initial=None,                初始值
    help_text='',                幫助信息(在標(biāo)簽旁邊顯示)
    error_messages=None,         錯(cuò)誤信息 {'required': '不能為空', 'invalid': '格式錯(cuò)誤'}
    show_hidden_initial=False,   是否在當(dāng)前插件后面再加一個(gè)隱藏的且具有默認(rèn)值的插件(可用于檢驗(yàn)兩次輸入是否一直)
    validators=[],               自定義驗(yàn)證規(guī)則
    localize=False,              是否支持本地化
    disabled=False,              是否可以編輯
    label_suffix=None            Label內(nèi)容后綴
    

CharField(Field)
    max_length=None,             大長度
    min_length=None,             最小長度
    strip=True                   是否移除用戶輸入空白

IntegerField(Field)
    max_value=None,              大值
    min_value=None,              最小值
    
DecimalField(IntegerField)
    max_value=None,              大值
    min_value=None,              最小值
    max_digits=None,             總長度
    decimal_places=None,         小數(shù)位長度
    
RegexField(CharField)
    regex,                      自定制正則表達(dá)式
    max_length=None,            大長度
    min_length=None,            最小長度
    error_message=None,         忽略,錯(cuò)誤信息使用 error_messages={'invalid': '...'}

EmailField(CharField)
FileField(Field)
    allow_empty_file=False     是否允許空文件

ChoiceField(Field)
    ...
    choices=[],                選項(xiàng),如:choices = [(0,'上海'),(1,'北京'),]
    required=True,             是否必填
    widget=None,               插件,默認(rèn)select插件
    label=None,                Label內(nèi)容
    initial=None,              初始值
    help_text='',              幫助提示
    
FilePathField(ChoiceField)     文件選項(xiàng),目錄下文件顯示在頁面中
    path,                      文件夾路徑
    match=None,                正則匹配
    recursive=False,           遞歸下面的文件夾
    allow_files=True,          允許文件
    allow_folders=False,       允許文件夾
    required=True,
    widget=None,
    label=None,
    initial=None,
    help_text=''

GenericIPAddressField
    protocol='both',           both,ipv4,ipv6支持的IP格式
    unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1時(shí)候,可解析為192.0.2.1, PS:protocol必須為both才能啟用
二、form驗(yàn)證規(guī)則
新建模塊forms.py
from django.forms import Form
from django.forms import fields
from django.forms import widgets
from app01 import models
import re
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

class UserInfoForm(Form):
    name = fields.CharField(
        required=True,
        min_length=6,
        max_length=12
    )
    email = fields.EmailField(
        required=True,
    )
    方法一: RegexValidator對象
    phone = fields.CharField(
        validators=[RegexValidator(r'^[0-9]+$', '請輸入數(shù)字'), RegexValidator(r'^159[0-9]+$', '數(shù)字必須以159開頭')]
     )
     
    方式二:函數(shù)
    def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手機(jī)號(hào)碼格式錯(cuò)誤')
        
    phone = fields.CharField(
         validators= [mobile_validate,]
     )
     
    方法三:當(dāng)前類的方法中,方法名稱要求: clean_phone方法
    phone = fields.CharField()
    
    def clean_phone(self):
        # 去取用戶提交的值:可能是錯(cuò)誤的,可能是正確
        value = self.cleaned_data['phone']
        mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
        if not mobile_re.match(value):
            raise ValidationError('手機(jī)號(hào)碼格式錯(cuò)誤')

        if models.UserInfo.objects.filter(phone=value).count():
            raise ValidationError('手機(jī)號(hào)碼已經(jīng)存在')

        return value
        
 注冊確認(rèn)密碼認(rèn)證clean函數(shù)
 class RegisterForm(Form):
    name = fields.CharField(
        widget=widgets.TextInput(attrs={'class': 'c1'})
    )

    email = fields.EmailField(
        widget=widgets.EmailInput(attrs={'class': 'c1'})
    )

    phone = fields.CharField(
        widget=widgets.Textarea(attrs={'class': 'c1'})
    )

    pwd = fields.CharField(
        widget=widgets.PasswordInput(attrs={'class': 'c1'})
    )

    pwd_confirm = fields.CharField(
        widget=widgets.PasswordInput(attrs={'class': 'c1'})
    )

    dp_id = fields.ChoiceField(
        choices=[]
    )

    roles_id = fields.ChoiceField(
        choices=[]
    )

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['dp_id'].choices = models.Depart.objects.values_list('id', 'title')
        self.fields['roles_id'].choices = models.Role.objects.values_list('id', 'name')

    def clean(self):
        pwd = self.cleaned_data['pwd']
        pwd_confirm = self.cleaned_data['pwd_confirm']
        if pwd == pwd_confirm:
            return self.cleaned_data
        else:
            from django.core.exceptions import ValidationError
            self.add_error('pwd_confirm', ValidationError('密碼輸入不一致'))
            return self.cleaned_data
三、中間件
項(xiàng)目目錄下新建目錄md
md目錄新建middleware.py文件
from django.shortcuts import HttpResponse,redirect

class MiddlewareMixin:
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin,self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

class M1(MiddlewareMixin):
    def process_request(self, request):
        print('m1.process_request')

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

    def process_exception(self,request,exception):
        print('m1.process_exception')

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

class M2(MiddlewareMixin):
    def process_request(self, request):
        print('m2.process_request')

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

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

    def process_exception(self,request,exception):
        print('m2.process_exception')
        
        
 settings.py文件中間件添加
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',
    'md.middleware.M1',    #添加項(xiàng)
    'md.middleware.M2',    #添加項(xiàng)
]


中間件是一個(gè)類
中間件中一共有四個(gè)方法:
process_request
process_view
process_exception
process_response


已經(jīng)添加中間件M1和M2
中間件執(zhí)行時(shí)機(jī): 請求到來,請求返回時(shí)
- 應(yīng)用:
    - 請求日志
    - 用戶登錄認(rèn)證

django form表單插件,中間件,緩存,信號(hào)

創(chuàng)新互聯(lián)專注于中大型企業(yè)的成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)和網(wǎng)站改版、網(wǎng)站營銷服務(wù),追求商業(yè)策劃與數(shù)據(jù)分析、創(chuàng)意藝術(shù)與技術(shù)開發(fā)的融合,累計(jì)客戶1000+,服務(wù)滿意度達(dá)97%。幫助廣大客戶順利對接上互聯(lián)網(wǎng)浪潮,準(zhǔn)確優(yōu)選出符合自己需要的互聯(lián)網(wǎng)運(yùn)用,我們將一直專注成都品牌網(wǎng)站建設(shè)和互聯(lián)網(wǎng)程序開發(fā),在前進(jìn)的路上,與客戶一起成長!
四、緩存
由于Django是動(dòng)態(tài)網(wǎng)站,所有每次請求均會(huì)去數(shù)據(jù)進(jìn)行相應(yīng)的操作,當(dāng)程序訪問量大時(shí),耗時(shí)必然會(huì)
更加明顯,最簡單解決方式是使用:緩存,緩存將一個(gè)某個(gè)views的返回值保存至內(nèi)存或者memcache中,
5分鐘內(nèi)再有人來訪問時(shí),則不再去執(zhí)行view中的操作,而是直接從內(nèi)存或者Redis中之前緩存的內(nèi)容拿
到,并返回

Django中提供了6種緩存方式:
1. 開發(fā)調(diào)試
2. 內(nèi)存
3. 文件
4. 數(shù)據(jù)庫
5. Memcache緩存(python-memcached模塊)
6. Memcache緩存(pylibmc模塊)

a.開發(fā)調(diào)試
# 此為開始調(diào)試用,實(shí)際內(nèi)部不做任何操作
# 配置:
CACHES = {            
    'default': {               
         'BACKEND': 'django.core.cache.backends.dummy.DummyCache',     # 引擎
         'TIMEOUT': 300, # 緩存超時(shí)時(shí)間(默認(rèn)300,None表示永不過期,0表示立即過期)
         'OPTIONS':{
             'MAX_ENTRIES': 300, # 大緩存?zhèn)€數(shù)(默認(rèn)300)
             'CULL_FREQUENCY': 3,    # 緩存到達(dá)大個(gè)數(shù)之后,剔除緩存?zhèn)€數(shù)的比例,即:1/CULL_FREQUENCY(默認(rèn)3)
             },
         'KEY_PREFIX': '', # 緩存key的前綴(默認(rèn)空)  
         'VERSION': 1,     # 緩存key的版本(默認(rèn)1)
         'KEY_FUNCTION' 函數(shù)名    # 生成key的函數(shù)(默認(rèn)函數(shù)會(huì)生成為:【前綴:版本:key】)
       }
     }
     
     
 def default_key_func(key, key_prefix, version):
     return '%s:%s:%s' % (key_prefix, version, key)
     
 def get_key_func(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. 內(nèi)存緩存
  此緩存將內(nèi)容保存至內(nèi)存的變量中
  # 配置:
  CACHES = {           
       'default': {                
           'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',                
           'LOCATION': 'unique-snowflake',
            }
        }
   
c. 文件緩存
# 此緩存將內(nèi)容保存至文件
    # 配置:
        CACHES = {            
            'default': {                
                'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',  
                'LOCATION': '/var/tmp/django_cache',
            }
        }
        
d. 數(shù)據(jù)庫緩存
# 此緩存將內(nèi)容保存至數(shù)據(jù)庫

    # 配置:
        CACHES = {            
            'default': {               
                 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',                
                 'LOCATION': 'my_cache_table', # 數(shù)據(jù)庫表                           
             }
        }
        
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',
            ]
        }
    }
    
    
緩存使用方法
1. 全站應(yīng)用配置
使用中間件,經(jīng)過一系列的認(rèn)證等操作,如果內(nèi)容在緩存中存在,則使用FetchFromCacheMiddleware獲
取內(nèi)容并返回給用戶,當(dāng)返回給用戶之前,判斷緩存中是否已經(jīng)存在,如果不存在則
UpdateCacheMiddleware會(huì)將緩存保存至緩存,從而實(shí)現(xiàn)全站緩存

MIDDLEWARE = [       
         'django.middleware.cache.UpdateCacheMiddleware',        # 其他中間件...
         'django.middleware.cache.FetchFromCacheMiddleware',
    ]

    #CACHE_MIDDLEWARE_ALIAS = ""
   # CACHE_MIDDLEWARE_SECONDS = ""
   # CACHE_MIDDLEWARE_KEY_PREFIX = ""
    
2.單獨(dú)視圖函數(shù)
方式一:        
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)),
    ]
    
    
3.局部視圖使用
a. 引入TemplateTag

        {% load cache %}

b. 使用緩存

        {% cache 5000 緩存key %}
            緩存內(nèi)容
        {% endcache %}
        
五、信號(hào)
1.內(nèi)置信號(hào)
Django中提供了“信號(hào)調(diào)度”,用于在框架執(zhí)行操作時(shí)解耦。通俗來講,就是一些動(dòng)作發(fā)生的時(shí)候,
信號(hào)允許特定的發(fā)送者去提醒一些接受者

Model signals
    pre_init                    # django的modal執(zhí)行其構(gòu)造方法前,自動(dòng)觸發(fā)
    post_init                   # django的modal執(zhí)行其構(gòu)造方法后,自動(dòng)觸發(fā)
    pre_save                    # django的modal對象保存前,自動(dòng)觸發(fā)
    post_save                   # django的modal對象保存后,自動(dòng)觸發(fā)
    pre_delete                  # django的modal對象刪除前,自動(dòng)觸發(fā)
    post_delete                 # django的modal對象刪除后,自動(dòng)觸發(fā)
    m2m_changed                 # django的modal中使用m2m字段操作第三張表(add,remove,clear)前后,自動(dòng)觸發(fā)
    class_prepared              # 程序啟動(dòng)時(shí),檢測已注冊的app中modal類,對于每一個(gè)類,自動(dòng)觸發(fā)
Management signals
    pre_migrate                 # 執(zhí)行migrate命令前,自動(dòng)觸發(fā)
    post_migrate                # 執(zhí)行migrate命令后,自動(dòng)觸發(fā)
Request/response signals
    request_started             # 請求到來前,自動(dòng)觸發(fā)
    request_finished            # 請求結(jié)束后,自動(dòng)觸發(fā)
    got_request_exception       # 請求異常后,自動(dòng)觸發(fā)
Test signals
    setting_changed             # 使用test測試修改配置文件時(shí),自動(dòng)觸發(fā)
    template_rendered           # 使用test測試渲染模板時(shí),自動(dòng)觸發(fā)
Database Wrappers
    connection_created          # 創(chuàng)建數(shù)據(jù)庫連接時(shí),自動(dòng)觸發(fā)
    
對于Django內(nèi)置的信號(hào),僅需注冊指定信號(hào),當(dāng)程序執(zhí)行相應(yīng)操作時(shí),自動(dòng)觸發(fā)注冊函數(shù):

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指上述導(dǎo)入的內(nèi)容


例子:
from django.core.signals import request_finished
from django.dispatch import receiver

@receiver(request_finished)
def my_callback(sender, **kwargs):    
    print("Request finished!")
    
2.自定義信號(hào)
a. 定義信號(hào)
import django.dispatch
pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])

b. 注冊信號(hào)
def callback(sender, **kwargs):
    print("callback")
    print(sender,kwargs)
 
pizza_done.connect(callback)

c. 觸發(fā)信號(hào)
from 路徑 import pizza_done
 
pizza_done.send(sender='seven',toppings=123, size=456)


例子請求后打印一行數(shù)據(jù): 配置在urls.py一層目錄下面的__init__.py文件中
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 test(sender, **kwargs):
    print("request_finished.222")
    print(sender, kwargs)

request_started.connect(test)    #請求開始時(shí)打印
request_finished.connect(test)    #請求結(jié)束后打印

創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開啟,新人活動(dòng)云服務(wù)器買多久送多久。

文章名稱:djangoform表單插件,中間件,緩存,信號(hào)-創(chuàng)新互聯(lián)
鏈接分享:http://bm7419.com/article12/djhggc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、外貿(mào)網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站建設(shè)、品牌網(wǎng)站制作品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作