您的位置:首页 > 编程语言 > Python开发

Python开发【Django】:图片验证码、KindEditor

2017-02-13 16:01 232 查看

图片验证码

生成图片验证码需要以下:

session

check_code.py(依赖:Pillow,字体文件) 模块安装 pip install Pillow

src属性后面加?

在utils下拷贝check_code.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" action="/login.html" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control"  placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control"  placeholder="请输入密码">
</div>
<div class="form-group">
<label for="password">验证码</label>

<div class="row">
<div class="col-xs-7">
<input type="text" class="form-control" placeholder="请输入验证码" name="check_code">
</div>
<div class="col-xs-5">
<img src="/check_code.html" onclick="changeCheckCode(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 changeCheckCode(ths){
ths.src = ths.src +  '?';   //刷新验证码
}
</script>
</body>
</html>


login.html
文件关键的两个点:

<div class="col-xs-5">
<img src="/check_code.html" onclick="changeCheckCode(this);">   <!--点击更换验证码-->
</div>
<script>
function changeCheckCode(ths){
ths.src = ths.src +  '?';   //刷新验证码
}
</script>


处理文件account.py

from io import BytesIO
from django.shortcuts import HttpResponse
from django.shortcuts import render
from utils.check_code import create_validate_code

def check_code(request):
"""
验证码
:param request:
:return:
"""
# 1. 创建一张图片 pip3 install Pillow
# 2. 在图片中写入随机字符串
# obj = object()
# 3. 将图片写入到制定文件
# 4. 打开制定目录文件,读取内容
# 5. HttpResponse(data)

stream = BytesIO()      #在内存中生成一个文件对象
img, code = create_validate_code()  #生成图片img和字符串code
img.save(stream,'PNG')      #把验证图片存放到内存中以PNG名存放
request.session['CheckCode'] = code     #把生成的字符串code存放到session中
print(code)
return HttpResponse(stream.getvalue())      #stream.getvalue()返回图片的内容

def login(request):
"""
登陆
:param request:
:return:
"""
if request.method == 'GET':
return render(request, 'login.html')
elif  request.method == 'POST':
# 此次省略用户名密码验证
code = request.POST.get('check_code')
if code.upper() == request.session['CheckCode'].upper():
print('验证码正确')
return HttpResponse('OK')
else:
print('验证码错误')
return render(request, 'login.html')


上述操作可完成图片验证的认证 

KindEditor文件编辑器

1、进入官网

2、下载

官网下载:http://kindeditor.net/down.php

本地下载:http://files.cnblogs.com/files/wupeiqi/kindeditor_a5.zip

3、文件夹说明

├── asp                          asp示例         可删
├── asp.net                    asp.net示例     可删
├── attached                  空文件夹,放置关联文件attached   可删
├── examples                 HTML示例       可删
├── jsp                          java示例        可删
├── kindeditor-all-min.js 全部JS(压缩)
├── kindeditor-all.js        全部JS(未压缩)
├── kindeditor-min.js      仅KindEditor JS(压缩)
├── kindeditor.js            仅KindEditor JS(未压缩)
├── lang                        支持语言
├── license.txt               License
├── php                        PHP示例         可删
├── plugins                    KindEditor内部使用的插件
└── themes                   KindEditor主题


4、基本使用  

把下载的kind-editor文件拷贝到static目录下

<textarea name="content" id="content"></textarea>

<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
$(function () {
initKindEditor();
});

function initKindEditor() {
// 第一个参数id content 第二个参数字典 进行配置
var kind = KindEditor.create('#content', {
width: '100%',       // 文本框宽度(可以百分比或像素)
height: '300px',     // 文本框高度(只能像素)
minWidth: 200,       // 最小宽度(数字)
minHeight: 400      // 最小高度(数字)
{#            items: ['superscript', 'clearhtml', 'quickformat', 'selectall'] ,// 配置工具栏#}
{#            noDisableItems: ["source", "fullscreen"],  // 得和designMode:false结合使用 表示只显示那些工具#}
{#            designMode: false,#}

});
}
</script>


重点:kind-editor的详细参数--》》http://kindeditor.net/docs/option.html

5、上传文件+文件空间管理

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form>
{% csrf_token %}
<div style="width: 500px;margin: 0 auto">
<textarea id="content"></textarea>
</div>
<input type="submit" value="提交"/>
</form>

<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>
<script>
$(function () {
// 第一个参数id content 第二个参数字典 进行配置
KindEditor.create('#content', {
uploadJson: '/upload_img/',         // 上传地址 图片?dir=image 不同类型dir不一样
fileManagerJson: '/file_manager/',     // 文件空间管理
allowImageRemote: true,             // 是否允许上传远程图片
allowImageUpload: true,            // 是否允许上传图片
allowFileManager: true,
extraFileUploadParams: {            // 这个比较重要,提交csrf_token
csrfmiddlewaretoken: "{{ csrf_token }}"
},
filePostName: 'fafafa'              // 发送文件名
});
})
</script>
</body>
</html>


处理文件:

def kind(request):

return render(request,'kind.html')

def upload_img(request):
# 文件上传
print(request.FILES)
# < MultiValueDict: {'fafafa': [ < InMemoryUploadedFile: 20170213143925.png(image / png) >]} >
dic = {
'error': 0,             # 0表示正确 1为错误
'url': '/static/imgs/20170213143925.png',   #预览图片地址
'message': '错误了...'
}
import json
return HttpResponse(json.dumps(dic))

import os
import time
import json
def file_manager(request):
"""
文件管理
:param request:
:return:
"""
dic = {}
root_path = 'C:/Users/L/PycharmProjects/Django项目'
static_root_path = '/static/'
request_path = request.GET.get('path')
if request_path:
abs_current_dir_path = os.path.join(root_path, request_path)
move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path

else:
abs_current_dir_path = root_path
dic['moveup_dir_path'] = ''

dic['current_dir_path'] = request_path
dic['current_url'] = os.path.join(static_root_path, request_path)

file_list = []
for item in os.listdir(abs_current_dir_path):
abs_item_path = os.path.join(abs_current_dir_path, item)
a, exts = os.path.splitext(item)
is_dir = os.path.isdir(abs_item_path)
if is_dir:
temp = {
'is_dir': True,
'has_file': True,
'filesize': 0,
'dir_path': '',
'is_photo': False,
'filetype': '',
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
else:
temp = {
'is_dir': False,
'has_file': False,
'filesize': os.stat(abs_item_path).st_size,
'dir_path': '',
'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
'filetype': exts.lower().strip('.'),
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}

file_list.append(temp)
dic['file_list'] = file_list
return HttpResponse(json.dumps(dic))


  

《第二十四章》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: