PYTHON 九月 20, 2019

第5节、缓存-发送邮件

文章字数 15k 阅读约需 13 mins. 阅读次数 1000000

一、配置缓存

settings.py

#添加缓存的配置
CACHES = {
    'default':{
        #缓存的位置
        'BACKEND':'django.core.cache.backends.db.DatabaseCache',
        'LOCATION':'my_cache_table',#缓存的表
    }
}

创建缓存表

python3 manage.py createcachetable my_cache_table

库中就会出现my_cache_table表

实例:

from django.shortcuts import render
from django.views.decorators.cache import cache_page
from App.models import User


#展示所有用户数据的方法
@cache_page(60)
def showUser(req):
    print('----能看到我几次?------')
    u = User.objects.all()
    return render(req,'showUser.html',{'data':u})

二、手动添加缓存

  1. cache.set 设置缓存
    • key
    • value
    • timeout
  2. cache.get(key) 获取缓存
  3. cache.get_many() 获取多条缓存
  4. cache.set_many() 设置多条缓存
  5. cache.delete() 删除缓存
  6. cache.clear 清空缓存

实例

from django.core.cache import cache

def showUser(req):
    html = cache.get('showUser')
    if html:
        return HttpResponse(html)
    else:
        print('----能看到我几次?------')
        u = User.objects.all()
        tem = loader.get_template('showUser.html')
        html = tem.render({'data': u})
        cache.set('showUser',html,60)
        return HttpResponse(html)

三、使用redis进行缓存

安装:

sudo pip3 install django-redis

配置settings.py

#添加缓存的配置
CACHES = {
    'default':{
        #reids进行缓存
        'BACKEND':'django_redis.cache.RedisCache',
        'LOCATION':'redis://127.0.0.1:6379/1',#设置缓存的数据库
    }
}

其它位置的代码不需要改变 重新访问路由地址即可

四、发送邮件

*注意:发送邮件报错:Mail from must equal authorized user,则需要设置临时环境变量 *

  • windows:set MAIL_USER=用作发送邮件的邮箱账号
  • linux:export MAIL_USER=用作发送邮件的邮箱账号

(1) 发送单封邮件

settings.py配置

#发送邮件配置
EMAIL_HOST = os.environ.get('MAIL_SERVER','smtp.1000phone.com')
EMAIL_HOST_USER = os.environ.get('MAIL_USER','xialigang@1000phone.com')
EMAIL_HOST_PASSWORD = os.environ.get('MAIL_PASSWORD','123456')

view.py

from django.shortcuts import render,HttpResponse
from django.core.mail import send_mail
import os

def sendMail(req):
    send_mail(
        'Subject here',
        'Here is the message.',
        os.environ.get('MAIL_USER'),
        ['793390457@qq.com'],
        fail_silently=False,
    )
    return HttpResponse('发送邮件')

(2) 发送多封邮件

def sendManyPeople(req):
    message1 = ('Subject here', 'Here is the message', os.environ.get('MAIL_USER'), ['948807313@qq.com'])
    message2 = ('Another Subject', 'Here is another message', os.environ.get('MAIL_USER'), ['793390457@qq.com'])
    send_mass_mail((message1, message2), fail_silently=False)
    return HttpResponse('发送多封邮件')

send_mass_mail()send_mail()

之间的主要区别send_mass_mail()和 send_mail()是 send_mail()打开每一个它的执行时间的邮件服务器的连接,同时send_mass_mail()使用其所有消息的单个连接。这使得 send_mass_mail()效率稍高。

(3) 发送html文本内容的邮件

#发送html文本
def sendHtmlMail(req):
    from django.core.mail import EmailMultiAlternatives

    subject, from_email, to = 'hello', os.environ.get('MAIL_USER'), '948807313@qq.com'
    html_content = '<p>This is an <strong><a href="http://www.baidu.com">百度</a></strong> message.</p>'
    msg = EmailMultiAlternatives(subject,from_email=from_email,to=[to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
    return HttpResponse('发送html文本的邮件')

五、JsonResponse 响应json数据

作用: 返回json数据 用于异步请求

导入

from django.http import JsonResponse

使用

def test(req):
    json = JsonResponse({'name':'zhangsan','age':18})
    return HttpResponse(json) #{"name":"zhangsan","age":18}

六、邮件进行注册认证

  1. 创建用户模型
  2. 创建视图函数 路由地址
  3. 创建模板
  4. 接受表单数据 添加到数据库
  5. 生成token值
  6. 发送邮件 渲染邮件模板
  7. 邮件激活
  8. 改变用户状态
  9. 登录

(1) 创建User模型

class User(models.Model):
    username = models.CharField(max_length=20)
    password_hash = models.CharField(max_length=80)
    sex = models.BooleanField(default=True)
    age = models.IntegerField(default=20)
    # email = models.CharField(max_length=40,unique=True)
    email = models.CharField(max_length=40)
    icon = models.CharField(max_length=36,default='default.jpg')
    createTime = models.DateTimeField(auto_now_add=True)
    confirm = models.BooleanField(default=False)
    def __str__(self):
        return self.username
    class Meta:
        db_table = 'user'

(2) 添加密码加密的装饰器

from django.contrib.auth.hashers import make_password,check_password

@property
def password(self):
    raise AttributeError
    #密码加密
@password.setter
def password(self,password):
    self.password_hash = make_password(password)

(3) 创建表单 register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <style>
        table{
            margin: auto;
            border-collapse: collapse;
        }
        td{
            width: 300px;
            height:40px;
            border:1px solid aqua;
        }
    </style>
</head>
<body>
<center><h4><a href="{% url 'Aft:login' %}">登录</a> | <a href="{% url 'Aft:register' %}">注册</a></h4></center>

<form action="{% url 'Aft:register' %}" method="post">
    {% csrf_token %}
<table>
    <caption><h2>注册</h2></caption>
    <tr>
        <td>用户名:</td>
        <td><input type="text" name="username" minlength="6" maxlength="12" placeholder="请输入用户名"></td>
    </tr>
    <tr>
        <td>密码:</td>
        <td><input type="password" name="userpass" minlength="6" maxlength="12" placeholder="请输入密码"></td>
    </tr>
    <tr>
        <td>激活邮箱:</td>
        <td><input type="email" name="email" maxlength="40" placeholder="请输入激活账户的邮箱地址..."></td>
    </tr>
    <tr>
        <td><input type="submit" value="submit"></td>
        <td><input type="reset" value="reset"></td>
    </tr>
</table>
</form>
</body>
</html>

(4) 添加注册路由地址

    url(r'^register/$',views.register,name='register'),

(5) 视图函数

#注册
def register(req):
    if req.method == 'GET':
        return render(req, 'register.html')
    if req.method == 'POST':
        u = User(username=req.POST.get('username'),password=req.POST.get('userpass'),email=req.POST.get('email'))
        u.save()
        token = u.get_token() #获取token
        # print(token)
        url = 'http://'+req.get_host()+reverse('Aft:activate',args=[token]) #生成激活的链接地址
        subject, from_email, to = '账户激活', os.environ.get('MAIL_USER'),u.email
        html_content = loader.get_template('mail/activate.html').render({'url': url, 'username': u.username})
        msg = EmailMultiAlternatives(subject, from_email=from_email, to=[to])
        msg.attach_alternative(html_content, "text/html")
        msg.send() #发送邮件
        return HttpResponse('<meta http-equiv="refresh" content="2;url=http://127.0.0.1:8000/login/">注册成功')

(6) 在models添加生成token的代码

import uuid,hashlib
from django.core.cache import cache
#拿到生成的token值
def get_token(self):
    myuuid = uuid.uuid4() #生成唯一的uuid字符串
    md5 = hashlib.md5()
    md5.update(str(myuuid).encode('utf-8'))
    token = md5.hexdigest() #生成惟一的加密字符串
    # print(token)
    cache.set(token, {'id': self.id}, 3600) #设置存储token对应值的过期时间
    return token

(7) 邮寄激活的模板

mail/activate.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>激活</title>
</head>
<body>
<h2>欢迎:{{ username }}</h2>
<h4>请点击右侧激活 进行最后一步的激活操作 <a href="{{ url }}">激活</a></h4>
</body>
</html>

(8) 在模型中添加激活的代码

#检测token是否存在
@staticmethod
def check_token(token):
    try:
        id = cache.get(token)['id']
        u = User.objects.get(pk=id)
        u.confirm = True
        u.save()
        return True
    except:
        return False

(9) 添加激活的视图函数

#激活操作
def activate(req,token):
    if User.check_token(token):
        return HttpResponse('激活成功')
    else:
        return HttpResponse('激活失败')

(10) 添加登录的模板 login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <style>
        table{
            margin: auto;
            border-collapse: collapse;
        }
        td{
            width: 300px;
            height:40px;

        }
        input{
            border-radius: 5px;
            box-shadow: 0 0 2px 2px aqua;
            color: red;
            font-size: 16px;
            width:200px;
            height: 25px;
        }
    </style>
</head>
<body>
<form action="{% url 'Aft:login' %}" method="post">
<center><h4><a href="{% url 'Aft:login' %}">登录</a> | <a href="{% url 'Aft:register' %}">注册</a></h4></center>
    {% csrf_token %}
<table>
    <caption><h2>登录</h2></caption>
    <tr>
        <td>用户名:</td>
        <td><input type="text" name="username" minlength="6" maxlength="12" placeholder="请输入用户名"></td>
    </tr>
    <tr>
        <td>密码:</td>
        <td><input type="password" name="userpass" minlength="6" maxlength="12" placeholder="请输入密码"></td>
    </tr>
    <tr>
        <td><input type="submit" value="submit"></td>
        <td><input type="reset" value="reset"></td>
    </tr>
</table>
</form>
</body>
</html>

(11) 在models中添加登录处理的函数

#检测密码
    def checkPassword(self,password):
        return check_password(password,self.password_hash)

(12) 添加登录的视图函数

#登录
def login(req):
    if req.method == 'GET':
        return render(req,'login.html')
    if req.method == 'POST':
        u = User.objects.filter(username=req.POST.get('username')).first()
        if u and u.checkPassword(req.POST.get('userpass')):
            return HttpResponse('登录成功')
        else:
            return HttpResponse('登录失败')

(13) 添加登录的路由地址

url(r'^login/$',views.login,name='login'),

(14) 将登录注册 添加ajax的请求处理


上一篇:
下一篇:
0%