django 發(fā)送郵件和緩存的實現(xiàn)代碼
發(fā)送郵件
概述:Django中內(nèi)置了郵件發(fā)送功能,發(fā)送郵件需要使用SMTP服務(wù),常用的免費服務(wù)器有:163、126、QQ
- 注冊并登陸163郵箱
- 打開POP3/SMTP服務(wù)與IMAP/SMTP服務(wù)
- 重置授權(quán)密碼
配置
#郵件發(fā)送 EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.163.com' EMAIL_PORT=25 #發(fā)送郵件的郵箱 EMAIL_HOST_USER='clement@163.com' #郵箱的授權(quán)密碼 EMAIL_HOST_PASSWORD='xxxxxx' #收件人看到的發(fā)件人 EMAIL_FROM='DAI<clement@163.com>'
發(fā)送
send_mail(subject, message, from_email, recipient_list)
from django.conf import settings
from django.core.mail import send_mail
def sendMail(request):
msg = '<a rel="external nofollow" >點擊激活</a>'
send_mail("注冊激活","",settings.EMAIL_FROM,["clement@163.com"],html_message=msg)
return HttpResponse("郵件已發(fā)送")
緩存
概述:對于中等流量的網(wǎng)站來說,盡可能的減少開銷是非常必要的。緩存數(shù)據(jù)就是為了保存那些需要很多計算資源的結(jié)果,這樣的話就不必在下次重復(fù)消耗計算資源。
Django自帶了一個健壯的緩存系統(tǒng)來保存動態(tài)頁面,避免每次請求都重新計算。
Django提供了不同級別的緩存策略,可以緩存特定的視圖的輸出、可以僅僅緩存那些很難計算出來的部分、或者緩存整個網(wǎng)站
設(shè)置緩存
通過設(shè)置決定把數(shù)據(jù)緩存在哪里,是數(shù)據(jù)庫中、文件系統(tǒng)中還是內(nèi)存中
默認(rèn)緩存
CACHES={
'default':{
'BACKEND':'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT':60
}
}
參數(shù)TIMEOUT:緩存的默認(rèn)過期時間,以秒為單位
- 默認(rèn)為300秒
- 設(shè)置為None,表示永不過期
- 設(shè)置為0造成緩存立即失效
將緩存存儲到redis
默認(rèn)使用redis中的1數(shù)據(jù)庫
安裝
pip install django-redis-cache
配置
CACHES={
'default':{
'BACKEND':'redis_cache.cache.RedisCache',
'LOCATION':'localhost:6379',
'TIMEOUT':60
}
}
單個view緩存
django.views.decorators.cache.cache_page裝飾器用于對視圖的輸出進行緩存
from django.views.decorators.cache import cache_page
@cache_page(60 * 2)
def index(request):
# return HttpResponse("sunck is a good man")
return HttpResponse("sunck is a nice man")
模板片段緩存
cache標(biāo)簽: 參數(shù)
- 緩存時間,以秒為單位
- 給緩存片段起名字
{#{% load static from staticfiles %}#}
{% load static %}
{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主頁</title>
{# <link rel="stylesheet" type="text/css" href="/static/css/index.css" rel="external nofollow" >#}
<link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}" rel="external nofollow" >
</head>
<body>
<h1>sunck is a nice man</h1>
{% cache 120 sunck %}
<h1>nice man</h1>
<!--<h1>good man</h1>-->
{% endcache %}
</body>
</html>
底層的緩存API
from django.core.cache import cache
- 設(shè)置:cache.set(鍵, 值, 有效時間)
- 獲?。篶ache.get(鍵)
- 刪除:cache.delete(鍵)
- 清空:cache.clear()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決Pytorch修改預(yù)訓(xùn)練模型時遇到key不匹配的情況
這篇文章主要介紹了解決Pytorch修改預(yù)訓(xùn)練模型時遇到key不匹配的情況,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
一步真實解決AttributeError:‘Upsample‘?object?has?no?attribute‘
這篇文章主要介紹了解決解決AttributeError:?‘Upsample‘?object?has?no?attribute?‘recompute_scale_factor‘的問題,本文給大家介紹的非常想詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06

