【python】-- 基于Django的杂货铺
Django的杂货铺
此篇文章保存基于Django而实现的各种小功能示例
1、验证码 + Session
这个是在前端图片验证码的生成,再配合Session进行后端校验的功能示例
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter _letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母,去除可能干扰的i,l,o,z
_upper_cases = _letter_cases.upper() # 大写字母
_numbers = ''.join(map(str, range(3, 10))) # 数字
init_chars = ''.join((_letter_cases, _upper_cases, _numbers)) def create_validate_code(size=(120, 30),
chars=init_chars,
img_type="GIF",
mode="RGB",
bg_color=(255, 255, 255),
fg_color=(0, 0, 255),
font_size=18,
font_type="Monaco.ttf",
length=4,
draw_lines=True,
n_line=(1, 2),
draw_points=True,
point_chance=2):
"""
@todo: 生成验证码图片
@param size: 图片的大小,格式(宽,高),默认为(120, 30)
@param chars: 允许的字符集合,格式字符串
@param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
@param mode: 图片模式,默认为RGB
@param bg_color: 背景颜色,默认为白色
@param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
@param font_size: 验证码字体大小
@param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
@param length: 验证码字符个数
@param draw_lines: 是否划干扰线
@param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
@param draw_points: 是否画干扰点
@param point_chance: 干扰点出现的概率,大小范围[0, 100]
@return: [0]: PIL Image实例
@return: [1]: 验证码图片中的字符串
""" width, height = size # 宽高
# 创建图形
img = Image.new(mode, size, bg_color)
draw = ImageDraw.Draw(img) # 创建画笔 def get_chars():
"""生成给定长度的字符串,返回列表格式"""
return random.sample(chars, length) def create_lines():
"""绘制干扰线"""
line_num = random.randint(*n_line) # 干扰线条数 for i in range(line_num):
# 起始点
begin = (random.randint(0, size[0]), random.randint(0, size[1]))
# 结束点
end = (random.randint(0, size[0]), random.randint(0, size[1]))
draw.line([begin, end], fill=(0, 0, 0)) def create_points():
"""绘制干扰点"""
chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100] for w in range(width):
for h in range(height):
tmp = random.randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0)) def create_strs():
"""绘制验证码字符"""
c_chars = get_chars()
strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开 font = ImageFont.truetype(font_type, font_size)
font_width, font_height = font.getsize(strs) draw.text(((width - font_width) / 3, (height - font_height) / 3),
strs, font=font, fill=fg_color) return ''.join(c_chars) if draw_lines:
create_lines()
if draw_points:
create_points()
strs = create_strs() # 图形扭曲参数
params = [1 - float(random.randint(1, 2)) / 100,
0,
0,
0,
1 - float(random.randint(1, 10)) / 100,
float(random.randint(1, 2)) / 500,
0.001,
float(random.randint(1, 2)) / 500
]
img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大) return img, strs
utils/check_code.py
from utils.check_code import create_validate_code
def check_code(request):
"""
验证码
:param request:
:return:
"""
stream = BytesIO()
img, code = create_validate_code()
img.save(stream, 'PNG')
request.session['CheckCode'] = code
return HttpResponse(stream.getvalue())
def login(request):
"""
登陆
:param request:
:return:
"""
if request.method == "POST":
if request.session['CheckCode'].upper() == request.POST.get('check_code').upper():
pass
else:
print('验证码错误')
return render(request, 'login.html')
View.py
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css"/>
<link rel="stylesheet" href="/static/plugins/font-awesome/css/font-awesome.css"/>
<link rel="stylesheet" href="/static/css/edmure.css"/>
<link rel="stylesheet" href="/static/css/commons.css"/>
<link rel="stylesheet" href="/static/css/account.css"/>
<style> </style>
</head>
<body>
<div class="login">
<div style="font-size: 25px; font-weight: bold;text-align: center;">
用户登陆
</div>
<form role="form">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
</div>
<div class="form-group">
<label for="password">验证码</label> <div class="row">
<div class="col-xs-7">
<input type="text" class="form-control" id="check_code" name="code" placeholder="请输入验证码" >
</div>
<div class="col-xs-5">
<img id="imgcode" src="/check_code.html" onclick="changeCode(this);">
</div>
</div> </div>
<div class="checkbox">
<label>
<input type="checkbox"> 一个月内自动登陆
</label>
<div class="right">
<a href="#">忘记密码?</a>
</div>
</div>
<button type="submit" class="btn btn-default">登 陆</button>
</form>
</div>
<script>
function changeCode(ths){ //ths是传递自己
//给img更换新的地址,这里的ths.src=ths.src后面是新的url地址,
// 但是这样页面不刷新(浏览器对相同的URL不做刷新,在后面加?来更改。原来的?是跟传递参数的,所以这样写没有问题
ths.src=ths.src+"?"
}
</script>
</body>
</html>
templates/login.html
2、持续更新......
【python】-- 基于Django的杂货铺的更多相关文章
- python基于django编写api+前端后端分离
有用 https://segmentfault.com/a/1190000016049962#articleHeader2 python的前后端分离(一):django+原生js实现get请求 htt ...
- python基于Django框架编译报错“django.core.exceptions.ImproperlyConfigured”的解决办法?
下面是我具体遇到的问题和解决方法: 错误详细信息: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_IND ...
- python学习-- Django根据现有数据库,自动生成models模型文件
Django引入外部数据库还是比较方便的,步骤如下 : 创建一个项目,修改seting文件,在setting里面设置你要连接的数据库类型和连接名称,地址之类,和创建新项目的时候一致 运行下面代码可以自 ...
- python 全栈开发,Day95(RESTful API介绍,基于Django实现RESTful API,DRF 序列化)
昨日内容回顾 1. rest framework serializer(序列化)的简单使用 QuerySet([ obj, obj, obj]) --> JSON格式数据 0. 安装和导入: p ...
- 基于Django的独立运行的python脚本开发
Django框架很方便,比如其方便的ORM,如果写基于Django的独立运行脚本,主要在脚本前面加上以下代码: import sys,os,django sys.path.append(os.path ...
- 在IIS上部署基于django WEB框架的python网站应用
django是一款基于python语言的WEB开源框架,本文给出了如何将基于django写的python网站部署到window的IIS上. 笔者的运行环境: Window xp sp3 IIS 5.1 ...
- 基于Django的独立运行python脚本开发
Django框架很方便,比如其方便的ORM,如果写基于Django的独立运行脚本,主要在脚本前面加上以下代码: import sys,os,django sys.path.append(os.path ...
- [Python] 利用Django进行Web开发系列(一)
1 写在前面 在没有接触互联网这个行业的时候,我就一直很好奇网站是怎么构建的.现在虽然从事互联网相关的工作,但是也一直没有接触过Web开发之类的东西,但是兴趣终归还是要有的,而且是需要自己动手去实践的 ...
- [系统开发] 一个基于Django和PureCSS的内容管理系统
这是我刚开发的一套基于Django和PureCSS的内容管理系统,目标是优雅.简洁.实用,目前功能还在完善中. 系统参考了网上的教程,除了文章管理.搜索.RSS,还增加了类别管理.用户管理,以及评论管 ...
随机推荐
- 一分钟学awk够用
[转载于58同城沈剑] 1.什么是AWK(1)Aho.Weinberger.Kernighan三位发明者名字首字母:(2)一个行文本处理工具: 2.AWK基本原理2.1原理:逐行处理文件中的数据 2. ...
- scrapy爬虫程序xpath中文编码报错
2017-03-23 问题描述: #选择出节点中“时间”二字 <h2>时间</h2> item["file_urls"]= response.xpath(& ...
- ECSHOP删除云服务
一.删除[云服务中心]删除/admin/cloud.php删除/admin/templates/menu.htm中以下代码 Ajax.call('cloud.php?is_ajax=1>act= ...
- 2017.4.7 e.toString() 与 e.getMessage()的区别
我使用的时候,抛出了空指针异常,本来是想将异常信息显示在errorInfo里,却发现没有拿到错误信息. 原因:我用的是getMessage(). 用e.getMessage() 时,返回的是null. ...
- 一起学Netty(一)之 Hello Netty
一起学Netty(一)之 Hello Netty 学习了:https://blog.csdn.net/linuu/article/details/51306480
- Java基础- super 和 this 解析
1. superkeyword表示超(父)类的意思.this变量代表对象本身. 2. super訪问父类被子类隐藏的变量或覆盖的方法.当前类假设是从超类继承而来的,当调用super.XX()就是调用基 ...
- EffectiveJava(8)覆盖equals是要遵守的约定
覆盖equals是要遵守的约定 1.覆盖种类: -类的每个1实例本质上都是唯一的 -不关心类是否提供了"逻辑相等"的测试功能(Random测试是否能随机相同数字) -超类已经覆盖了 ...
- Sending SMS And Dialing Numbers without User Consent(Context is not needed)
Sending SMS And Dialing Numbers without User Consent Sending SMS does not require context or user in ...
- Python线程操作
一.全局锁 1.在Python中,Python代码的执行由Python虚拟机来控制,而在Python虚拟机中,同一时刻只有一个线程在执行,就像单CPU的系统中运行多个进程那样,内存中可以存放多个程序, ...
- 倍福TwinCAT(贝福Beckhoff)基础教程 松下驱动器试运行提示过速度保护怎么办
在试运行的时候,取消勾选自动设定,然后可以自己设置过速度等级设置和过载等级设置 更多教学视频和资料下载,欢迎关注以下信息: 我的优酷空间: http://i.youku.com/acetaoh ...