1.settings

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://192.168.8.102:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://192.168.8.102:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "sms_code": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://192.168.8.102:6379/15",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

# 保存 session数据到 Redis中
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"

APPEND_SLASH=False

2.urls.py

    url(r'^check_sms.html', sms.check_sms,name="check_sms"),
    url(r'^sms.html', sms.sms, name="sms"),

3.html

# check_sms.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>sms</title>
    <script src="/static/plugins/jquery.min.js"></script>
    <script>

    </script>
</head>
<body>
<form action="{% url 'check_sms' %}" method="post">
    手机号:<input id="phone_num" type="text" name="phone_num" value="{{ phone }}" style="color: red" readonly="true"><span style="color: #761c19"></span>
    <p></p>&nbsp;&nbsp;&nbsp;码:<input id="check_code" type="text" name="passwd" placeholder="请输入密码"><span style="color: #761c19"></span>
    <p></p>
    <input type="submit" value="登录" class="log">
    {{ cookie_content }}
    {{ session_content }}
    {{ is_login }}
    {{ username }}
    {% csrf_token %}
</form>

</body>
</html>


# sms.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>sms</title>

</head>
<body>
<form action="{% url 'sms' %}" method="post">
    手机号:<input id="phone_num" type="text" name="phone_num" placeholder="请输入手机号"><span style="color: #761c19"></span>
    <p></p>&nbsp;&nbsp;&nbsp;码:<input id="check_passwd" type="text" name="passwd" placeholder="请输入密码">&nbsp;&nbsp;<span style="color: red"></span>
     <p></p>
    验证码:<input id="code" type="text" name="code" placeholder="请输入验证码">&nbsp;&nbsp;<span style="color: red">{{ code }}</span>
    <p></p>
    <input type="submit" value="注册" class="reg">
    {{ cookie_content }}
    {{ session_content }}
    {{ is_login }}
    {{ username }}
    {% csrf_token %}
</form>

</body>
</html>

4.视图 sms.py

'''
# sms_code.py
#!/usr/bin/python env
# coding:utf-8

import random
def code(num=4):
    res = ""
    for i in range(num):
        # 数字0-9
        num1 = str(random.randint(0, 9))
        # 大写字母A-Z
        # a = chr(random.randint(65, 90))
        # 小写字母a-z
        # b = chr(random.randint(97, 122))
        # res += random.choice([num1, b])
        res += random.choice([num1])
    return res
'''


#!/usr/bin/python env
# coding:utf-8
from exta_function import redis_con
from django.shortcuts import redirect, render, HttpResponse
from django_redis import get_redis_connection
from exta_function import sms_code
import json


def sms(request):
    if request.method == "GET":
        code = sms_code.code(6)
        request.session["code"] = code
        return render(request, "sms/sms.html", locals())
    elif request.method == "POST":
        phone_num = request.POST.get("phone_num")
        phone_num1 = "sms_" + str(phone_num)
        passwd = request.POST.get("passwd")
        code = request.POST.get("code")
        conn = get_redis_connection("sms_code")
        keys = conn.keys(phone_num1)
        if keys:
            return HttpResponse("用户已注册过!")

        elif request.session.get("code") == code:
            # 注册功能  
            #                                  手机号 有效期 密码
            # reids 存储数据格式 SETEX sms_18501020304 300 323242
            conn = get_redis_connection("sms_code")
            key = "sms_" + str(phone_num)
            t = 600
            val = passwd
            conn.setex(key, t, val)
            request.session["is_login"] = "true"
            request.session['username'] = 'wangwu'
            request.session["phone"] = phone_num
            session_content = request.session
            cookie_content = request.COOKIES
            print(conn.get(key).decode("utf-8"))
            return redirect("check_sms.html")
        else:
            return HttpResponse("验证码错误")


def check_sms(request):
    if request.method == "GET":
        code = sms_code.code(6)
        phone = request.session["phone"]
        return render(request, "sms/check_sms.html", locals())
    elif request.method == "POST":
        # 验证功能 phone_num check_code
        phone_num = request.POST.get("phone_num")
        passwd = request.POST.get("passwd")
        code = request.session["code"]
        key = "sms_" + str(phone_num)

        conn = get_redis_connection("sms_code")

        print("recv: ", key, passwd)
        print(conn.get(key))
        if not conn.get(key):
            return redirect("sms.html")
        elif conn.get(key) == passwd.encode("utf-8"):
            cookie_content = request.COOKIES
            is_login = request.session["is_login"]
            username = request.session["username"]

            dic_data = {
                "cookie_content": cookie_content,
                "is_login": is_login,
                "username": username,
            }
            print("cookie_content: ", cookie_content)
            print(conn.get(phone_num))

            return HttpResponse(json.dumps(dic_data))
        else:
            return HttpResponse("密码错误")