python第一百一十八天---ajax--图片验证码 + Session

原生AJAX
  
Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。

1、XmlHttpRequest对象介绍
XmlHttpRequest对象的主要方法:
 1 XmlHttpRequest对象的主要方法:
 2     a. void open(String method,String url,Boolen async)
 3    用于创建请求
 4 
 5    参数:
 6        method: 请求方式(字符串类型),如:POST、GET、DELETE...
 7        url:    要请求的地址(字符串类型)
 8        async:  是否异步(布尔类型)
 9 
10 b. void send(String body)
11     用于发送请求
12 
13     参数:
14         body: 要发送的数据(字符串类型)
15 
16 c. void setRequestHeader(String header,String value)
17     用于设置请求头
18 
19     参数:
20         header: 请求头的key(字符串类型)
21         vlaue:  请求头的value(字符串类型)
22 
23 d. String getAllResponseHeaders()
24     获取所有响应头
25 
26     返回值:
27         响应头数据(字符串类型)
28 
29 e. String getResponseHeader(String header)
30     获取响应头中指定header的值
31 
32     参数:
33         header: 响应头的key(字符串类型)
34 
35     返回值:
36         响应头中指定的header对应的值
37 
38 f. void abort()
39 
40     终止请求
View Code
XmlHttpRequest对象的主要属性:
 1 a. Number readyState
 2    状态值(整数)
 3 
 4    详细:
 5       0-未初始化,尚未调用open()方法;
 6       1-启动,调用了open()方法,未调用send()方法;
 7       2-发送,已经调用了send()方法,未接收到响应;
 8       3-接收,已经接收到部分响应数据;
 9       4-完成,已经接收到全部响应数据;
10 
11     b. Function onreadystatechange
12        当readyState的值改变时自动触发执行其对应的函数(回调函数)
13 
14     c. String responseText
15        服务器返回的数据(字符串类型)
16 
17     d. XmlDocument responseXML
18        服务器返回的数据(Xml对象)
19 
20     e. Number states
21        状态码(整数),如:200、404...
22 
23     f. String statesText
24        状态文本(字符串),如:OK、NotFound...
View Code
2、跨浏览器支持
  
XmlHttpRequest
IE7+, Firefox, Chrome, Opera, etc.
ActiveXObject("Microsoft.XMLHTTP")
IE6, IE5


基于原生AJAX - Demo
 1 <!DOCTYPE html>
 2     <html>
 3     <head lang="en">
 4         <meta charset="UTF-8">
 5         <title></title>
 6     </head>
 7     <body>
 8 
 9         <h1>XMLHttpRequest - Ajax请求</h1>
10         <input type="button" οnclick="XmlGetRequest();" value="Get发送请求" />
11         <input type="button" οnclick="XmlPostRequest();" value="Post发送请求" />
12 
13         <script src="/statics/jquery-1.12.4.js"></script>
14         <script type="text/javascript">
15 
16             function GetXHR(){
17                 var xhr = null;
18                 if(XMLHttpRequest){
19                     xhr = new XMLHttpRequest();
20                 }else{
21                     xhr = new ActiveXObject("Microsoft.XMLHTTP");
22                 }
23                 return xhr;
24 
25             }
26 
27             function XhrPostRequest(){
28                 var xhr = GetXHR();
29                 // 定义回调函数
30                 xhr.onreadystatechange = function(){
31                     if(xhr.readyState == 4){
32                         // 已经接收到全部响应数据,执行以下操作
33                         var data = xhr.responseText;
34                         console.log(data);
35                     }
36                 };
37                 // 指定连接方式和地址----文件方式
38                 xhr.open('POST', "/test/", true);
39                 // 设置请求头
40                 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
41                 // 发送请求
42                 xhr.send('n1=1;n2=2;');
43             }
44 
45             function XhrGetRequest(){
46                 var xhr = GetXHR();
47                 // 定义回调函数
48                 xhr.onreadystatechange = function(){
49                     if(xhr.readyState == 4){
50                         // 已经接收到全部响应数据,执行以下操作
51                         var data = xhr.responseText;
52                         console.log(data);
53                     }
54                 };
55                 // 指定连接方式和地址----文件方式
56                 xhr.open('get', "/test/", true);
57                 // 发送请求
58                 xhr.send();
59             }
60 
61         </script>
62 
63     </body>
64     </html>
View Code

 



