美文网首页程序员工具癖
flask工具构建自动化测试平台8-验证用户输入

flask工具构建自动化测试平台8-验证用户输入

作者: python测试开发 | 来源:发表于2018-09-16 00:08 被阅读56次

    主要内容:

    •选择验证点
    •验证

    验证点

    服务器端和客户端需要兼顾。

    把犯罪地图增加验证

    style.css

    body { 
        font-family: sans-serif; 
        background: #eee; 
    }
    
    #map-canvas {
        width: 70%;
        height: 500px;
        float: left;
    }
    
    #newcrimeform {
        float: right;
        width: 25%;
    }
    
    #error {
        color: red;
    }
    
    input, select, textarea { 
        display: block;
        color: grey;
        border: 1px solid lightsteelblue;
        line-height: 15px;
        margin: 2px 6px 16px 0px;
        width: 100%;
    }
    
    input[type="submit"] {
        padding: 5px 10px 5px 10px;
        color: black;
        background: lightsteelblue;
        border: none;
        box-shadow: 1px 1px 1px #4C6E91;
    }
    
    input[type="submit"]:hover {
        background: steelblue;
    }
    

    模板home.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
    
      <link type="text/css" rel="stylesheet" href="{{url_for('static', filename='css/style.css') }}" /> 
    
      <script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js">
      </script> 
    
      <script type="text/javascript">
        var map;
        var marker;
        var existing_crimes;
    
        function initialize() { 
          var mapOptions = {
            center: new google.maps.LatLng(-33.30578381949298, 26.523442268371582),
            zoom: 15
          };
          map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
          google.maps.event.addListener(map, 'click', function(event){   
            placeMarker(event.latLng);
          });
          placeCrimes({{crimes | safe}});
        }
    
        function placeCrimes(crimes) {
          for (i=0; i<crimes.length; i++) {
            crime = new google.maps.Marker( {
              position: new google.maps.LatLng(crimes[i].latitude, crimes[i].longitude),
              map: map,
              title: crimes[i].date + "\n" + 
                crimes[i].category + "\n" + crimes[i].description
              }
            );
          }
        }
    
        function placeMarker(location) {
          if (marker) {
            marker.setPosition(location);
          } else {
            marker = new google.maps.Marker({
              position: location, 
              map: map
            });
          }
        document.getElementById('latitude').value = location.lat();
        document.getElementById('longitude').value = location.lng();
        }
      </script>
      
    </head>
      <body onload="initialize()">
          <h1>CrimeMap</h1>
          <p>A map of recent criminal activity in the Grahamstown area.</p>
          <div id="map-canvas"></div>
    
          <div id="newcrimeform">
            <h2>Submit new crime</h2>
            {% if error_message %}
              <div id="error"><p>{{error_message}}</p></div>
            {% endif %}
            <form action="/submitcrime" method="POST">
            <label for="category">Category</label> 
            <select name="category" id="category">
              {% for category in categories %}
                <option value="{{category}}">{{category}}</option>
              {% endfor %}
            </select> 
            <label for="date">Date</label>
            <input name="date" id="date" type="date">
            <label for="latitude">Latitude</label>
            <input name="latitude" id="latitude" type="text" readonly>
            <label for="longitude">Longitude</label>
            <input name="longitude" id="longitude" type="text" readonly>
            <label for="description">Description</label>
            <textarea name="description" id="description" placeholder="A brief but detailed description of the crime"></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </body>
    </html>
    
    

    crimemap.py

    from flask import Flask
    from flask import render_template
    from flask import request
    import json
    import dateparser
    import datetime
    import string
    import dbconfig
    if dbconfig.test:
        from mockdbhelper import MockDBHelper as DBHelper
    else:
        from dbhelper import DBHelper
    
    
    app = Flask(__name__)
    DB = DBHelper()
    
    categories = ['mugging', 'break-in']
    
    
    def sanitize_string(userinput):
        whitelist = string.ascii_letters + string.digits + " !?.,;:-'()&"
        return filter(lambda x: x in whitelist, userinput)
    
    
    def format_date(userdate):
        date = dateparser.parse(userdate)
        try:
            return datetime.datetime.strftime(date, "%Y-%m-%d")
        except TypeError:
            return None
    
    
    @app.route("/")
    def home(error_message=None):
        crimes = DB.get_all_crimes()
        crimes = json.dumps(crimes)
        return render_template("home.html", crimes=crimes, categories=categories, error_message=error_message)
    
    
    @app.route("/submitcrime", methods=['POST'])
    def submitcrime():
        try:
            error_message = None
            category = request.form.get("category")
            if category not in categories:
                return home()
    
            date = format_date(request.form.get("date"))
            if not date:
                return home("Invalid date. Please use yyyy-mm-dd format")
            try:
                latitude = float(request.form.get("latitude"))
                longitude = float(request.form.get("longitude"))
            except:
                error_message = "Latitude and Longitude have incorrect format"
                return home(error_message)
            description = sanitize_string(request.form.get("description"))
            DB.add_crime(category, date, latitude, longitude, description)
            return home()
        except Exception as e:
            print(e)
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0',port=8000, debug=True)
    
    

    参考资料

    • 讨论qq群144081101 591302926 567351477 钉钉免费群21745728
    image.png

    相关文章

      网友评论

        本文标题:flask工具构建自动化测试平台8-验证用户输入

        本文链接:https://www.haomeiwen.com/subject/woctnftx.html