Django子应用里的通用类混合视图处理

# 子应用的views.py此文件用于编写Web应用视图,处理复杂的业务逻辑

#导入方法视图模板
from django.shortcuts import render
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View
#从配置文件已安装的django应用模块导入数据库类
from mysite.models import User
from supermarket.models import Product
#导入json
import json
#导入时间模块
import time
#导入源生sql连接
from django.db import connection

#导入通用类视图装饰器
from django.utils.decorators import method_decorator



#定义一个用cookie验证登录的装饰器decorator
#用session验证登录的装饰器只需换下变量名,在注销功能改下即可
def cookie(func):
    def wrapper(request,*args,**kwargs):
        login = request.COOKIES.get("username",False)
        if not login:
            return HttpResponseRedirect('/supermarket/login')
        return func(request,*args,**kwargs)
    return wrapper


#定义反爬装饰器,定义形参,一秒允许请求一次
def limit(seconds=1):
    #定义内部方法
    def rate_limit(func):
        def func_limit(request):
            #获取当前时间
            now = time.time()
            ip = request.META.get('REMOTE_ADDR')
            print(int(now))
            print(ip)
            print('- '*50)
            #获取首次来访时间
            request_time = request.session.get('req_time',0)
            print(request_time)
            _ip = request.session.get('ip',ip)
            print(_ip)
            #做减法
            in_time = int(now) - request_time

            #判断访问者在一秒内来了不止一次
            if in_time < seconds and ip == _ip:
                #抛出异常,使用第二个参数来指定异常
                return HttpResponse('你是爬虫,不要来了',status = 403)
            else:
                #存储第一次请求时间
                request.session['req_time'] = time.time()
                request.session['ip'] = ip
                #让访问者继续访问
                ret = func(request)
                return ret
        return func_limit
    return rate_limit



# Create your views here.
#定义注册逻辑类视图
class Reg(View):

    #定义注册接收方法
    def post(self,request):

        #等待时间
        time.sleep(1)

        #接收参数
        username = request.POST.get('username','未收到username值')
        password = request.POST.get('password','未收到password值')
        
        #注册入库逻辑
        #先验证用户唯一性
        res = User.objects.filter(username=username).count()
        if res > 0:
            # #该用户名已被注册
            # #将dict强转为json数据
            # data = json.dumps({'msg':'该用户名已被注册'},ensure_ascii=False)
            # #声明返回网页头部信息为json类型
            # return HttpResponse(data,content_type='application/json')
            return JsonResponse({'msg':'该用户名已被注册'})
        else:
            #入库
            #实例化一个对象
            user = User(username=username,password=password)
            #保存
            user.save()
            # #将dict强转为json数据
            # data = json.dumps({'msg':'恭喜您,注册成功'},ensure_ascii=False)
            # return HttpResponse(data,content_type='application/json')
            return JsonResponse({'msg':'恭喜您,注册成功'},safe=False)



#为登录页面加上图形验证码的验证逻辑
from PIL import ImageDraw
#导入绘图字体库
from PIL import ImageFont
#到导入图片库
from PIL import Image
import io,random
#定义随机颜色方法
def get_random_color():
    R = random.randrange(255)
    G = random.randrange(255)
    B = random.randrange(255)
    return (R,G,B)
#定义随机验证码
def test_captcha(request):
    #定义背景颜色
    bg_color = get_random_color()
    #定义画布大小,宽 高
    img_size = (150,80)
    #定义画笔,颜色中类,画布,背景颜色
    image = Image.new('RGB',img_size,bg_color)
    #定义画笔对象 ,图片对象,颜色类型
    draw = ImageDraw.Draw(image,"RGB")
     #定义随机字符
    source =  '0123456789qwertyuiopasdfghjklzxcvbnm'
    #定义四个字符
    #定义容器,用来接收随机字符串
    code_str=""
    for i in range(4):
        #获取随机颜色
        text_color = get_random_color()
        #获取随机字符串
        tmp_num = random.randrange(len(source))
        #获取字符集
        random_str =source[tmp_num]
        #将随机生成的字符串添加到容器中
        code_str += random_str
        #将字符画动画布上 坐标,字符串,字符串颜色,字体
        #先导入系统字体
        my_font = ImageFont.truetype("c:\\Windows/Fonts/consolai.ttf",30)
        draw.text((10+30*i,20),random_str,text_color,font=my_font)
    #使用io获取一个缓存区
    buf= io.BytesIO()
    #将图片保存到缓存区 透明图片
    image.save(buf,'png')

    #将随机码存储到session中,用于登录认证
    request.session['code'] = code_str

    #第二个参数声明头部信息
    return HttpResponse(buf.getvalue(),'image/png')





