python3+django2 开发易语言网络验证(中)
Posted 雪落忆海
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3+django2 开发易语言网络验证(中)相关的知识,希望对你有一定的参考价值。
第四步:网络验证的逻辑开发
1.将model注册到adminx.py中
1.在apps/yanzheng目录下新建admin.py 文件,添加代码:
import xadmin from xadmin import views from .models import Cards class BaseSetting(object): """ 引入更换主题功能 """ enable_themes = True use_bootswatch = True class GlobalSettings(object): """ 页头和页脚 """ site_title = "雪易网络验证后台" site_footer = "雪易网络验证" # menu_style = "accordion"#如果加上,后台的菜单会变成下拉式 class CardsAdmin(object): list_display = [\'user\', \'kacode\', \'time\', \'is_used\'] search_fields = [\'user\', \'kacode\', \'time\', \'is_used\'] list_filter = [\'user\', \'kacode\', \'time\', \'is_used\'] xadmin.site.register(Cards, CardsAdmin) xadmin.site.register(views.BaseAdminView, BaseSetting) xadmin.site.register(views.CommAdminView, GlobalSettings)
2.修改apps/yanzheng/apps.py为:
from django.apps import AppConfig class YanzhengConfig(AppConfig): name = \'yanzheng\' verbose_name=\'验证\'
这时,再重启项目,登录到http://127.0.0.1:8000/xadmin/ 发现数据表已经出现在了后台菜单中,同时页头和页尾也变了。
2.网络验证几个功能的开发:
功能分析:
1、注册功能
2、登录功能
3、心跳包功能
4、生产充值卡密功能
5、充值功能
6、修改密码功能
显然是要跨站post的,所以到settings.py中把csrf关了:
MIDDLEWARE = [ \'django.middleware.security.SecurityMiddleware\', \'django.contrib.sessions.middleware.SessionMiddleware\', \'django.middleware.common.CommonMiddleware\', #屏蔽掉下面这一行,跨站post才可以正常进行,不然会403错误 #\'django.middleware.csrf.CsrfViewMiddleware\', \'django.contrib.auth.middleware.AuthenticationMiddleware\', \'django.contrib.messages.middleware.MessageMiddleware\', \'django.middleware.clickjacking.XFrameOptionsMiddleware\', ]
1.注册功能:
1.在apps/yanzheng/目录下新建form.py文件用于post提交上来数据的初步验证,写入验证注册信息的代码:
from django import forms from .models import UserProfile class RegisterForm(forms.Form): """注册信息的验证""" uid = forms.CharField(required=True, max_length=150, error_messages={ \'required\': \'用户名不能为空.\', \'max_length\':\'用户名过长!\'}) pwd = forms.CharField(required=True, max_length=128, error_messages={ \'required\': \'密码不能为空.\', \'max_length\': "密码过长!"}) def clean(self): """查看用户名是否已经被占用""" uid=self.cleaned_data.get(\'uid\',\'\') u=UserProfile.objects.filter(username=uid) if u: raise forms.ValidationError(\'此用户名已经被占用\') else: return self.cleaned_data
2.在apps/yanzheng/views.py中写相关逻辑代码:
from django.views.generic import View from .form import RegisterForm from django.shortcuts import render,redirect from django.http import HttpResponse from .models import UserProfile, import re import time import datetime class RegisterView(View): """注册""" def post(self,request): reg_form=RegisterForm(request.POST) if reg_form.is_valid(): uid=request.POST.get(\'uid\',\'\') pwd=request.POST.get(\'pwd\',\'\') u=UserProfile() u.username=uid u.password=pwd u.save() msg="注册成功!" else: msg=str(reg_form.errors) if re.findall("注册成功!",msg): return HttpResponse(0) elif re.findall("此用户名已经被占用",msg): return HttpResponse(1) elif re.findall("用户名不能为空",msg): return HttpResponse(2) elif re.findall("用户名过长",msg): return HttpResponse(3) elif re.findall("密码不能为空",msg): return HttpResponse(4) elif re.findall("密码过长",msg): return HttpResponse(5) else: return HttpResponse(6)
3.在urls.py中配置路由:
#...... from yanzheng.views import RegisterView urlpatterns = [ #...... path(\'register\',RegisterView.as_view()), ]
2.登录功能:
1.在form.py 中增加对跟登录有关的post过来的数据的验证代码:
class LoginForm(forms.Form): """登录""" uid = forms.CharField(required=True,error_messages={\'required\': \'用户名不能为空.\',}) pwd = forms.CharField(required=True,error_messages={\'required\': \'密码不能为空.\',})
2.在views.py中添加登录相关的逻辑代码:
from django.views.generic import View from .form import RegisterForm,LoginForm from django.shortcuts import render,redirect from django.http import HttpResponse from .models import UserProfile import re import time import datetime class LoginView(View): """登录""" def post(self,request): login_form=LoginForm(request.POST) if login_form.is_valid(): uid=request.POST.get(\'uid\',\'\') pwd=request.POST.get(\'pwd\',\'\') u=UserProfile.objects.filter(username=uid).first() if u.password==pwd: if not u.is_ban: u_endtime_stamp=int(time.mktime(u.end_time.timetuple())) nowtime_stamp=int(time.time()) if u_endtime_stamp>nowtime_stamp: u.end_time=u.end_time.strftime(\'%Y-%m-%d %H:%M:%S\') msg="登录成功,到期时间:"+u.end_time else: msg="该账户已无剩余时间,请充值!" else: msg=\'此账户已经被冻结\' else: msg=\'密码错误\' else: msg=str(login_form.errors) if re.findall("登录成功",msg): return HttpResponse(msg) elif re.findall("请充值",msg): return HttpResponse(11) elif re.findall("此账户已经被冻结",msg): return HttpResponse(12) elif re.findall("密码错误",msg): return HttpResponse(13) elif re.findall("用户名不能为空",msg): return HttpResponse(14) elif re.findall("密码不能为空",msg): return HttpResponse(15) else: return HttpResponse(16)
3.在urls.py中配置路由:
#...... from yanzheng.views import RegisterView,LoginView urlpatterns = [ #...... path(\'login\',LoginView.as_view()), ]
3.心跳包功能:
1.这个虽然也是post数据,但是个人感觉没必要写form
2.在views.py中相关逻辑代码:
from django.views.generic import View from django.http import HttpResponse from .models import UserProfile import re import time import datetime class PingView(View): """心跳包""" def post(self,request): uid = request.POST.get(\'uid\', \'\') pwd = request.POST.get(\'pwd\', \'\') u = UserProfile.objects.filter(username=uid).first() u_endtime_stamp = int(time.mktime(u.end_time.timetuple())) nowtime_stamp = int(time.time()) if u_endtime_stamp > nowtime_stamp: msg=\'0\' else: msg =\'1\' return HttpResponse(msg)
3.在urls.py中配置路由:
#...... from yanzheng.views import RegisterView,LoginView,PingView urlpatterns = [ #...... path(\'ping\',PingView.as_view()), ]
4.生产充值卡密功能:
1.我特意为充值卡密开发一个网页
1.在templates目录下新建一个html文件:index.html
2.到网上找一些素材模板,装饰网页,css文件放在static/css目录下,js文件放在static/js目录下,图片文件放在media/image目录下
3.为了引用到图片文件,在apps/yanzheng目录下的models.py中,为图片文件的路径建一个表:
class bg(models.Model): image=models.ImageField(upload_to=\'image\',verbose_name=\'背景图\',default=\'image/bg.jpg\')
然后打开Terminal执行经典的数据更新命令:
python manage.py makemigrations
python manage.py migrate
当然,2、3两个步骤,只是为了让生成卡密的网页显得更好看,而好看这件事,仁者见仁智者见智,读者需要自己去网上挑选自己喜欢的网页模板。
4.index.html文件代码:
<!doctype html> {% load staticfiles %} <html lang="en"> <head> <meta charset="UTF-8"> <title>卡密工厂</title> <style> html{ background-image:url({{ MEDIA_URL }}{{ bgt.image }}); background-repeat:no-repeat; background-size:100% 100%; -moz-background-size:100% 100%; } </style> <link rel="stylesheet" type="text/css" href="{% static \'css/index.css\' %}"> </head> <body> <form action="{% url \'card\' %}" method="post"> <input type="hidden" name="key" value="{{ key }}"> <h1 id="info" style="color:red">{{ msg }}</h1> <label for="nums">生产张数:</label> <input type="text" name="nums" id="nums" value="100"/> <label for="unit">时间面值:</label> <select name="unit" id="unit"> <option value="0">小时</option> <option value="1" selected>天</option> <option value="2">星期</option> <option value="3">月</option> <option value="4">三月</option> <option value="5">半年</option> <option value="6">年</option> </select> <input type="submit" value="确认生产" style="cursor:pointer" onclick="info()"> </form> <script type="text/javascript" src="{% static \'js/index.js\' %}"></script> <script> function info() { document.getElementById(\'info\').innerHTML=\'正在生产卡密,请稍等……\' } </script> </body> </html>
5.在views.py中开发 生产卡密功能的get方法:
生成卡密的页面的view不能谁都可以访问,为了安全起见,需要做一个登录验证限制!
我们项目中的views.py里写的每个功能,都是基于类来实现的,而django自带的“登录验证限制访问” 装饰器@login_required是不能使用了。
所以我们要自己定义一个脚本模块来实现基于类的登录限制访问。
首先在apps目录下,新建目录untils,再在该目录下新建py文件:mixin_untils.py 加入代码:
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator class LoginRequiredMinxin(object): @method_decorator(login_required(login_url=\'/xadmin/\')) def dispatch(self,request,*args,**kwargs): return super(LoginRequiredMinxin,self).dispatch(request,*args,**kwargs)
在views.py中开发生产卡密功能的get方法
from django.views.generic import View from .form import RegisterForm,LoginForm from django.shortcuts import render,redirect from django.http import HttpResponse from .models import UserProfile,Cards,bg import re import time import datetime import hashlib from netauth.settings import SECRET_KEY from untils.mixin_utils import LoginRequiredMinxin #...... class CardView(LoginRequiredMinxin,View): """生成卡密""" def get(self,request): key=request.user.password bgt=bg.objects.all().first() return render(request,\'index.html\',{\'bgt\':bgt,\'key\':key})
6.在urls.py中配置路由:
#...... from yanzheng.views import RegisterView,LoginView,PingView,CardView urlpatterns = [ #...... path(\'card\',CardView.as_view(),name=\'card\'), ]
然后运行django项目,浏览器get访问:http://127.0.0.1:8000/card 在登录以后,会看到下面这样一个效果页面:(当然了,再次强调,html文件是必须的,css和js文件,以及图片文件,这些网页的装修方式,读者可以根据自己的审美,自己去网上选素材,或者自己编写。)
2.补齐views.py中生产卡密相关类的post方法:
class CardView(LoginRequiredMinxin,View): """生成卡密""" def get(self,request): key=request.user.password bgt=bg.objects.all().first() return render(request,\'index.html\',{\'bgt\':bgt,\'key\':key}) def post(self,request): key=request.POST.get(\'key\',\'\') if key==request.user.password: nums = request.POST.get(\'nums\', \'\') if nums.isdigit(): n=abs(int(nums)) u=request.POST.get(\'unit\',\'\') for i in range(n): j = str(int(time.time())) k = str(i) l = j + k + SECRET_KEY i = hashlib.sha256() i.update(l.encode(\'utf8\')) card=Cards() card.kacode=i.hexdigest() if u==\'0\': card.time=3600 elif u==\'1\': card.time = 3600*24 elif u==\'2\': card.time = 3600*24*7 elif u==\'3\': card.time = 3600*24*31 elif u==\'4\': card.time = 3600*24*31*3 elif u==\'5\': card.time = 3600*24*31*6 elif u==\'6\': card.time = 3600*24*31*12 card.save() return redirect(\'/xadmin/yanzheng/cards/\') else: msg=\'生产张数必须是整数\' else: msg=\'验证失败\' return render(request,\'index.html\',{\'msg\':msg})
5.充值功能:
1.在form.py中写对post过来的充值相关数据验证的代码:
from django import forms from .models import UserProfile class RechangForm(forms.Form): """充值验证""" uid = forms.CharField(required=True, error_messages={\'required\': \'用户名不能为空.\', }) code=forms.CharField(required=True, error_messages={\'required\': \'卡密不能为空.\', }) def clean(self): """查看用户名是否存在""" uid=self.cleaned_data.get(\'uid\',\'\') u=UserProfile.objects.filter(username=uid) if u: return self.cleaned_data else: raise forms.ValidationError(\'此用户名不存在\')
2.在views.py中开发充值相关的代码:
from django.views.generic import View from .form import RegisterForm,LoginForm,RechangForm,ResetPwdForm from django.shortcuts import render,redirect from django.http import HttpResponse from .models import UserProfile,Cards,bg import re import time import datetime import hashlib from netauth.settings import SECRET_KEY from untils.mixin_utils import LoginRequiredMinxin class RechargeView(View): """充值""" def post(self,request): rechange_form=RechangForm(request.POST) if rechange_form.is_valid(): code=request.POST.get(\'code\',\'\') card=Cards.objects.filter(kacode=code).last() if 以上是关于python3+django2 开发易语言网络验证(中)的主要内容,如果未能解决你的问题,请参考以下文章