django實現(xiàn)同一個ip十分鐘內(nèi)只能注冊一次的實例
很多小伙伴都會有這樣的問題,說一個ip地址十分鐘內(nèi)之內(nèi)注冊一次,用來防止用戶來重復注冊帶來不必要的麻煩
邏輯:
取ip,在數(shù)據(jù)庫找ip是否存在,存在判斷當前時間和ip上次訪問時間之差,小于600不能注冊,到登錄界面,大于600可以注冊,
設計一個數(shù)據(jù)庫來存儲這個ip地址和訪問時間,
class Ip(models.Model): ip=models.CharField(max_length=20) time=models.DateTimeField() class Meta: verbose_name = u'訪問時間' verbose_name_plural = verbose_name def __str__(self): return self.ip
然后去
python manage.py makemigrations
python manage.py migrate
這樣來更新我們的數(shù)據(jù)庫,然后我們運行我們的項目可以在后臺看到我們新注冊的ip的數(shù)據(jù)
我們根據(jù)前面的邏輯,可以來設計我們的代碼,
from django.views.generic.base import View from blog.models import Ip class RegView(View): def get(self,request): ipreques = request.META['REMOTE_ADDR'] try: ip_c=Ip.objects.get(ip=ipreques) if ip_c : if (datetime.datetime.now()-ip_c.time).total_seconds()<600: return render(request, 'login.html', {'msg': u'10分鐘內(nèi)只能注冊一次'}) ip_c.time=datetime.datetime.now() ip_c.save() return render(request, 'reg.html') except Exception as e: new=Ip() new.ip=str(ipreques) new.time=datetime.datetime.now() new.save() return render(request, 'reg.html') def post(self,request): username=request.POST['username'] if len(getuser(username))<=0: return render(request,'reg.html',{'msg':u'用戶名應該是6-16組成'}) passwor1 = request.POST['password'] passwor2 = request.POST['password1'] shouj = request.POST['shouji'] if len(getPhoneNumFromFile(shouj))<=0: return render(request, 'reg.html', {'msg':u'手機號格式是否正確'}) shouji = User.objects.filter(mobile__exact=shouj) if shouji: return render(request, 'reg.html', {'msg': u'手機號已經(jīng)存在'}) youjian = request.POST['email'] if len(getMailAddFromFile(youjian))<=0: return render(request, 'reg.html', {'msg': u'郵箱格式是否正確'}) use=User.objects.filter(username__exact=username) if use: return render(request,'reg.html',{'msg':u'用戶名已經(jīng)存在'}) else: if passwor1==passwor2: use1=User() use1.username=username use1.password=passwor1 use1.mobile=shouj use1.email=youjian use1.save() return HttpResponseRedirect('login') else: return render(request,'reg.html',{'msg':u'請查看密碼是否一致'}) return render(request,'reg.html')
其實這樣,我們的整個過程就已經(jīng)構建完畢,代碼出來后,有小伙伴會問,你這代碼怎么和我用的不一樣,
我們都是函數(shù)式編程,其實很簡單,我們?nèi)ゼ蒝iew類就可以實現(xiàn)我們的面向對象的編程,在url中我們只需要這么來寫我們的代碼。
url(r'^reg$', RegView.as_view(),name='reg'),
這樣我們就可以完成了限制同個ip一段時間的注冊的次數(shù)。
以上這篇django實現(xiàn)同一個ip十分鐘內(nèi)只能注冊一次的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Django 添加靜態(tài)文件的兩種實現(xiàn)方法(必看篇)
- django靜態(tài)文件加載的方法
- Django學習教程之靜態(tài)文件的調(diào)用詳解
- django模板加載靜態(tài)文件的方法步驟
- Django壓縮靜態(tài)文件的實現(xiàn)方法詳析
- 詳解Django模版中加載靜態(tài)文件配置方法
- 詳解Django中間件的5種自定義方法
- 詳解Django中間件執(zhí)行順序
- Django中間件工作流程及寫法實例代碼
- Python編程django實現(xiàn)同一個ip十分鐘內(nèi)只能注冊一次
- Python django框架應用中實現(xiàn)獲取訪問者ip地址示例
- Django框架靜態(tài)文件使用/中間件/禁用ip功能實例詳解
相關文章
基于python代碼實現(xiàn)簡易濾除數(shù)字的方法
今天小編就為大家分享一篇基于python代碼實現(xiàn)簡易濾除數(shù)字的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07