#定义登录逻辑类视图
class Login(View):

    #定义登录方法
    def post(self,request):

        # time.sleep(2)

        #接收参数
        username = request.POST.get('username','未收到username值')
        password = request.POST.get('password','未收到password值')
        code = request.POST.get('code','未收到code值')

        #判断
        res = User.objects.filter(username=username,password=password).count()
        
        #测试中文用户名
        # return HttpResponse(res)
        
        if res > 0 and code == request.session['code']:
            #登录成功
            response = HttpResponse('登陆成功')
            #对中文用户名编码
            username = bytes(username,'utf-8').decode('ISO-8859-1')
            #存入cookie  request.COOKIES.get('username')
            response.set_cookie('username',username,max_age=3600)
            response.set_cookie('password',password,max_age=3600)
            #用户名存入session
            request.session['username'] = username
            return response
        elif res > 0 and code != request.session['code']:
            return HttpResponse('验证码输入有误,请重新输入!')
        else:
            #登录失败,防止暴力破解
            return HttpResponse('您输入的用户名或者密码错误,请重新输入!')



#定义注销功能
class Logout(View):
    #定义注销方法
    def get(self,request):
        #建立response对象
        response = HttpResponseRedirect('/supermarket/login')
        #删除cookie
        response.delete_cookie('username')
        response.delete_cookie('password')
        # #删除session
        # del request.session['username']
        return response

        
# 定义商品列表页混合视图
class ProductList(View):

    @method_decorator(cookie)
    #客户端get请求
    def get(self,request):
        infos = Product.objects.all()
        print(infos)
        username = request.COOKIES.get('username','未登录')
        #对中文用户名解码
        try:
            username = username.encode('ISO-8859-1').decode('utf-8')
        except Exception as e:
            print(e)
            pass
        #渲染模板
        return render(request,'supermarket/productList.html',locals())


#商品入库
class Add(View):

    def post(self,request):
        name = request.POST.get('name')
        price = request.POST.get('price')
        #只让不同的商品入库
        ret = Product.objects.filter(name=name,price=int(price)).count()
        if ret == 0:
            sql = Product(name=name,price=int(price))
            sql.save()
            return HttpResponse('入库成功')
        else:
            return HttpResponse('该商品已存在')



#定义商品删除操作
class ProDel(View):
    
    def post(self,request):
        #接受参数
        id = request.POST.get('id')
        id=int(id)
        #删除操作
        Product.objects.filter(id=id).delete()
        return HttpResponse('删除成功')



#修改操作
class ProEdit(View):

    def post(self,request):
        id = request.POST.get('id')
        id=int(id)
        name = request.POST.get('name')
        price = request.POST.get('price')
        price=int(price)
        #修改
        Product.objects.filter(id=id).update(name=name,price=price)
        return HttpResponse('修改成功')



#添加购物车操作
class AddCart(View):

    def post(self,request):
        id = request.POST.get('id')
        id = int(id)
        #判断购物车,是否存在
        # cartlist = request.session.get('cartlist',0)

        #获取session的用户名的购物车
        username = request.session.get('username')
        cartlist = request.session.get(username,0)
        
        #如果没有购物车,就创建后添加
        if cartlist == 0:
            clist = []
            clist.append(id)
            # request.session['cartlist'] = clist
            request.session[username] = clist
        #如果有购物车
        else:
            #取出购物车
            # slist = request.session['cartlist']
            slist = request.session[username]
            #id直接存入购物车
            slist.append(id)
            #把购物车重新放入session
            # request.session['cartlist'] = slist
            request.session[username] = slist
        
        return HttpResponse('成功加入购物车')



