一.前言
本系列文章的前几篇,博主已经给大家分享过如何在Django框架下构建web用户登陆注册系统和实时视频分享的功能,今天,我们将其整合一下,并添加页面构成一套web用户的交互系统。
二.代码分析
1.代码架构
图1 代码架构
2.主代码分享
online/view.py
#coding=utf-8
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django import forms
from online.models import MyUser
from online.models import Message
from online.models import SystemStatus
from django.contrib.auth import authenticate, login
from django.utils import timezone
import os
import json
import encodings
#表单
class UserForm(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())
# loginaddr="http://127.0.0.1:8000/online/login/"
# registaddr="http://127.0.0.1:8000/online/regist/"
#注册
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.statusParam=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_firstflag=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:
#比较失败,跳转loginfaild
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.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.dumps(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('textfailed.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,'static','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):
# 在Python3中使用 def __str__(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
|