django做网站涉及到登录界面的验证码功能,验证码本质上是一张图片,图片上显示生成的随机字母和数字,再加上一些干扰处理,既然是一张图片,就要用python 来生成一张图片,在python中处理图像可以用第三方库 PIL(Python Imaging Library)
安装 *PIL
sudo apt-get install python-imaging
生成验证码的代码(checkcode.py)
生成验证码图片.png如果通过 $ python checkcode.py 运行会报错
IOError: cannot open resource
这是字体缺失的原因,下面会讨论
在views.py 中编写代码
from myapp import checkcode
from io import BytesIO
from django.http import HttpResponse,Http404
def create_code_img(request):
f = BytesIO() //在内存中开辟一块空间,用来储存生成的图片
img,code = checkcode.create_code()
request.session['check_code'] = code
img.save(f,'PNG')
return HttpResponse(f.getvalue())
在urls.py中添加路由
url(r'^create_code/$',views.create_code_img),
在login.html/中添加脚本
<img id="check_code_img" src="/create_code/" onclick="refresh_check_code(this)">
当点击验证码时触发onclick事件,调用 refresh_check_code(this)
<script>
function refresh_check_code(ths){
ths.src += '?';
}
</script>
同过在地址后面每次添加一个 ?,从而每次的到的图片都不一样,防止缓存
当网站跑起来的时候,每点击一次验证码,它都会刷新一次,地址也会多加一个问号,图片可以印证这一点
网站对服务器的请求Ubuntu字体缺少的问题
网站跑起来的时候,发现图片一直不能正常显示,发现其实是之前定的字体,在Ubuntu中确实
解决方法有两种
- 安装Windows字体(安装ttf-mscorefonts-installer)
$ sudo apt-get update
$ sudo apt-get install ttf-mscorefonts-installer
接受协议开始安装
接受协议.png更新字体缓存
$ sudo fc-cache -f -v
- 拷贝Windows系统的字体
在Linux创建一个目录用来存放 Winows字体
$ sudo mkdir /usr/share/fonts/WindowsFonts
Windows字体在c:\windows下的Fonts下,拷贝到刚才创建的文件夹下
更改字体文件的权限
$ sudo chmod /usr/shar/fonts/WindowsFonts/*
更新字体缓存
$ sudo fc-cache -f -v
运行
如果通过 $ python checkcode.py 运行没有报错
最后
python manage.py runserver localhost:8000
效果图.png
网友评论