#购物车列表页
class CartList(View):

    def get(self,request):
        # del request.session['cartlist']

        # cartlist = request.session.get('cartlist',0)

        #获取个人购物车
        username = request.session.get('username',0)
        cartlist = request.session.get(username,0)

        #查询商品数据库的id字段
        idlist = Product.objects.raw("select id from product")
        #对象列表嵌套数据,用列表推导式和对象.属性,生成id列表
        idlist = [ x.id for x in idlist]
        # print(idlist)

        #购物车为空或没有创建购物车
        if cartlist != 0 and cartlist != []:
            #准备传给前端的数据
            context = []
            for i in cartlist:
                #判断购物车的商品是否能买
                if i in idlist:
                    obj = Product.objects.filter(id=i)
                    # print('- '*50)
                    # print(obj[0].id)#对象列表嵌套
                    context.append(obj[0])
                #此商品已下架
                else:
                    obj = {'id':i,'name':'该商品已下架','price':''}
                    context.append(obj)
        #没有创建购物车
        elif cartlist == []:
            context = '[]'

        return render(request,'supermarket/cartList.html',locals())


#购物车删除操作
class CartDel(View):

    def post(self,request):
        id = request.POST.get('id')
        id = int(id)
        # cartlist = request.session.get('cartlist',0)
        #获取session的用户名的购物车
        username = request.session.get('username')
        cartlist = request.session[username]

        #remove()会删除第一个等于指定值的元素
        if cartlist != []:
            cartlist.remove(id)
            request.session[username] = cartlist

        return HttpResponse('删除成功')


'''
from django.http import JsonResponse
用来对象dumps成json字符串,然后返回将json字符串封装成Response对象返回给浏览器。
并且他的Content-Type是application/json。
非字典只有list,tuple转json应该在使用HttpResponse的时候,传入一个safe=False参数
'''
def Json(request):
    ddd = {"username":"知乎大神","age":18}
    lll = ['a','b','c','d']
    ttt = (1,2,3,4,5,6)
    return JsonResponse(lll,safe=False)

 


#导入方法视图模板
from django.shortcuts import render
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View
#从配置文件已安装的django应用模块导入数据库类
from mysite.models import User
from supermarket.models import Product
#导入json
import json
#导入时间模块
import time
#导入源生sql连接
from django.db import connection

#导入通用类视图装饰器
from django.utils.decorators import method_decorator



#定义一个用cookie验证登录的装饰器decorator
#用session验证登录的装饰器只需换下变量名,在注销功能改下即可
def cookie(func):
def wrapper(request,*args,**kwargs):
login = request.COOKIES.get("username",False)
if not login:
return HttpResponseRedirect('/supermarket/login')
return func(request,*args,**kwargs)
return wrapper


#定义反爬装饰器,定义形参,一秒允许请求一次
def limit(seconds=1):
#定义内部方法
def rate_limit(func):
def func_limit(request):
#获取当前时间
now = time.time()
ip = request.META.get('REMOTE_ADDR')
print(int(now))
print(ip)
print('- '*50)
#获取首次来访时间
request_time = request.session.get('req_time',0)
print(request_time)
_ip = request.session.get('ip',ip)
print(_ip)
#做减法
in_time = int(now) - request_time

#判断访问者在一秒内来了不止一次
if in_time < seconds and ip == _ip:
#抛出异常,使用第二个参数来指定异常
return HttpResponse('你是爬虫,不要来了',status = 403)
else:
#存储第一次请求时间
request.session['req_time'] = time.time()
request.session['ip'] = ip
#让访问者继续访问
ret = func(request)
return ret
return func_limit
return rate_limit



# Create your views here.
#定义注册逻辑类视图
class Reg(View):

