一、form插件
django form表單類(lèi)的字段和插件,字段用于表單驗(yàn)證獲取數(shù)據(jù),插件用來(lái)生成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, 大長(zhǎng)度
min_length=None, 最小長(zhǎng)度
strip=True 是否移除用戶(hù)輸入空白
IntegerField(Field)
max_value=None, 大值
min_value=None, 最小值
DecimalField(IntegerField)
max_value=None, 大值
min_value=None, 最小值
max_digits=None, 總長(zhǎng)度
decimal_places=None, 小數(shù)位長(zhǎng)度
RegexField(CharField)
regex, 自定制正則表達(dá)式
max_length=None, 大長(zhǎng)度
min_length=None, 最小長(zhǎng)度
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),目錄下文件顯示在頁(yè)面中
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對(duì)象
phone = fields.CharField(
validators=[RegexValidator(r'^[0-9]+$', '請(qǐng)輸入數(shù)字'), RegexValidator(r'^159[0-9]+$', '數(shù)字必須以159開(kāi)頭')]
)
方式二:函數(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)前類(lèi)的方法中,方法名稱(chēng)要求: clean_phone方法
phone = fields.CharField()
def clean_phone(self):
# 去取用戶(hù)提交的值:可能是錯(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
注冊(cè)確認(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è)類(lèi)
中間件中一共有四個(gè)方法:
process_request
process_view
process_exception
process_response
已經(jīng)添加中間件M1和M2
中間件執(zhí)行時(shí)機(jī): 請(qǐng)求到來(lái),請(qǐng)求返回時(shí)
- 應(yīng)用:
- 請(qǐng)求日志
- 用戶(hù)登錄認(rèn)證

四、緩存
由于Django是動(dòng)態(tài)網(wǎng)站,所有每次請(qǐng)求均會(huì)去數(shù)據(jù)進(jìn)行相應(yīng)的操作,當(dāng)程序訪(fǎng)問(wèn)量大時(shí),耗時(shí)必然會(huì)
更加明顯,最簡(jiǎn)單解決方式是使用:緩存,緩存將一個(gè)某個(gè)views的返回值保存至內(nèi)存或者memcache中,
5分鐘內(nèi)再有人來(lái)訪(fǎng)問(wèn)時(shí),則不再去執(zhí)行view中的操作,而是直接從內(nèi)存或者Redis中之前緩存的內(nèi)容拿
到,并返回
Django中提供了6種緩存方式:
1. 開(kāi)發(fā)調(diào)試
2. 內(nèi)存
3. 文件
4. 數(shù)據(jù)庫(kù)
5. Memcache緩存(python-memcached模塊)
6. Memcache緩存(pylibmc模塊)
a.開(kāi)發(fā)調(diào)試
# 此為開(kāi)始調(diào)試用,實(shí)際內(nèi)部不做任何操作
# 配置:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache', # 引擎
'TIMEOUT': 300, # 緩存超時(shí)時(shí)間(默認(rèn)300,None表示永不過(guò)期,0表示立即過(guò)期)
'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ù)庫(kù)緩存
# 此緩存將內(nèi)容保存至數(shù)據(jù)庫(kù)
# 配置:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table', # 數(shù)據(jù)庫(kù)表
}
}
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)過(guò)一系列的認(rèn)證等操作,如果內(nèi)容在緩存中存在,則使用FetchFromCacheMiddleware獲
取內(nèi)容并返回給用戶(hù),當(dāng)返回給用戶(hù)之前,判斷緩存中是否已經(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í)解耦。通俗來(lái)講,就是一些動(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對(duì)象保存前,自動(dòng)觸發(fā)
post_save # django的modal對(duì)象保存后,自動(dòng)觸發(fā)
pre_delete # django的modal對(duì)象刪除前,自動(dòng)觸發(fā)
post_delete # django的modal對(duì)象刪除后,自動(dòng)觸發(fā)
m2m_changed # django的modal中使用m2m字段操作第三張表(add,remove,clear)前后,自動(dòng)觸發(fā)
class_prepared # 程序啟動(dòng)時(shí),檢測(cè)已注冊(cè)的app中modal類(lèi),對(duì)于每一個(gè)類(lèi),自動(dòng)觸發(fā)
Management signals
pre_migrate # 執(zhí)行migrate命令前,自動(dòng)觸發(fā)
post_migrate # 執(zhí)行migrate命令后,自動(dòng)觸發(fā)
Request/response signals
request_started # 請(qǐng)求到來(lái)前,自動(dòng)觸發(fā)
request_finished # 請(qǐng)求結(jié)束后,自動(dòng)觸發(fā)
got_request_exception # 請(qǐng)求異常后,自動(dòng)觸發(fā)
Test signals
setting_changed # 使用test測(cè)試修改配置文件時(shí),自動(dòng)觸發(fā)
template_rendered # 使用test測(cè)試渲染模板時(shí),自動(dòng)觸發(fā)
Database Wrappers
connection_created # 創(chuàng)建數(shù)據(jù)庫(kù)連接時(shí),自動(dòng)觸發(fā)
對(duì)于Django內(nèi)置的信號(hào),僅需注冊(cè)指定信號(hào),當(dāng)程序執(zhí)行相應(yīng)操作時(shí),自動(dòng)觸發(fā)注冊(cè)函數(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. 注冊(cè)信號(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)
例子請(qǐng)求后打印一行數(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) #請(qǐng)求開(kāi)始時(shí)打印
request_finished.connect(test) #請(qǐng)求結(jié)束后打印創(chuàng)新互聯(lián)www.cdcxhl.cn,專(zhuān)業(yè)提供香港、美國(guó)云服務(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)已開(kāi)啟,新人活動(dòng)云服務(wù)器買(mǎi)多久送多久。
文章名稱(chēng):djangoform表單插件,中間件,緩存,信號(hào)-創(chuàng)新互聯(lián)
鏈接分享:http://www.chinadenli.net/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)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容