[雪峰磁针石博客]flask构建自动化测试平台7-添加google地图

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 本章将介绍以下主题: mock数据库 创建犯罪地图 本文最新版本 代码地址 mock数据库 mockdbhelper.py class MockDBHelper: def connect(self, database="crimemap"): pass def.

本章将介绍以下主题:

  • mock数据库
  • 创建犯罪地图

本文最新版本
代码地址

mock数据库

mockdbhelper.py


class MockDBHelper:

    def connect(self, database="crimemap"):
        pass

    def add_crime(self, category, date, latitude, longitude, description):
        data = [category, date, latitude, longitude, description]
        for i in data:
            print (i, type(i))

    def get_all_crimes(self):
        return [{'latitude': -33.301304,
                 'longitude': 26.523355,
                 'date': "2000-01-01",
                 'category': "mugging",
                 'description': "mock description"}]

    def add_input(self, data):
        pass

    def clear_all(self):
        pass

db_setup.py


import pymysql
import dbconfig
connection = pymysql.connect(host='localhost',
                             user=dbconfig.db_user,
                             passwd=dbconfig.db_password)

try:
    with connection.cursor() as cursor:
        sql = "CREATE DATABASE IF NOT EXISTS crimemap"
        cursor.execute(sql)
        sql = """CREATE TABLE IF NOT EXISTS crimemap.crimes (
id int NOT NULL AUTO_INCREMENT,
latitude FLOAT(10,6),
longitude FLOAT(10,6),
date DATETIME,
category VARCHAR(50),
description VARCHAR(255),
updated_at TIMESTAMP,
PRIMARY KEY (id)
)"""
        cursor.execute(sql)
    connection.commit()
finally:
    connection.close()

crimemap.py


from flask import Flask
from flask import render_template
from flask import request
import json
import dbconfig
if dbconfig.test:
    from mockdbhelper import MockDBHelper as DBHelper
else:
    from dbhelper import DBHelper

app = Flask(__name__)
DB = DBHelper()


@app.route("/")
def home():
    crimes = DB.get_all_crimes()
    crimes = json.dumps(crimes)
    return render_template("home.html", crimes=crimes)


@app.route("/submitcrime", methods=['POST'])
def submitcrime():
    category = request.form.get("category")
    date = request.form.get("date")
    latitude = float(request.form.get("latitude"))
    longitude = float(request.form.get("longitude"))
    description = request.form.get("description")
    DB.add_crime(category, date, latitude, longitude, description)
    return home()


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=8000, debug=True)

dbconfig.py


test = True

dbhelper.py


import pymysql
import dbconfig


class DBHelper:

    def connect(self, database="crimemap"):
        return pymysql.connect(host='localhost',
                               user=dbconfig.db_user,
                               passwd=dbconfig.db_password,
                               db=database)

    def get_all_inputs(self):
        connection = self.connect()
        try:
            query = "SELECT description FROM crimes;"
            with connection.cursor() as cursor:
                cursor.execute(query)
            return cursor.fetchall()
        finally:
            connection.close()

    def add_input(self, data):
        connection = self.connect()
        try:
            query = "INSERT INTO crimes (description) VALUES (%s);"
            with connection.cursor() as cursor:
                cursor.execute(query, data)
                connection.commit()
        finally:
            connection.close()

    def clear_all(self):
        connection = self.connect()
        try:
            query = "DELETE FROM crimes;"
            with connection.cursor() as cursor:
                cursor.execute(query)
                connection.commit()
        finally:
            connection.close()

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>
        <form action="/submitcrime" method="POST">
        <label for="category">Category</label> 
        <select name="category" id="category">
            <option value="mugging">Mugging</option>
            <option value="breakin">Break-in</option>
        </select> 
        </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">
        <label for="longitude">Longitude</label>
        <input name="longitude" id="longitude" type="text">
        <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>

style.css


body { 
    font-family: sans-serif; 
    background: #eee; 
}

#map-canvas {
    width: 70%;
    height: 500px;
    float: left;
}

#newcrimeform {
    float: right;
    width: 25%;
}

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;
}

image.png

