目录

1、上传文件  

2、验证码  

一、上传文件

首先了解一下 request.FILES :

字典 request.FILES 中的每一个条目都是一个UploadFile对象。UploadFile对象有如下方法:
1、UploadFile.read():
从文件中读取全部上传数据。当上传文件过大时,可能会耗尽内存,慎用。
2、UploadFile.multiple_chunks():
如上传文件足够大,要分成多个部分读入时,返回True.默认情况,当上传文件大于2.5M时,返回True。但这一个值可以配置。
3、UploadFile.chunks():
返回一个上传文件的分块生成器。如multiple_chunks()返回True,必须在循环中使用chrunks()来代替read()。一般情况下直接使用chunks()就行。
4、UploadFile.name:上传文件的文件名
5、UplaodFile.size:上传文件的文件大小(字节)

django普通版本上传

models.py

class UploadFile(models.Model):
username =models.CharField(max_length=50)
uploadfile = models.FileField(upload_to='./static/')#指定的upload目录相对于根目录下media目录 def __str__(self):
return self.username

  

index.html

<form method="post" enctype="multipart/form-data">
<label>用户名:</label><input type="text" name="username" />
<label>文 件:</label><input type="file" name="uploadfile" />
<input type="submit" value="'提交" />
</form>

 

views.py

def index(request):
if request.method == 'POST':
un = request.POST.get('username')
print(un)
f = request.FILES.get('uploadfile')#'uploadfile'与提交表单中input名一致,多个文件参见getlist()
filename = os.path.join('static', f.name) #存放内容的目标文件
# 123 = os.path.join('static', 'images', filename.name)
with open(filename, 'wb') as keys:
for chunk in f.chunks():#chunks()方法将文件切分成为块(<=2.5M)的迭代对象
keys.write(chunk)
#新数据表信息
models.UploadFile.objects.create(username=un, uploadfile=filename)
return HttpResponse(filename + 'ok')
return render_to_response('index.html', {})

  

django from上传

models.py

class UploadFile(models.Model):
username =models.CharField(max_length=50)
uploadfile = models.FileField(upload_to='./static/')#指定的upload目录相对于根目录下media目录 def __str__(self):
return self.username

  

mo.html

<form method="post" enctype="multipart/form-data">
{{ uf.username }}
{{ uf.uploadfile }}
<input type="submit" value="'提交" />
</form>

  

forms.py

from django import forms

class UploadForm(forms.Form):
username = forms.CharField()
uploadfile = forms.FileField()

  

views.py

def model(request):
if request.method =='POST':
uf =forms.UploadForm(request.POST,request.FILES)
if uf.is_valid():
username =uf.cleaned_data['username']
uploadfile=uf.cleaned_data['uploadfile']
u = models.UploadFile()
u.username=username
u.uploadfile=uploadfile
u.save()
return HttpResponse('ok')
uf = forms.UploadForm()
return render_to_response('mo.html',{'uf':uf})

  

Ajax上传文件

html文件

    <div>
{{ uf.uploadfile }}
<input type="button" id="submitj" value="提交" />
</div> <script src="/static/jquery-2.1.4.min.js"></script>
<script>
$('#submitj').bind("click",function () {
var file = $('#id_uploadfile')[0].files[0];
console.log("fff",file);
var form = new FormData();
form.append('uploadfile', file);
$.ajax({ type:'POST',
url: '/mo/',
data: form,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(arg){ }
})
})
</script>

  

views.py

def UploadFile(request):
print(request.FILES)
uf = forms.uploadForm(request.POST, request.FILES)
print(uf.is_valid())
if uf.is_valid():
upoad = models.UploadFile()
print(123234)
upoad.username = 'alex'
upoad.uploadfile = uf.cleaned_data['uploadfile']
upoad.save()
return render(request,'ajax.html',locals())

 

forms.py 

from django import forms

class uploadForm(forms.Form):

    uploadfile = forms.FileField()

  

models.py

class UploadFile(models.Model):
username =models.CharField(max_length=50)
uploadfile = models.FileField(upload_to='./static/')#指定的upload目录相对于根目录下media目录 def __str__(self):
return self.username

  

二、验证码

views.py