#定义注册接收方法
def post(self,request):

#等待时间
time.sleep(1)

#接收参数
username = request.POST.get('username','未收到username值')
password = request.POST.get('password','未收到password值')
 
#注册入库逻辑
#先验证用户唯一性
res = User.objects.filter(username=username).count()
if res > 0:
# #该用户名已被注册
# #将dict强转为json数据
# data = json.dumps({'msg':'该用户名已被注册'},ensure_ascii=False)
# #声明返回网页头部信息为json类型
# return HttpResponse(data,content_type='application/json')
return JsonResponse({'msg':'该用户名已被注册'})
else:
#入库
#实例化一个对象
user = User(username=username,password=password)
#保存
user.save()
# #将dict强转为json数据
# data = json.dumps({'msg':'恭喜您,注册成功'},ensure_ascii=False)
# return HttpResponse(data,content_type='application/json')
return JsonResponse({'msg':'恭喜您,注册成功'},safe=False)



#为登录页面加上图形验证码的验证逻辑
from PIL import ImageDraw
#导入绘图字体库
from PIL import ImageFont
#到导入图片库
from PIL import Image
import io,random
#定义随机颜色方法
def get_random_color():
R = random.randrange(255)
G = random.randrange(255)
B = random.randrange(255)
return (R,G,B)
#定义随机验证码
def test_captcha(request):
#定义背景颜色
bg_color = get_random_color()
#定义画布大小,宽 高
img_size = (150,80)
#定义画笔,颜色中类,画布,背景颜色
image = Image.new('RGB',img_size,bg_color)
#定义画笔对象 ,图片对象,颜色类型
draw = ImageDraw.Draw(image,"RGB")
#定义随机字符
source = '0123456789qwertyuiopasdfghjklzxcvbnm'
#定义四个字符
#定义容器,用来接收随机字符串
code_str=""
for i in range(4):
#获取随机颜色
text_color = get_random_color()
#获取随机字符串
tmp_num = random.randrange(len(source))
#获取字符集
random_str =source[tmp_num]
#将随机生成的字符串添加到容器中
code_str += random_str
#将字符画动画布上 坐标,字符串,字符串颜色,字体
#先导入系统字体
my_font = ImageFont.truetype("c:\\Windows/Fonts/consolai.ttf",30)
draw.text((10+30*i,20),random_str,text_color,font=my_font)
#使用io获取一个缓存区
buf= io.BytesIO()
#将图片保存到缓存区 透明图片
image.save(buf,'png')

#将随机码存储到session中,用于登录认证
request.session['code'] = code_str

#第二个参数声明头部信息
return HttpResponse(buf.getvalue(),'image/png')





#定义登录逻辑类视图
class Login(View):

#定义登录方法
def post(self,request):

# time.sleep(2)

#接收参数
username = request.POST.get('username','未收到username值')
password = request.POST.get('password','未收到password值')
code = request.POST.get('code','未收到code值')

#判断
res = User.objects.filter(username=username,password=password).count()
 
#测试中文用户名
# return HttpResponse(res)
 
if res > 0 and code == request.session['code']:
#登录成功
response = HttpResponse('登陆成功')
#对中文用户名编码
username = bytes(username,'utf-8').decode('ISO-8859-1')
#存入cookie request.COOKIES.get('username')
response.set_cookie('username',username,max_age=3600)
response.set_cookie('password',password,max_age=3600)
#用户名存入session
request.session['username'] = username
return response
elif res > 0 and code != request.session['code']:
return HttpResponse('验证码输入有误,请重新输入!')
else:
#登录失败,防止暴力破解
return HttpResponse('您输入的用户名或者密码错误,请重新输入!')



#定义注销功能
class Logout(View):
#定义注销方法
def get(self,request):
#建立response对象
response = HttpResponseRedirect('/supermarket/login')
#删除cookie
response.delete_cookie('username')
response.delete_cookie('password')
# #删除session
# del request.session['username']
return response

 
# 定义商品列表页混合视图
class ProductList(View):