参考资料

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
4月前
|
边缘计算 安全 5G
高精度时钟同步测试仪:构建全场景时间同步生态
在数字化转型中,时间同步至关重要。西安同步电子科技的 SYN5106 高精度时钟测试仪,具备±20ns 时差测量精度与 GPS/北斗双模授时能力,广泛应用于电力、通信、金融和科研领域。它解决变电站时间偏差、5G 基站同步误差及高频交易延迟等问题,助力智能电网、5G 网络和科研实验。产品便携可靠,支持多协议,满足国家安全要求,为各行业提供精准时间同步解决方案。未来将探索量子通信与深空探测等领域,持续推动技术创新。
|
8月前
|
分布式计算 Shell MaxCompute
odps测试表及大量数据构建测试
odps测试表及大量数据构建测试
|
6月前
|
机器学习/深度学习 设计模式 测试技术
Python 高级编程与实战:构建自动化测试框架
本文深入探讨了Python中的自动化测试框架,包括unittest、pytest和nose2,并通过实战项目帮助读者掌握这些技术。文中详细介绍了各框架的基本用法和示例代码,助力开发者快速验证代码正确性,减少手动测试工作量。学习资源推荐包括Python官方文档及Real Python等网站。
|
10月前
|
jenkins 测试技术 持续交付
自动化测试框架的构建与优化:提升软件交付效率的关键####
本文深入探讨了自动化测试框架的核心价值,通过对比传统手工测试方法的局限性,揭示了自动化测试在现代软件开发生命周期中的重要性。不同于常规摘要仅概述内容,本部分强调了自动化测试如何显著提高测试覆盖率、缩短测试周期、降低人力成本,并促进持续集成/持续部署(CI/CD)流程的实施,最终实现软件质量和开发效率的双重飞跃。通过具体案例分析,展示了从零开始构建自动化测试框架的策略与最佳实践,包括选择合适的工具、设计高效的测试用例结构、以及如何进行性能调优等关键步骤。此外,还讨论了在实施过程中可能遇到的挑战及应对策略,为读者提供了一套可操作的优化指南。 ####
|
3月前
|
Java 测试技术 容器
Jmeter工具使用:HTTP接口性能测试实战
希望这篇文章能够帮助你初步理解如何使用JMeter进行HTTP接口性能测试,有兴趣的话,你可以研究更多关于JMeter的内容。记住,只有理解并掌握了这些工具,你才能充分利用它们发挥其应有的价值。+
739 23
|
8月前
|
数据可视化 前端开发 测试技术
接口测试新选择:Postman替代方案全解析
在软件开发中,接口测试工具至关重要。Postman长期占据主导地位,但随着国产工具的崛起,越来越多开发者转向更适合中国市场的替代方案——Apifox。它不仅支持中英文切换、完全免费不限人数,还具备强大的可视化操作、自动生成文档和API调试功能,极大简化了开发流程。
|
5月前
|
SQL 安全 测试技术
2025接口测试全攻略:高并发、安全防护与六大工具实战指南
本文探讨高并发稳定性验证、安全防护实战及六大工具(Postman、RunnerGo、Apipost、JMeter、SoapUI、Fiddler)选型指南,助力构建未来接口测试体系。接口测试旨在验证数据传输、参数合法性、错误处理能力及性能安全性,其重要性体现在早期发现问题、保障系统稳定和支撑持续集成。常用方法包括功能、性能、安全性及兼容性测试,典型场景涵盖前后端分离开发、第三方服务集成与数据一致性检查。选择合适的工具需综合考虑需求与团队协作等因素。
681 24
|
5月前
|
SQL 测试技术
除了postman还有什么接口测试工具
最好还是使用国内的接口测试软件,其实国内替换postman的软件有很多,这里我推荐使用yunedit-post这款接口测试工具来代替postman,因为它除了接口测试功能外,在动态参数的支持、后置处理执行sql语句等支持方面做得比较好。而且还有接口分享功能,可以生成接口文档给团队在线浏览。
236 2
|
7月前
|
JSON 前端开发 测试技术
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
333 10
大前端之前端开发接口测试工具postman的使用方法-简单get接口请求测试的使用方法-简单教学一看就会-以实际例子来说明-优雅草卓伊凡
|
7月前
|
JSON 前端开发 API
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡
334 5
以项目登录接口为例-大前端之开发postman请求接口带token的请求测试-前端开发必学之一-如果要学会联调接口而不是纯写静态前端页面-这个是必学-本文以优雅草蜻蜓Q系统API为实践来演示我们如何带token请求接口-优雅草卓伊凡

热门文章

最新文章

推荐镜像

更多