6-交互式犯罪地图
本章将介绍以下主题:
- mysql
- 创建犯罪地图
安装mysql
```#!sh
apt-get install mysql-server
pip3 install pymysql
python db_setup.py # 创建数据库
dbconfig.py
```#!python
test = False
db_user = 'root'
db_password = '654321_'
db_setup.py
```#!python
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
```#!python
from dbhelper import DBHelper
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
DB = DBHelper()
@app.route("/")
def home():
try:
data = DB.get_all_inputs()
except Exception as e:
print(e)
data = None
return render_template("home.html", data=data)
@app.route("/add", methods=["POST"])
def add():
try:
data = request.form.get("userinput")
DB.add_input(data)
except Exception as e:
print(e)
return home()
@app.route("/clear")
def clear():
try:
DB.clear_all()
except Exception as e:
print(e)
return home()
if __name__ == '__main__':
app.run(host='0.0.0.0',port=8000, debug=True)
dbhelper.py
```#!python
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
```#!html
<html>
<body>
<head>
<title>Crime Map</title>
</head>
<h1>Crime Map</h1>
<form action="/add" method="POST">
<input type="text" name="userinput">
<input type="submit" value="Submit">
</form>
<a href="/clear">clear</a>
{% for userinput in data %}
<p>{{userinput}}</p>
{% endfor %}
</body>
</html>
参考资料
- 本文相关书籍下载
- python测试等IT技术支持qq群144081101(后期会录制视频存在该群群文件) 591302926 567351477
- 道家技术-手相手诊看相中医等钉钉群21734177 qq群:391441566 184175668 338228106 看手相、面相、舌相、抽签、体质识别。服务费50元每人次起。请联系钉钉或者微信pythontesting
- 本文最新版本地址
- 本文涉及的python测试开发库 谢谢点赞!
- 接口自动化性能测试线上培训大纲
- 本文代码地址