@method_decorator(cookie)
#客户端get请求
def get(self,request):
infos = Product.objects.all()
print(infos)
username = request.COOKIES.get('username','未登录')
#对中文用户名解码
try:
username = username.encode('ISO-8859-1').decode('utf-8')
except Exception as e:
print(e)
pass
#渲染模板
return render(request,'supermarket/productList.html',locals())


#商品入库
class Add(View):

def post(self,request):
name = request.POST.get('name')
price = request.POST.get('price')
#只让不同的商品入库
ret = Product.objects.filter(name=name,price=int(price)).count()
if ret == 0:
sql = Product(name=name,price=int(price))
sql.save()
return HttpResponse('入库成功')
else:
return HttpResponse('该商品已存在')



#定义商品删除操作
class ProDel(View):
 
def post(self,request):
#接受参数
id = request.POST.get('id')
id=int(id)
#删除操作
Product.objects.filter(id=id).delete()
return HttpResponse('删除成功')



#修改操作
class ProEdit(View):

def post(self,request):
id = request.POST.get('id')
id=int(id)
name = request.POST.get('name')
price = request.POST.get('price')
price=int(price)
#修改
Product.objects.filter(id=id).update(name=name,price=price)
return HttpResponse('修改成功')



#添加购物车操作
class AddCart(View):

def post(self,request):
id = request.POST.get('id')
id = int(id)
#判断购物车,是否存在
# cartlist = request.session.get('cartlist',0)

#获取session的用户名的购物车
username = request.session.get('username')
cartlist = request.session.get(username,0)
 
#如果没有购物车,就创建后添加
if cartlist == 0:
clist = []
clist.append(id)
# request.session['cartlist'] = clist
request.session[username] = clist
#如果有购物车
else:
#取出购物车
# slist = request.session['cartlist']
slist = request.session[username]
#id直接存入购物车
slist.append(id)
#把购物车重新放入session
# request.session['cartlist'] = slist
request.session[username] = slist
 
return HttpResponse('成功加入购物车')



#购物车列表页
class CartList(View):

def get(self,request):
# del request.session['cartlist']

# cartlist = request.session.get('cartlist',0)

#获取个人购物车
username = request.session.get('username',0)
cartlist = request.session.get(username,0)

#查询商品数据库的id字段
idlist = Product.objects.raw("select id from product")
#对象列表嵌套数据,用列表推导式和对象.属性,生成id列表
idlist = [ x.id for x in idlist]
# print(idlist)

#购物车为空或没有创建购物车
if cartlist != 0 and cartlist != []:
#准备传给前端的数据
context = []
for i in cartlist:
#判断购物车的商品是否能买
if i in idlist:
obj = Product.objects.filter(id=i)
# print('- '*50)
# print(obj[0].id)#对象列表嵌套
context.append(obj[0])
#此商品已下架
else:
obj = {'id':i,'name':'该商品已下架','price':''}
context.append(obj)
#没有创建购物车
elif cartlist == []:
context = '[]'

return render(request,'supermarket/cartList.html',locals())


#购物车删除操作
class CartDel(View):

def post(self,request):
id = request.POST.get('id')
id = int(id)
# cartlist = request.session.get('cartlist',0)
#获取session的用户名的购物车
username = request.session.get('username')
cartlist = request.session[username]

#remove()会删除第一个等于指定值的元素
if cartlist != []:
cartlist.remove(id)
request.session[username] = cartlist

return HttpResponse('删除成功')


'''
from django.http import JsonResponse
用来对象dumps成json字符串,然后返回将json字符串封装成Response对象返回给浏览器。
并且他的Content-Type是application/json。
非字典只有list,tuple转json应该在使用HttpResponse的时候,传入一个safe=False参数
'''
def Json(request):
ddd = {"username":"知乎大神","age":18}
lll = ['a','b','c','d']
ttt = (1,2,3,4,5,6)
return JsonResponse(lll,safe=False)
posted @ 2019-02-17 10:30  justblue  阅读(382)  评论(0编辑  收藏  举报