import io
import os
from django_code import check_code def check_coder(request):
mstream = io.BytesIO()
img, code = check_code.create_validate_code()
img.save(mstream, "GIF")
request.session["CheckCode"] = code ##写入session
print(mstream.getvalue())
return HttpResponse(mstream.getvalue())

  

check_code.py 文件

#!/usr/bin/env python
#coding:utf-8 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

文件连接 Monaco.ttf 字体文件

http://www.gringod.com/2006/02/24/return-of-monacottf/

python 小功能的更多相关文章

  1. python小功能记录

    本博客会不断完善,记录python小功能. 1. 合并两个字典 # in Python 3.5+ >>> x = {'a': 1, 'b': 2} >>> y = ...

  2. 五、python小功能记录——打包程序

    使用pyinstaller打包Python程序 安装工具 :pip3 install pyinstaller 在Python程序文件夹上(不点进去)按住shift并且右键,在弹出的选项中点击" ...

  3. 三、python小功能记录——杀掉进程

    import os os.system("taskkill /F /IM python.exe")#旧版 os.system("taskkill /F /IM py.ex ...

  4. Python小功能汇总

    1.没有文件夹就新建 适用以下3种情况. (1)文件夹适用 (2)相对路径适用 (3)绝对路径适用 # 判断输出文件夹是否存在.不存在就创建 # 1.output_dir为绝对路径 if os.pat ...

  5. 四、python小功能记录——按键转点击事件

    import win32api,win32gui,win32confrom pynput.keyboard import Listener def clickLeftCur(): win32api.m ...

  6. 二、python小功能记录——监听鼠标事件

    1.原文链接 #-*- coding:utf-8 -*- from pynput.mouse import Button, Controller ## ======================== ...

  7. 一、python小功能记录——监听键盘事件

    1.监听键盘按键 from pynput.keyboard import Listener def press(key): print(key.char) with Listener(on_press ...

  8. python实现简单的循环购物车小功能

    python实现简单的循环购物车小功能 # -*- coding: utf-8 -*- __author__ = 'hujianli' shopping = [ ("iphone6s&quo ...

  9. 怎么样通过编写Python小程序来统计测试脚本的关键字

    怎么样通过编写Python小程序来统计测试脚本的关键字 通常自动化测试项目到了一定的程序,编写的测试代码自然就会很多,如果很早已经编写的测试脚本现在某些基础函数.业务函数需要修改,那么势必要找出那些引 ...

随机推荐

  1. ABP学习日记1

  2. .NET Core全面扫盲贴

    标签: .NETCore Asp.NETCore 1. 前言 2. .NET Core 简介 2.1 .NET Core是什么 2.2 .NET Core的组成 2.3 .NET Core的特性 2. ...

  3. js正则表达式校验非负浮点数:^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. VMware12下安装Debian8.5

    参考:  Debian 8.2.0 (Jessie) 快速纯净安装教程    Debian 7 安装配置总结    Debian 7.8 系统安装配置过程 软件包管理命令    包命令    从源代码 ...

  5. angular的$filter服务

    首先,介绍下$filter服务: 1.$filter是用来进行数据格式化的专用服务: 2.AngularJS内置了currency.date.filter.json.limitTo.lowercase ...

  6. Web Service随笔

    什么是Web Service? WebService是一个SOA(面向服务的编程)的架构,它是不依赖于语言,不依赖于平台,可以实现不同的语言间的相互调用,通过Internet进行基于Http协议的网络 ...

  7. html和html5详解

    最近看群里聊天聊得最火热的莫过于手机网站和html5这两个词.可能有人会问,这两者有什么关系呢?随着这移动互联网快速发展的时代,尤其是4G时代已经来临的时刻,加上微软对"XP系统" ...

  8. Using AlloyTouch to control three.js 3D model

    As you can see, the above cube rotation, acceleration, deceleration stop all through the AlloyTouch ...

  9. Xcode7使用插件的简单方法&&以及怎样下载到更早版本的Xcode

    Xcode7自2015年9上架以来也有段时间了, 使用Xcode7以及Xcode7.1\Xcode7.2的小伙伴会发现像VVDocumenter-Xcode\KSImageNamed-Xcode\HO ...

  10. Android面试题(一)

    1. 请描述一下Activity 生命周期. 答: 如下图所示.共有七个周期函数,按顺序分别是: onCreate(), onStart(), onRestart(), onResume(), onP ...