jQuery Ajax
jQuery其实就是一个JavaScript的类库,其将复杂的功能做了上层封装,使得开发者可以在其基础上写更少的代码实现更多的功能。
jQuery 不是生产者,而是大自然搬运工。
jQuery Ajax本质 XMLHttpRequest 或 ActiveXObject
注:2.+版本不再支持IE9以下的浏览器


 1 jQuery Ajax 方法列表
 2     jQuery.get(...)
 3                 所有参数:
 4                      url: 待载入页面的URL地址
 5                     data: 待发送 Key/value 参数。
 6                  success: 载入成功时回调函数。
 7                 dataType: 返回内容格式,xml, json,  script, text, html
 8 
 9 
10             jQuery.post(...)
11                 所有参数:
12                      url: 待载入页面的URL地址
13                     data: 待发送 Key/value 参数
14                  success: 载入成功时回调函数
15                 dataType: 返回内容格式,xml, json,  script, text, html
16 
17 
18             jQuery.getJSON(...)
19                 所有参数:
20                      url: 待载入页面的URL地址
21                     data: 待发送 Key/value 参数。
22                  success: 载入成功时回调函数。
23 
24 
25             jQuery.getScript(...)
26                 所有参数:
27                      url: 待载入页面的URL地址
28                     data: 待发送 Key/value 参数。
29                  success: 载入成功时回调函数。
30 
31 
32             jQuery.ajax(...)
33 
34                 部分参数:
35 
36                         url:请求地址
37                        type:请求方式,GET、POST(1.9.0之后用method)
38                     headers:请求头
39                        data:要发送的数据
40                 contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
41                       async:是否异步
42                     timeout:设置请求超时时间(毫秒)
43 
44                  beforeSend:发送请求前执行的函数(全局)
45                    complete:完成之后执行的回调函数(全局)
46                     success:成功之后执行的回调函数(全局)
47                       error:失败之后执行的回调函数(全局)
48 
49 
50                     accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
51                    dataType:将服务器端返回的数据转换成指定类型
52                                    "xml": 将服务器端返回的内容转换成xml格式
53                                   "text": 将服务器端返回的内容转换成普通文本格式
54                                   "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
55                                 "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
56                                   "json": 将服务器端返回的内容转换成相应的JavaScript对象
57                                  "jsonp": JSONP 格式
58                                           使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
59 
60                                   如果不指定,jQuery 将自动根据HTTP包MIME信息返回相应类型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string
61 
62                  converters: 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数
63                          $.ajax({
64                               accepts: {
65                                 mycustomtype: 'application/x-some-custom-type'
66                               },
67 
68                               // Expect a `mycustomtype` back from server
69                               dataType: 'mycustomtype'
70 
71                               // Instructions for how to deserialize a `mycustomtype`
72                               converters: {
73                                 'text mycustomtype': function(result) {
74                                   // Do Stuff
75                                   return newresult;
76                                 }
77                               },
78                             });
View Code

 

基于jQueryAjax - Demo
 1 <!DOCTYPE html>
 2     <html>
 3     <head lang="en">
 4         <meta charset="UTF-8">
 5         <title></title>
 6     </head>
 7     <body>
 8 
 9         <p>
10             <input type="button" οnclick="XmlSendRequest();" value='Ajax请求' />
11         </p>
12 
13 
14         <script type="text/javascript" src="jquery-1.12.4.js"></script>
15         <script>
16 
17             function JqSendRequest(){
18                 $.ajax({
19                     url: "http://c2.com:8000/test/",
20                     type: 'GET',
21                     dataType: 'text',
22                     success: function(data, statusText, xmlHttpRequest){
23                         console.log(data);
24                     }
25                 })
26             }
27 
28 
29         </script>
30     </body>
31     </html>
View Code

 

 

图片验证码 + Session

