用户信息
2018-04-11 本文已影响0人
大猪厂
layout: "post"
title: "用户模块"
date: "2018-04-11 09:02"
用户系统
注册
数据表:users.User
前端页面:register.html
注册流程:用户(浏览器)发起请求,django服务器接受请求,对收到的请求进行url解析,分配到users.urls中,users.urls进一步对地址进行解析,调用请求的视图函数(类);
静态请求配置:
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
django确认请求静态文件:请求路径开始部分和STATIC_URL进行对比,相同则认为请求的是静态文件;
django静态文件查找路径:按照STATICFILES_DIRS的路径进行拼接查找,在应用目录下面的static目录下查找;
# /urls.py
from django.conf.urls import url
import user.urls
urlpatterns = [
url(r'^users/',include(users.url,namespace='users'))
]
# /users/urls.py
from django.conf.urls import url
from users import views
urlpatterns = [
url(r'^register$',views.RegisterView.as_view(),name='register')
]
templates配置:
# settings.py
'DIR':[os.path.join(BASE_DIR,'templates')]
views代码:
/users/views.py
from django.views.generic import View
from django.shotcuts import render,redirect
from users.models import User
from django import db
from celery_tasks.tasks import send_active_email
import re
class RegisterView(View):
def get(self,request):
return render(request,"register.html")
def post(self,request):
# 获取参数
username = request.POST.get("username")
password = request.POST.get("pwd")
email = request.POST.get("email")
allow = request.POST.get("allow")
# 参数校验
if not all([username,password,email]):
return redirect(reverse("users:register"))
if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{1,2}$)',email):
return render(request,"register.html",{"message":"邮箱格式不正确"})
if allow != "on":
return render(request,"register.html",{"message":"请勾选协议"})
# 业务逻辑
try:
user = User.objects.create_user(username,email,password)
except db.IntegrityError:
return render(request,"register.html",{"message":"用户已经注册"})
user.is_active = False
user.save()
# 生成token
token = user.generate_active_token()
# 发送激活邮件
send_active_email.delay(email,user_name,token)
# 返回前端页面
return redirect(reverse("goods:index"))
template页面代码略
### 激活
celery配置
生成激活码:
# /users/models.py
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from utils.models import BaseModel
class User(AbstractUser,BaseModel):
def generate_active_token(self):
s = Serialize(settings.SECRET_KEY,3600)
data = {"confirm":self.id}
token = s.dumps(data)
return token.decode()
url配置
# /users/urls.py
url(r'^active/(?P<token>.+)$',views.ActiveView.as_view(),name='active')
views代码:
# users/views.py
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serialize,SignatureExpired
from django.http import HttpResponse
class ActiveView(View):
def get(self,request,token):
s = Serialize(settings.SECRET_KEY,3600)
try:
ret = s.loads(token)
except SignatureExpired:
return HttpResponse("激活链接已过期")
user_id =ret.get("confirm")
try:
user = User.objects.get(id=user_id)
user.is_active = True
user.save()
except User.DoesNotExist;
return HttpResponse("用户不存在")
return HttpResponse("这是登陆页面")
发送邮件
邮箱网页中需要开启smtp协议
# settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.126.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = 'funkypython@126.com'
EMAIL_HOST_PASSWORD = 'MFB012315sf'
EMAIL_FROM = '天天项目<tiantian@126.com>'
celery代码:
# /celety_tasks/tasks.py
from celery import Celery
import os
os.emviron["DJANGO_SETTINGS_MODEL"] = "dailyfresh.settings"
# 放到celery服务器上时将注释打开,在django运行时不需要,在celery服务器上面运行时,celery执行自己的脚本文件,所以需要初始化一下django的变量;
# import django
# django.setup()
from django.core.mail import send_mail
from django.conf import settings
# 创建celery应用对象
app = Celery("celery_tasks.tasks",broker="redis://10.211.55.5/4")
@app.task
def send_active_email(to_email,user_name,token):
"""发送激活邮件"""
subject = "天天生鲜用户激活" # 标题
body = "" # 文本邮件体
sender = settings.EMAIL_FROM # 发件人
receiver = [to_email] # 接收人
html_body = '<h1>尊敬的用户 %s,感谢您注册天天生鲜</h1>'\
'<br/><p>请点击此链接激活账号<a href="http://127.0.0.1:8000/users/active/%s">'\
'http://127.0.0.1:8000/users/active/%s</a></p>' % (user_name,token,token)
send_mail(subject,body,sender,receiver,html_message=html_body)
开启celery服务器
celery -A celery_tasks.tasks worker -l info
#celery -A celery_tasks.tasks worker --loglevel=info
指明把tasks这个任务对象交给worker处理,如果运行过程中出现问题,就已loglevel=info的规格显示出来,即普通文件的形式;
登录
数据表:user.models.User
前端页面: login.html
登录流程:用户(浏览器)发送请求,django服务器接受请求,对收到的请求进行url解析,分配到user.urls中,user.urls进一步对地址进行解析,调用请求的视图函数(类);
缓存配置:django封装了Login方法,但是默认将登录用户的信息session存放到MySQL中,本项目更改到redis中;
# 缓存
CACHES = {
"default":{
"BACKEND":"django_redis.cache.RedisCache",
"LOCAATION":"redis://127.0.0.1:6379/5",
"OPTIONS":{
"CLIENT_CLASS":"django_redis.client.DefaultClient",
}
}
}
# Session
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHS_ALIAS = "default"
配置url:
# /users/urls.py
from django.conf.urls import url
from users import views
urlpatterns = [
url(r'^login$',views.LoginView.as_view(),name='login'),
]
视图函数:
/users/views.py
from django.views.generic import View
from django.shotcuts import render,redirect
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login,logout
class LoginView(View):
def get(self,request):
return render(request,"login.html")
def post(self,request):
# 获取参数
username = request.POST.get("username")
password = request.POST.get("word")
remembered = request.POST.get("remembered")
# 校验参数
if not all([username,password]):
return redirect(recerse("users:login"))
user = authenticate(username=username,password=password)
if user is None:
return render(request,"login.html",{"errmsg":"用户名或密码错误"})
if user.is_active is False:
return render(request,"login.html",{"errmsg":"用户未激活"})
# 业务处理
login(request,user)
if remembered != "on":
request.session.set_expiry(0)
else:
request.session.set_expiry(None)
# 返回用户
return redirect(reverse("goods:index"))
templates页面略
退出
删除浏览器中的cookie和session_id
配置url:
# /users/urls.py
from django.urls import url
from users import views
urlpatterns = [
url(r'^logout$',views.LogoutView.as_view(),name='logout'),
]
# /users/views.py
class LogoutView(View);
def get(self,request):
logout(request)
return redirect(reverse("goods;index"))