django 要点

1. django 用户认证

用户登录后才可访问页面地址,否则跳转到登录页面(需要在settings.py 文件中定义LOGIN_URL字段), 跳转后的地址形式:http://127.0.0.1/login?next=要访问的页面地址
from django.contrib.auth.decorators import login_required
class LoginRequestMixin(object):
    @classmethod
    def as_view(cls, **initkwargs):
        view = super(LoginRequestMixin, cls).as_view(**initkwargs)
        return login_required(view)
LoginRequestMixin 的使用
from utils.mixin import LoginRequestMixin

class UserInfoView(LoginRequestMixin, View):
    ......

2. 加密/解密 token

加密
# 安装itsdangerous(pip install itsdangerous)
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired # 加密内容过期错误
# 秘钥
serializer = Serializer(settings.SECRET_KEY, 3600 * 2)
# 需要加密的内容
info = {'confirm': create_users.id}
# 加密
token = serializer.dumps(info).decode()
解密
serializer = Serializer(settings.SECRET_KEY, 3600 * 2)
# 获取解密后的内容
info = serializer.loads(token)
user_id = info['confirm']

3. Django发送邮箱

settings.py文件中配置邮箱信息(使用网易邮箱)

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
# 发送邮件的邮箱
EMAIL_HOST_USER = 'xxxx@163.com'
# 邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = 'xxxxx'
# 收件人看到的发件人
EMAIL_FROM = '天天生鲜<xxxx@163.com>'

Celery异步发送(创建celery_task模块包,新建tasks.py模块)

from celery import Celery
from django.conf import settings
from django.core.mail import send_mail

# 实例celery对象(中间人)
app = Celery('celery_task.tasks', broker='redis://127.0.0.1:6379/8')
# 定义任务函数
@app.task
def send_register_active_email(to_email, username, token):
    """发送激活邮件"""
    subject = '天天生鲜欢迎信息'
    message = '<h1>%s, 欢迎您成为天天生鲜的会员</h1>请点击下面链接激活您的账号<br />' \
              '<a href="http://127.0.0.1:8000/user/active/%s">激活</a>' % (username, token)
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    send_mail(subject=subject, message='', html_message=message, from_email=sender, recipient_list=receiver)

视图类中使用任务函数

from celery_task.tasks import send_register_active_email
class RegisterView(View):
    ......
    # 发邮件
    send_register_active_email.delay(email, user_name, token)
    return redirect('user:login')

Celery任务的使用(拷贝项目到其他盘符或服务器,修改tasks文件,添加如下内容)

import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings')
django.setup()

在celery模块所在父目录下执行 celery -A celery_task.tasks worker -l info 启动工作者

4. 使用redis保存缓存

settings.py 配置redis

# Django 缓存配置 并安装django-redis模块包(pip install django-redis)
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
# Session 配置
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

设置缓存

class LoginView(View):
      ........
      if users.is_active:
          # 记录登录用户状态
          login(request, user=users)
          next_url = request.GET.get('next', 'goods:home')
          response = redirect(next_url)
          if remember == 'on':
              # 设置缓存
              response.set_cookie('username', users.username, max_age=7 * 24 * 3600)
          else:
              # 删除缓存
              response.delete_cookie('username')
          return response
      ......

拓展redis内容

from django_redis import get_redis_connection
# 连接redis
conn = get_redis_connection('default')
history_key = 'history_%d'% user.id # 列表 [1, 2, 3]
cart_key = 'cart_%d' % user.id #哈希字典保存数据{1:2,2:4}
# 获取列表中前5个值lrange(key,start,stop)
conn.lrange(history_key,0,4)
# 移除列表中所有值为4 lrem(key, 0, value) 0表示所有
conn.lrem(history_key,0,4)
# 从左边插入列表
conn.lpush(history_key, 4)
# 截取列表中前5个值
conn.ltrim(history_key, 0, 4)
# 获取哈希字典长度hlen(name)
conn.hlen(cart_key)
# 获取哈希字典所有键值对 hgetall(name)
conn.hgetall(cart_key)
# 获取关键字为1的值hget(name, key)
conn.hget(cart_key, 1)
# 获取所有值的列表 hvals(name)
conn.hvals(cart_key)
# 设置关键字2的值为4 hset(name, key, value)
conn.hset(cart_key, 2, 4)
# 删除关键字2的值 hdel(name, key)
conn.hdel(cart_key, 2)

版权声明:本文为netalen原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/netalen/p/11491784.html