练手小工具--使用Flask框架

    看了点Flask的简介,无聊之中花了点时间搞了个小测试工具出来,代码乱的自己都看不下去,工具的功能不完善,比如POST的时候还不能加入数据,出来的json格式没有解析,Decode时没有判断header中的编码等,后续有时间再优化下

    运行界面如图:

    主要功能:可以对包含参数的url提取参数,用户修改后再对修改后的结果进行GET请求,对没有参数的url可以进行GET或POST请求并返回response

    结构图如下:

    api/     <--根目录

     |

    +-templates    <---模板

             |

            +-api.html

     |

    +-api.py

    

    只有2个文件

    api.html

 1 <html>
 2 <head>
 3 <style type="text/css">
 4 * {margin:0;padding:0;}    
 5 p{font-weight:normal;font-size:16px; height:35px; }
 6 body { background: 0 0 ;margin:0px;}
 7 h2 {color:white;text-align:center;height: 800px;line-height: 80px;}
 8 form {margin:30px}
 9 header {max-width:200em; background:#666;width:100%;height:80px;}
10 input[id="dizhi"] {border:solid 1px #E6E6FA;height:25px;}
11 #getp {background:#1386b7;color: #fff;width: 98px;height:23px;border: medium none;cursor: pointer;}
12 #send {background:#1386b7;color: #fff;width: 48px;height:23px;border: medium none;cursor: pointer;}
13 
14 </style>
15 
16   <title>Api test </title>
17 <!-- This is a comment -->
18 </head>
19 <body class="html" >
20 <header >
21 <h2 >Welcome to Apitest</h1>
22 </header>
23 
24 <form action="/apitest"  method="post" name="form1" >
25 <div  border-style:"solid none">
26     <p >Request address :</p>
27       <p>          <input id ="dizhi"  name="dizhi"  class=dizhi type="text"   size="120" value={{ url }}  >
28       </p>
29 
30     <input id="getp" type="submit" name="action" value="GetParameter" >    
31     <br /><br /> <hr /><br />
32 
33     <p>Parameter :<br/></p>
34     {% for key in rurl: %}  
35     <input  name="pkey" type="text" size="5" value={{ key }} />:&nbsp;&nbsp; <input name="pvalue" type="text" size="5" value={{ rurl[key][0] }} />
36     &nbsp;&nbsp;&nbsp;&nbsp;
37     {% endfor %}
38      <br /> <br />
39      <select name="mtd" ><option value ="GET">GET</option>
40           <option value ="POST">POST</option>
41     </select>&nbsp;&nbsp;&nbsp;
42  <input id="send" type="submit" name="action" value="Send" > 
43  <br /><br />  <hr /><br />
44  <p> Response:</p>
45 <textarea rows="10" cols="130"  >
46 {{ data }}
47 </textarea>
48 </div>
49 </form>
50 </body>
51 </html>

    api.py

 1 # -*- coding: utf-8 -*-
 2 
 3 import re
 4 from flask import Flask, request, render_template
 5 from urllib.parse import urlparse
 6 import urllib
 7 import json
 8 
 9 
10 app = Flask(__name__)
11 
12 @app.route('/apitest', methods=['GET','POST'])
13 
14 def apitest():
15     err = 0
16     testdata = {} 
17     #return render_template('api.html')
18     if request.method == 'POST':
19         url = request.form['dizhi']
20         rurl = urllib.parse.urlparse(url)
21 
22         if request.form["action"] == "GetParameter":    #Click GetParameter button
23             return render_template('api.html',rurl=urllib.parse.parse_qs(rurl.query),url=url)
24         else:     #Click send button
25             if not rurl.query:   #no parameter
26                 if request.form["mtd"] == "GET" :     #Send get
27                     try:
28                         with urllib.request.urlopen(url) as f:
29                             data = f.read()
30                     except Exception as e:
31                         err = e
32                 elif request.form["mtd"] == "POST" :     # Send post 
33                     #req = urllib.request.Request(url,data=None)
34                     try:
35                         req = urllib.request.Request(url,data=None)
36                         req.add_header('Content-Type', 'application/json; charset=utf-8')
37                         jsondata = json.dumps(testdata)
38                         jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
39                         req.add_header('Content-Length', len(jsondataasbytes))
40                         with urllib.request.urlopen(req,jsondataasbytes) as f:
41                             data = f.read()
42                     except Exception as e:
43                         err = e
44                 if err:
45                     return render_template('api.html',rurl=urllib.parse.parse_qs(rurl.query),url=url,data=err)
46                 else:
47                     return render_template('api.html',rurl=urllib.parse.parse_qs(rurl.query),url=url,data=data.decode('utf-8'))
48 
49             else:   #has parameter
50                 if request.form["mtd"] == "GET" :     #Send get
51                     listkey = request.form.getlist('pkey', None)
52                     listvalue = request.form.getlist('pvalue', None)
53                     dic1 = dict(zip(listkey,listvalue))  # 2 lists join to a dic
54                     str=""
55                     for key in dic1:
56                         item = key +'=' + dic1[key]
57                         str = str + '&' + item
58                     uquery = str[1:]    # delete &
59                     urllast = url.split('?')[0] + '?'+ uquery   # the url to request
60                     rurl = urllib.parse.urlparse(urllast)
61                     try:
62                         with urllib.request.urlopen(urllast) as f:
63                             data = f.read()
64                     except Exception as e:
65                         err = e
66                 elif request.form["mtd"] == "POST":     # Send post 
67                     err = "Please select GET"
68                 if err or not data:
69                     return render_template('api.html',rurl=urllib.parse.parse_qs(rurl.query),url=urllast,data=err)
70                 else:
71                     return render_template('api.html',rurl=urllib.parse.parse_qs(rurl.query),url=urllast,data=data.decode('utf-8'))
72         
73 
74     else:
75         return render_template('api.html',url="")
76 
77 
78 if __name__ == '__main__':
79     app.debug = True
80     app.run(host="192.168.2.10",port=9000)
原文地址:https://www.cnblogs.com/Hebe/p/5153134.html