django项目小记
- django 用户认证
用户登录后才可访问页面地址,否则跳转到登录页面(需要在settings.py 文件中定义LOGIN_URL字段), 跳转后的地址形式:http://127.0.0.1/login?next=要访问的页面地址
1 from django.contrib.auth.decorators import login_required 2 class LoginRequestMixin(object): 3 @classmethod 4 def as_view(cls, **initkwargs): 5 view = super(LoginRequestMixin, cls).as_view(**initkwargs) 6 return login_required(view)
LoginRequestMixin 的使用
from utils.mixin import LoginRequestMixin class UserInfoView(LoginRequestMixin, View): ......
- 加密/解密 token
1 # 安装itsdangerous(pip install itsdangerous) 2 from itsdangerous import TimedJSONWebSignatureSerializer as Serializer 3 from itsdangerous import SignatureExpired # 加密内容过期错误 4 # 秘钥 5 serializer = Serializer(settings.SECRET_KEY, 3600 * 2) 6 # 需要加密的内容 7 info = {'confirm': create_users.id} 8 # 加密 9 token = serializer.dumps(info).decode()
1 serializer = Serializer(settings.SECRET_KEY, 3600 * 2) 2 # 获取解密后的内容 3 info = serializer.loads(token) 4 user_id = info['confirm']
- django发送邮箱
# settings.py文件中配置邮箱信息(使用网易邮箱) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 25 # 发送邮件的邮箱 EMAIL_HOST_USER = 'xxxxxx@163.com' # 邮箱中设置的客户端授权密码 EMAIL_HOST_PASSWORD = 'xxxxxx' # 收件人看到的发件人 EMAIL_FROM = '天天生鲜<xxxxxx@163.com>'
# 使用Celery发送(创建celery_task模块包,新建tasks.py模块), 需要安装celery 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 -A celery_task.tasks worker -l info 命令
- 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 ......
# django-redis 拓展内容
1 from django_redis import get_redis_connection 2 # 连接redis 3 conn = get_redis_connection('default') 4 history_key = 'history_%d'% user.id # 列表 [1, 2, 3] 5 cart_key = 'cart_%d' % user.id #哈希字典保存数据{1:2,2:4} 6 # 获取列表中前5个值lrange(key,start,stop) 7 conn.lrange(history_key,0,4) 8 # 移除列表中所有值为4 lrem(key, 0, value) 0表示所有 9 conn.lrem(history_key,0,4) 10 # 从左边插入列表 11 conn.lpush(history_key, 4) 12 # 截取列表中前5个值 13 conn.ltrim(history_key, 0, 4) 14 # 获取哈希字典长度hlen(name) 15 conn.hlen(cart_key) 16 # 获取哈希字典所有键值对 hgetall(name) 17 conn.hgetall(cart_key) 18 # 获取关键字为1的值hget(name, key) 19 conn.hget(cart_key, 1) 20 # 获取所有值的列表 hvals(name) 21 conn.hvals(cart_key) 22 # 设置关键字2的值为4 hset(name, key, value) 23 conn.hset(cart_key, 2, 4) 24 # 删除关键字2的值 hdel(name, key) 25 conn.hdel(cart_key, 2)
- 分页
# 数据分页 paginator = Paginator(orders, 1) try:
# 当前页 page = int(page) except Exception as e: page = 1 # num_pages 总页数 if page > paginator.num_pages: page = 1 orders_page = paginator.page(page) # 页码控制 num_page = paginator.num_pages if num_page < 5: pages = range(1, num_page + 1) elif page <= 3: pages = range(1, 6) elif num_page - page <= 2: pages = range(num_page - 4, num_page + 1) else: pages = range(page - 2, page + 3)
# 前端渲染
# previous_page_number 前一页页码
# next_page_number 后一页页码
# number 当前页页码
<div class="pagenation"> {% if orders_page.has_previous_page %} <a href="{% url 'user:order' orders_page.previous_page_number %}"> < 上一页 </a> {% endif %} {% for pindex in pages %} {% if pindex == orders_page.number %} <a href="{% url 'user:order' pindex %}" class="active">{{ pindex }}</a> {% else %} <a href="{% url 'user:order' pindex %}">{{ pindex }}</a> {% endif %} {% endfor %} {% if orders_page.has_next_page %} <a href="{% url 'user:order' orders_page.next_page_number %}">下一页></a> {% endif %}
</div>