一.前言
本系列文章的前幾篇,博主已經給大家分享過如何在Django框架下構建web用戶登陸注冊系統和實時視頻分享的功能,今天,我們將其整合一下,并添加頁面構成一套web用戶的交互系統。
二.代碼分析
1.代碼架構
圖1 代碼架構
2.主代碼分享
online/view.py
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.
template import RequestContext
from online.models import MyUser
from online.models import Message
from online.models import SystemStatus
from django.contrib.auth import authen
ticate, login
from django.utils import timezone
import os
import json
import encodings
#表單
?
class Use
rForm(forms.Form):
username = forms.CharField(label='用戶名',max_length=100)
password = forms.CharField(label='密碼',widget=forms.PasswordInput())
?
#def getuser(forms):
# return forms.username
# password1 = forms.CharField(label='重復密碼',widget=forms.TextInput())
# logina
ddr="http://127.0.0.1:8000/online/login/"
?
#注冊
def regist(req):
if req.method == 'POST':
uf = UserForm(req.POST)
if uf.is_valid():
#獲得表單數據
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
password1 = req.POST['password1']
#比較數據庫中是否已有用戶
#user = myUser.objects.all().filter(username = username)
#print(user)
if MyUser.objects.filter(username =username).exists():
return render_to_response('registfaild.html',{'uf':uf}, context_instance=RequestContext(req))
else:
if password1==password:
user=MyUser.objects.create(username= username,password=password)#添加用戶進數據庫
# profile=UserProfile()#e************************
# profile.user_id=user.id
# profile.phone=phone
# profile.save()
# user = MyUser.objects.create_user(username=username,password=password)
print(user.is_staff) #True
#user.set_password(password)
user.save()
print(user.id)
#user.userID=user.id
#user.save()
#print(user.userID)
#user_sum=MyUser.objects.all().values('username').count()
#user.userID=user_sum
#print(user.userID)
#user.save()
response = HttpResponseRedirect('/online/registsuccee/')
return response
else:
return render_to_response('registfaild1.html',{'uf':uf}, context_instance=RequestContext(req))
else:
uf = UserForm()
return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req))
?
?
def createSystemstatus():#創建系統狀態
信息
#SystemStatus.objects.filter().delete()
SystemRecord=SystemStatus.objects.filter().count()#返回所有狀態信息對象
print('SystemRecord = ',SystemRecord)
if SystemRecord == 0:#系統狀態信息只創建一個,如已創建,則不再創建
print('create systemstatus')
systemstatus=SystemStatus()
systemstatus.statusName="peopleInfront"
systemstatus.statusValue=-1
systemstatus.statusPa
ram=0
systemstatus.statusDiscirption="no people in front"
systemstatus.save()
print('statusName = ',systemstatus.statusName)
print('statusDiscirption = ',systemstatus.statusDiscirption)
else:
print(' systemstatus had credted')
?
#登陸
def loginin(req):
# getAllUser(req)
createSystemstatus()#創建全服務器唯一的系統狀態對象
user_fi
rstflag=True #初始化接收用戶選擇標志位
print(timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S"))
#獲取本機IP
#myname = socket.getfqdn(socket.gethostname( ))
#獲取本機ip
#myaddr = socket.gethostbyname(myname)
#print('myname is ',myname,'myaddr = ',myaddr)
if req.method == 'POST':
uf = UserForm(req.POST)
if uf.is_valid():
#獲取表單用戶密碼
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
?
#獲取的表單數據與數據庫進行比較
user = MyUser.objects.filter(username__exact = username,password__exact = password)
#user = authenticate(username=username, password=password)
if user:
#比較成功,跳轉index
response = HttpResponseRedirect('/online/index/')
#good="xiaoms"
#將username寫入瀏覽器cookie,失效時間為3600
response.set_cookie('username',username,3600)
response.set_cookie('user_firstflag',user_firstflag,3600)#成功登陸后,第一次的用戶是未選擇接收者
return response
else:
return render_to_response('loginfaild.html',{'uf':uf},context_instance=RequestContext(req))
else:
uf = UserForm()
return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
?
?
#def loginfaild(req):
# response = login(req)
# return response
#
def registsuccee(req):
if req.method == 'POST':
uf = UserForm(req.POST)
if uf.is_valid():
#獲取表單用戶密碼
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
#獲取的表單數據與數據庫進行比較
user = MyUser.objects.filter(username__exact = username,password__exact = password)
if user:
#比較成功,跳轉index
response = HttpResponseRedirect('/online/index/')
#將username寫入瀏覽器cookie,失效時間為3600
response.set_cookie('username',username,3600)
return response
else:
#比較失敗,跳轉loginfaild
return render_to_response('loginfaild.html',{'uf':uf},context_instance=RequestContext(req))
else:
uf = UserForm()
#return render_to_response('registfaild.html',{'uf':uf},context_instance=RequestContext(req))
return render_to_response('registsuccee.html',{'uf':uf},context_instance=RequestContext(req))
#
#def registfaild(req):
# response = regist(req)
# return response
#
#def registfaild1(req):
# response = regist(req)
# return response
?
def jsonclient(req):#獲取json對象
try:
print("start json POST")
req = json.loads((req.body).decode())
print("get json succee")
return req
except:
import sys
info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
print(info)
?
?
def datasave(request):#解板json對象并保存
info = 'Data log save success'
try:
if request.method == 'POST':
print("start json POST")
req = json.loads((request.body).decode())
user = req['user']
infoType = req['infoType']
name = req['name']
print(name)
print(infoType)
print(user)
except:
import sys
info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
print(info)
?
dict['message']=info
return HttpResponse(json)
?
def getOtherUser(req,name):
userlogin=MyUser.objects.filter(username__exact=name)#檢索當前登陸用戶
print(userlogin)
print(userlogin.id)
user_list=MyUser.objects.all().values('username','id').exclude(id__in=userlogin.id)
# user_sum=MyUser.objects.all().values('username').count()
print(user_list)
# print(user_sum)
return user_list
?
def getAllUser(req):#獲取已注冊過的所有用戶
user_list=MyUser.objects.all().values('username','id').order_by('id')
user_sum=MyUser.objects.all().values('username').count()
print(user_list)
print(user_sum)
return user_list
?
#登陸成功
def index(req):
username = req.COOKIES.get('username','')
user_list=getAllUser(req)#檢索所有擁有username和id的用戶對象
?
i=0
for list in user_list:
name=list.get('username').encode()
user_list[i].update({'username':name})
i=i+1
?
print('user_list == ',user_list)
#good=req.COOKIES.get('good','')
#print('good = ',good)
#user_list=getOtherUser(req,username)#檢索當前登陸用戶以外的所有用戶
?
#user_first=user_list[0].username
user_first=username #暫時以登錄人自己為默認接收人
#user_sum=MyUser.objects.all().values('username').count()#統計注冊的用戶數
#print(user_sum)
#datasave(req)
key_input=0
if req.method == 'POST':
print('index.username first= ',username)
?
json=jsonclient(req)#獲取json對象
if json is not None:#判斷是選擇用戶還是選擇輸入方式
user_ower = json['ownerID']#獲取owerID
print('json is not none user_ower = ',user_ower)
#message=Message()#當選擇消息接收者時創建消息對象
response = render_to_response('login_user.html' ,{'user_list':user_list,'username':username,'user_first':user_first},context_instance=RequestContext(req))
response.set_cookie('ownerID',user_ower,3600)
return response
?
?
else:
ownerID = req.COOKIES.get('ownerID','')#獲取接收者ID
print('the message ownerID is',ownerID)
if ownerID:#如果有選擇,則用選擇者
user_ower=ownerID
else:#否則默認推送給發送者自己
Uower=MyUser.objects.get(username__exact=username)
user_ower=Uower.id
?
# message=Message.objects.get(id=messid)
#user_ower=message.ownerID
message=Message()#創建消息,注意就算第一次未選擇消息接收者,也應該創建默認消息對象,默認接收ID為發送者自身
infoType_c=req.POST['
submit']#提交信息的方式獲取
infoType=int(infoType_c)
print('index:infotType=',infoType)
key_user=user_ower
key_input=infoType
print('key_user=',key_user)
print('key_input=',key_input)
user_push=MyUser.objects.get(username__exact=username)
print('username=',username)
print('user_push=',user_push)
message.infoType=infoType#推送消息的類型
message.pushID=user_push.id#推送者ID
message.ownerID= key_user#接收者的ID
message.pushTim=timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S")
message.isTop = 0 #置頂標志默認1
message.viewWeight = 1#閱讀等級默認1
message.save()
print('message.id=',message.id)
messid=message.id
print('messid=',messid)
?
#由于post 的bug這里用html5前端來保存我們的messid
if key_input == 0:
print('please input text')
response = HttpResponseRedirect('/online/text/')
#將username寫入瀏覽器cookie,失效時間為3600
response.set_cookie('username',username,3600)
response.set_cookie('messid',messid,3600)
?
print('index:messid=',messid)
return response
elif key_input == 1:
print('please input video')
response = HttpResponseRedirect('/online/video/')
#將username寫入瀏覽器cookie,失效時間為3600
response.set_cookie('username',username,3600)
response.set_cookie('messid',messid,3600)
?
return response
else:
response = render_to_response('login_user.html' ,{'user_list':user_list,'username':username,'user_first':user_first,'messid':messid},context_instance=RequestContext(req))
print('error ~! just donot in this page')
response.set_cookie('messid',messid,3600)
?
return response
#return render_to_response('loginsuccee.html' ,{'user_list':json.du
mps(user_list),'username':username,'user_first':user_first,'messid':messid},context_instance=RequestContext(req))
else:
return render_to_response('login_user.html' ,{'user_list': user_list,'user_first':user_first,'username':username},context_instance=RequestContext(req))
?
#退出
def logout(req):
response = HttpResponse('logout !!')
#清理cookie里保存username
response.delete_cookie('username')
response.delete_cookie('messid')
return response
#response = HttpResponse('logout !!')
#清理cookie里保存username
# response.delete_cookie('username')
# return response
?
?
?
def text(req):#輸入文本處理
username = req.COOKIES.get('username','')
messid= req.COOKIES.get('messid','')
print('text:username=',username)
print('text:messid=',messid)
?
if req.method == 'POST':
# json=jsonclient(req)#獲取json對象
# messid1 = json['messid']#獲取owerID
# print(messid1)
?
text = req.POST['text_input']
#if text is not None:
user=MyUser.objects.get(username__exact=username)
print('user.id=',user.id)
print('messid=',messid)
#userID=user.id
message=Message.objects.get(id=messid)
message.infoContent=text
print(username)
print('message.ownerID = ',message.ownerID)
print('message.pushID =',message.pushID)
print(message.infoContent)
#message.pushTim=timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S")
message.save()
response = HttpResponseRedirect('/online/show/')
#將username寫入瀏覽器cookie,失效時間為3600
response.set_cookie('username',username,3600)
return response
# else:
# return render_to_response('textfai
led.html')
# print(dir(MyUser))
?
return render_to_response('text1.html',context_instance=RequestContext(req))
?
?
def video(req):#輸入視頻處理
username = req.COOKIES.get('username','')
messid= req.COOKIES.get('messid','')
print('video:username=',username)
print('video:messid=',messid)
if req.method == 'POST':
f = req.FILES.get('video')
if f is not None:
baseDir = os.path.dirname(os.path.abspath(__name__))
dir = os.path.join(baseDir,'stat
ic','save')
filedir=os.path.join(dir,f.name)
print('filedir = ',filedir)
timename=timezone.localtime(timezone.now()).strftime("%Y%m%d%H%M%S")
#filename = os.path.join(dir,f.name)
fname=os.path.splitext(f.name)
fsuffix=fname[1]
print('fsuffix =',fsuffix)
filename = os.path.join(dir,timename+fsuffix)#用當地時間編號代替
手機發過來的任意文章名,以免重疊
print('filename =',filename)
fobj = open(filename,'wb')
for chrunk in f.chunks():
fobj.write(chrunk)
fobj.close()
message=Message.objects.get(id=messid)
message.filePath=filename
message.save()
response = HttpResponseRedirect('/online/show/')
#將username寫入瀏覽器cookie,失效時間為3600
response.set_cookie('username',username,3600)
return response
else:
return render_to_response('camera_reinput.html')
?
else:
return render_to_response('camera.html')
?
?
?
def show(req):
username = req.COOKIES.get('username','')
messid = req.COOKIES.get('messid','')
message=Message.objects.get(id=messid)
print('message.infoContent',message.infoContent)
return render_to_response('save.html',{'text':text,'username':username,'message.infoContent':message.infoContent})
?
?
?
def delete():
MyUser.objects.filter().delete()
?
?
online/models.py
#coding:utf8
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin)
?
?
class MyUserManager(BaseUserManager):
# def _create_user(self, username, email, password, **extra_fields):
def _create_user(self, username, password, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
if not username:
raise ValueError('The given username must be set')
# email = self.normalize_email(email)
# user = self.model(username=username, email=email, **extra_fields)
user = self.model(username=username, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
?
# def create_user(self, username, email, password, **extra_fields):
def create_user(self, username, password, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('email',"")
extra_fields.setdefault('phone',"")
extra_fields.setdefault('haarValue',"")
extra_fields.setdefault('avatarImg',"")
# extra_fields.setdefault('text',"")
# extra_fields.setdefault('video',"")
# extra_fields.setdefault('time',"")
return self._create_user(username, password, **extra_fields)
# return self._create_user(username, email, password, **extra_fields)
# def create_superuser(self, username, email, password, **extra_fields):
def create_superuser(self, username, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
?
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True')
#拓展user數據 by xiao
#get
#to
#message_flag
#text
#video
#time
# extra_fields.setdefault('got',username)
# extra_fields.setdefault('to',username)
# extra_fields.setdefault('message_flag',"1")
# extra_fields.setdefault('text',"")
# extra_fields.setdefault('video',"")
# extra_fields.setdefault('time',"")
?
return self._create_user(username, password, **extra_fields)
# return self._create_user(username, email, password, **extra_fields)
?
?
class MyUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254, unique=True, db_index=True)
email = models.CharField(max_length=254)
phone = models.CharField(max_length=254)
haarValue = models.CharField(max_length=254)
avatarImg = models.CharField(max_length=254)
?
#email = models.EmailField('email address', max_length=254)
#text=models.CharField(max_length=254, unique=True, db_index=True)
is_staff = models.BooleanField('staff status', default=False)
?
# userID = models.IntegerField(default=1) #用戶獨有的ID
?
# is_active = models.BooleanField('active', default=True)
# got = models.CharField(max_length=254,default=username)
# to = models.CharField(max_length=254,default=username)
# message_flag = models.CharField(max_length=254, default=1)
# text = models.CharField(max_length=254, default="")
# video = models.CharField(max_length=254,default="")
# time = models.CharField(max_length=254,default="")
?
?
USERNAME_FIELD = 'username'
# REQUIRED_FIELDS = ['email']
?
objects = MyUserManager()
?
class Meta:
db_table = 'myuser'
?
?
# def get_full_name(self):
# return self.username
?
# def get_short_name(self):
# return self.username
#建立推送消息的模型
?
?
class Message(models.Model):
# username = models.CharField(max_length=254) #消息推送者的名字
ownerID = models.IntegerField(default=1)
pushID = models.IntegerField(default=1)
infoType = models.IntegerField(default=0)
infoSubject = models.CharField(max_length=254)
infoContent = models.CharField(max_length=254)
filePath = models.CharField(max_length=1000)
pushTim = models.CharField(max_length=254)
infoValidityTime = models.CharField(max_length=254)
isTop = models.IntegerField(default=0)
viewWeight = models.IntegerField(default=1)
def __unicode__(self):
return self.name
?
class SystemStatus(models.Model): #實例化對象:online_message MMDB.updateSystemStatus('peopleInfront',-1,0,'no people in front')
statusName = models.CharField(max_length=30,default="peopleInfront")
statusValue = models.IntegerField(default=-1)
statusParam = models.IntegerField(default=0)
statusDiscirption = models.CharField(max_length=50,default="no people in front")
?
def __unicode__(self):
# 在Python3中使用 def __str__(self)
return self.name
三.演示效果圖
圖2 注冊頁面
圖3 視頻上傳頁面
圖4 消息選擇頁面
圖5 上傳成功頁面
四.例程分享:
http://pan.baidu.com/share/link?shareid=3536829173&uk=1812979481
評論
查看更多