python3之天天生鲜项目(初学者)3

python

用户模块

实现:

  注册----登录    功能     验证

这里views.py使用类方法

from django.conf.urls import url

from users import views

urlpatterns = [

url(r"^register", views.RigisterView.as_view(),name="register"),

]

class RigisterView(View):

def get(self,request):

return render(request,"register.html")

def post(self,request):

# 获取注册信息

username = request.POST.get("user_name")

password = request.POST.get("pwd")

cpassword = request.POST.get("cpwd")

email = request.POST.get("email")

allow = request.POST.get("allow")

# 数据处理 验证数据完整性

ifnot all([username, password, cpassword, email, allow]):

return render(request, "register.html", {"errmsg": "数据不完整"})

# 验证密码是否一致

if password != cpassword:

return render(request, "register.html", {"errmsg": "密码不一致"})

# 验证邮箱 # [w.-]+ 指一个或多个[w.-] 这样的字符,如 "aaa" "-ab" "c" "s._-l"

ifnot re.match(r"^[a-z0-9][w.-]*@[a-z0-9-]+(.[a-z]{2,5}){1,2}$", email):

return render(request, "register.html", {"errmsg": "邮箱格式不正确"})

# 验证是否勾选协议

if allow != "on":

return render(request, "register.html", {"errmsg": "请同意协议"})

# 验证用户名是否存在(这里使用不重复户用名)

try:

user = User.objects.get(username=username)

except User.DoesNotExist:

user = None # 如果不存在 赋值为空

if user: # 如果存在

return render(request, "register.html", {"errmsg": "用名已存在"})

# 保存到数据库 mysql

user = User.objects.create_user(username, email, password)

user.is_active = False # 0 也可以 邮箱未验证设置为0

user.save()

# 邮箱激活

# 获取token

token = user.gennerate_activeate_token()

# 发送邮件

celery_send_email.delay(email,token)

return render(request, "login.html")

注册 ---------  功能    mysql.......celery.....redis........

这里使用    异步邮箱验证(celery)   前面有讲到 异步实现的方法  

    代理redis 库4的信息  

填写注册信息

 

mysql查看注册信息  

 收到激活链接

 接下来就是要实现邮箱验证  active  

from django.conf.urls import url

from users import views

urlpatterns = [

url(r"^activate(?P<token>.+)/", views.activate,name="activate"),

]

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

def
activate(request,token):

serializer = Serializer(settings.SECRET_KEY,3600) # 设置3600秒过期

try:

json_str = serializer.loads(token)

except:

return HttpResponse("连接已过期")

user_id = json_str["confirm"]try:

user = User.objects.get(id=user_id)

except User.DoesNotExist:

return HttpResponse("账号存在异常")

#邮箱验证通过 修改

user.is_active = True

user.save()

return render(request,"login.html")

后期要用它来 登录验证 

.....

以上是 python3之天天生鲜项目(初学者)3 的全部内容, 来源链接: utcz.com/z/531201.html

回到顶部