【python】-- 基于Django的杂货铺

Django的杂货铺

此篇文章保存基于Django而实现的各种小功能示例

1、验证码 + Session

这个是在前端图片验证码的生成,再配合Session进行后端校验的功能示例

  1 import random
  2 from PIL import Image, ImageDraw, ImageFont, ImageFilter
  3 
  4 _letter_cases = "abcdefghjkmnpqrstuvwxy"  # 小写字母,去除可能干扰的i,l,o,z
  5 _upper_cases = _letter_cases.upper()  # 大写字母
  6 _numbers = ''.join(map(str, range(3, 10)))  # 数字
  7 init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
  8 
  9 
 10 def create_validate_code(size=(120, 30),
 11                          chars=init_chars,
 12                          img_type="GIF",
 13                          mode="RGB",
 14                          bg_color=(255, 255, 255),
 15                          fg_color=(0, 0, 255),
 16                          font_size=18,
 17                          font_type="Monaco.ttf",
 18                          length=4,
 19                          draw_lines=True,
 20                          n_line=(1, 2),
 21                          draw_points=True,
 22                          point_chance=2):
 23     """
 24     @todo: 生成验证码图片
 25     @param size: 图片的大小,格式(宽,高),默认为(120, 30)
 26     @param chars: 允许的字符集合,格式字符串
 27     @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
 28     @param mode: 图片模式,默认为RGB
 29     @param bg_color: 背景颜色,默认为白色
 30     @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
 31     @param font_size: 验证码字体大小
 32     @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
 33     @param length: 验证码字符个数
 34     @param draw_lines: 是否划干扰线
 35     @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
 36     @param draw_points: 是否画干扰点
 37     @param point_chance: 干扰点出现的概率,大小范围[0, 100]
 38     @return: [0]: PIL Image实例
 39     @return: [1]: 验证码图片中的字符串
 40     """
 41 
 42     width, height = size  # 宽高
 43     # 创建图形
 44     img = Image.new(mode, size, bg_color)
 45     draw = ImageDraw.Draw(img)  # 创建画笔
 46 
 47     def get_chars():
 48         """生成给定长度的字符串,返回列表格式"""
 49         return random.sample(chars, length)
 50 
 51     def create_lines():
 52         """绘制干扰线"""
 53         line_num = random.randint(*n_line)  # 干扰线条数
 54 
 55         for i in range(line_num):
 56             # 起始点
 57             begin = (random.randint(0, size[0]), random.randint(0, size[1]))
 58             # 结束点
 59             end = (random.randint(0, size[0]), random.randint(0, size[1]))
 60             draw.line([begin, end], fill=(0, 0, 0))
 61 
 62     def create_points():
 63         """绘制干扰点"""
 64         chance = min(100, max(0, int(point_chance)))  # 大小限制在[0, 100]
 65 
 66         for w in range(width):
 67             for h in range(height):
 68                 tmp = random.randint(0, 100)
 69                 if tmp > 100 - chance:
 70                     draw.point((w, h), fill=(0, 0, 0))
 71 
 72     def create_strs():
 73         """绘制验证码字符"""
 74         c_chars = get_chars()
 75         strs = ' %s ' % ' '.join(c_chars)  # 每个字符前后以空格隔开
 76 
 77         font = ImageFont.truetype(font_type, font_size)
 78         font_width, font_height = font.getsize(strs)
 79 
 80         draw.text(((width - font_width) / 3, (height - font_height) / 3),
 81                   strs, font=font, fill=fg_color)
 82 
 83         return ''.join(c_chars)
 84 
 85     if draw_lines:
 86         create_lines()
 87     if draw_points:
 88         create_points()
 89     strs = create_strs()
 90 
 91     # 图形扭曲参数
 92     params = [1 - float(random.randint(1, 2)) / 100,
 93               0,
 94               0,
 95               0,
 96               1 - float(random.randint(1, 10)) / 100,
 97               float(random.randint(1, 2)) / 500,
 98               0.001,
 99               float(random.randint(1, 2)) / 500
100               ]
101     img = img.transform(size, Image.PERSPECTIVE, params)  # 创建扭曲
102 
103     img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜,边界加强(阈值更大)
104 
105     return img, strs
utils/check_code.py
 1 from utils.check_code import create_validate_code
 2     
 3     
 4     def check_code(request):
 5         """
 6         验证码
 7         :param request:
 8         :return:
 9         """
10         stream = BytesIO()
11         img, code = create_validate_code()
12         img.save(stream, 'PNG')
13         request.session['CheckCode'] = code
14         return HttpResponse(stream.getvalue())
15     
16     
17     def login(request):
18         """
19         登陆
20         :param request:
21         :return:
22         """
23         if request.method == "POST":
24             if request.session['CheckCode'].upper() == request.POST.get('check_code').upper():
25                 pass
26             else:
27                 print('验证码错误')
28     
29     
30         return render(request, 'login.html')
View.py
 1  <!DOCTYPE html>
 2     <html>
 3     <head lang="en">
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css"/>
 7         <link rel="stylesheet" href="/static/plugins/font-awesome/css/font-awesome.css"/>
 8         <link rel="stylesheet" href="/static/css/edmure.css"/>
 9         <link rel="stylesheet" href="/static/css/commons.css"/>
10         <link rel="stylesheet" href="/static/css/account.css"/>
11         <style>
12     
13         </style>
14     </head>
15     <body>
16     <div class="login">
17         <div style="font-size: 25px; font-weight: bold;text-align: center;">
18             用户登陆
19         </div>
20         <form role="form">
21             <div class="form-group">
22                 <label for="username">用户名</label>
23                 <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名">
24             </div>
25             <div class="form-group">
26                 <label for="password">密码</label>
27                 <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
28             </div>
29             <div class="form-group">
30                 <label for="password">验证码</label>
31     
32                 <div class="row">
33                     <div class="col-xs-7">
34                         <input type="text" class="form-control" id="check_code" name="code" placeholder="请输入验证码" >
35                     </div>
36                     <div class="col-xs-5">
37                         <img id="imgcode" src="/check_code.html" onclick="changeCode(this);">
38                     </div>
39                 </div>
40     
41             </div>
42             <div class="checkbox">
43                 <label>
44                     <input type="checkbox"> 一个月内自动登陆
45                 </label>
46                 <div class="right">
47                     <a href="#">忘记密码?</a>
48                 </div>
49             </div>
50             <button type="submit" class="btn btn-default">登 陆</button>
51         </form>
52     </div>
53         <script>
54             function changeCode(ths){ //ths是传递自己
55                 //给img更换新的地址,这里的ths.src=ths.src后面是新的url地址,
56                 // 但是这样页面不刷新(浏览器对相同的URL不做刷新,在后面加?来更改。原来的?是跟传递参数的,所以这样写没有问题
57                 ths.src=ths.src+"?"
58             }
59         </script>
60     </body>
61 </html>
templates/login.html

2、持续更新......

 

posted @ 2018-10-12 15:23  Wilson_Blogs  阅读(322)  评论(0编辑  收藏  举报