check_code.py

 

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 
  4 import random
  5 from PIL import Image, ImageDraw, ImageFont, ImageFilter
  6 
  7 _letter_cases = "abcdefghjkmnpqrstuvwxy"  # 小写字母,去除可能干扰的i,l,o,z
  8 _upper_cases = _letter_cases.upper()  # 大写字母
  9 _numbers = ''.join(map(str, range(3, 10)))  # 数字
 10 init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
 11 
 12 
 13 def create_validate_code(size=(120, 30),
 14                          chars=init_chars,
 15                          img_type="GIF",
 16                          mode="RGB",
 17                          bg_color=(255, 255, 255),
 18                          fg_color=(0, 0, 255),
 19                          font_size=18,
 20                          font_type="Monaco.ttf",
 21                          length=4,
 22                          draw_lines=True,
 23                          n_line=(1, 2),
 24                          draw_points=True,
 25                          point_chance=2):
 26     """
 27     @todo: 生成验证码图片
 28     @param size: 图片的大小,格式(宽,高),默认为(120, 30)
 29     @param chars: 允许的字符集合,格式字符串
 30     @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
 31     @param mode: 图片模式,默认为RGB
 32     @param bg_color: 背景颜色,默认为白色
 33     @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
 34     @param font_size: 验证码字体大小
 35     @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
 36     @param length: 验证码字符个数
 37     @param draw_lines: 是否划干扰线
 38     @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
 39     @param draw_points: 是否画干扰点
 40     @param point_chance: 干扰点出现的概率,大小范围[0, 100]
 41     @return: [0]: PIL Image实例
 42     @return: [1]: 验证码图片中的字符串
 43     """
 44 
 45     width, height = size  # 宽高
 46     # 创建图形
 47     img = Image.new(mode, size, bg_color)
 48     draw = ImageDraw.Draw(img)  # 创建画笔
 49 
 50     def get_chars():
 51         """生成给定长度的字符串,返回列表格式"""
 52         return random.sample(chars, length)
 53 
 54     def create_lines():
 55         """绘制干扰线"""
 56         line_num = random.randint(*n_line)  # 干扰线条数
 57 
 58         for i in range(line_num):
 59             # 起始点
 60             begin = (random.randint(0, size[0]), random.randint(0, size[1]))
 61             # 结束点
 62             end = (random.randint(0, size[0]), random.randint(0, size[1]))
 63             draw.line([begin, end], fill=(0, 0, 0))
 64 
 65     def create_points():
 66         """绘制干扰点"""
 67         chance = min(100, max(0, int(point_chance)))  # 大小限制在[0, 100]
 68 
 69         for w in range(width):
 70             for h in range(height):
 71                 tmp = random.randint(0, 100)
 72                 if tmp > 100 - chance:
 73                     draw.point((w, h), fill=(0, 0, 0))
 74 
 75     def create_strs():
 76         """绘制验证码字符"""
 77         c_chars = get_chars()
 78         strs = ' %s ' % ' '.join(c_chars)  # 每个字符前后以空格隔开
 79 
 80         font = ImageFont.truetype(font_type, font_size)
 81         font_width, font_height = font.getsize(strs)
 82 
 83         draw.text(((width - font_width) / 3, (height - font_height) / 3),
 84                   strs, font=font, fill=fg_color)
 85 
 86         return ''.join(c_chars)
 87 
 88     if draw_lines:
 89         create_lines()
 90     if draw_points:
 91         create_points()
 92     strs = create_strs()
 93 
 94     # 图形扭曲参数
 95     params = [1 - float(random.randint(1, 2)) / 100,
 96               0,
 97               0,
 98               0,
 99               1 - float(random.randint(1, 10)) / 100,
100               float(random.randint(1, 2)) / 500,
101               0.001,
102               float(random.randint(1, 2)) / 500
103               ]
104     img = img.transform(size, Image.PERSPECTIVE, params)  # 创建扭曲
105 
106     img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜,边界加强(阈值更大)
107 
108     return img, strs
View Code

 





转载于:https://www.cnblogs.com/uge3/p/7464761.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值