|
|
# 从app模块导入create_app应用工厂函数和db数据库实例
|
|
|
from app import create_app, db
|
|
|
|
|
|
# 从app.models模块导入MonitorPoint监控点模型和MonitorData监控数据模型
|
|
|
from app.models import MonitorPoint, MonitorData
|
|
|
|
|
|
# 从datetime模块导入datetime和timedelta类,用于处理时间计算
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
|
# 导入random模块,用于生成随机数
|
|
|
import random
|
|
|
|
|
|
# 定义创建测试数据的函数
|
|
|
def create_test_data():
|
|
|
# 使用应用工厂函数创建Flask应用实例
|
|
|
app = create_app()
|
|
|
# 在应用上下文中执行数据库操作
|
|
|
with app.app_context():
|
|
|
# 清除现有的测试数据:删除MonitorData表中的所有数据
|
|
|
MonitorData.query.delete()
|
|
|
# 清除现有的测试数据:删除MonitorPoint表中的所有数据
|
|
|
MonitorPoint.query.delete()
|
|
|
|
|
|
# 创建测试监控点的数据列表,包含3个监控点的信息
|
|
|
test_points = [
|
|
|
{
|
|
|
# 监控点名称
|
|
|
'name': '1号养殖池',
|
|
|
# 监控点位置
|
|
|
'location': 'A区-东侧',
|
|
|
# 监控点描述
|
|
|
'description': '草鱼养殖池'
|
|
|
},
|
|
|
{
|
|
|
# 监控点名称
|
|
|
'name': '2号养殖池',
|
|
|
# 监控点位置
|
|
|
'location': 'A区-西侧',
|
|
|
# 监控点描述
|
|
|
'description': '鲫鱼养殖池'
|
|
|
},
|
|
|
{
|
|
|
# 监控点名称
|
|
|
'name': '3号养殖池',
|
|
|
# 监控点位置
|
|
|
'location': 'B区-北侧',
|
|
|
# 监控点描述
|
|
|
'description': '鲤鱼养殖池'
|
|
|
}
|
|
|
]
|
|
|
|
|
|
# 创建空列表用于存储已创建的监控点对象
|
|
|
created_points = []
|
|
|
# 遍历测试监控点数据列表
|
|
|
for point_data in test_points:
|
|
|
# 使用字典解包创建MonitorPoint实例
|
|
|
point = MonitorPoint(**point_data)
|
|
|
# 将新创建的监控点添加到数据库会话中
|
|
|
db.session.add(point)
|
|
|
# 将监控点对象添加到已创建点列表中
|
|
|
created_points.append(point)
|
|
|
|
|
|
# 提交数据库事务,将所有监控点保存到数据库
|
|
|
db.session.commit()
|
|
|
|
|
|
# 为每个监控点生成24小时的测试数据
|
|
|
now = datetime.utcnow() # 获取当前UTC时间
|
|
|
# 遍历所有已创建的监控点
|
|
|
for point in created_points:
|
|
|
# 生成过去24小时的数据,每小时一条记录
|
|
|
# 从24小时前开始,到当前时间为止,倒序遍历
|
|
|
for hours_ago in range(24, -1, -1):
|
|
|
# 计算时间戳(当前时间减去指定小时数)
|
|
|
timestamp = now - timedelta(hours=hours_ago)
|
|
|
|
|
|
# 生成合理范围内的随机数据,创建MonitorData实例
|
|
|
data = MonitorData(
|
|
|
point_id=point.id, # 关联监控点ID
|
|
|
# 生成4.0-8.0之间的随机数作为溶解氧值,保留2位小数
|
|
|
dissolved_oxygen=round(random.uniform(4.0, 8.0), 2),
|
|
|
# 生成6.5-8.5之间的随机数作为pH值,保留2位小数
|
|
|
ph_value=round(random.uniform(6.5, 8.5), 2),
|
|
|
# 生成20.0-28.0之间的随机数作为温度值,保留1位小数
|
|
|
temperature=round(random.uniform(20.0, 28.0), 1),
|
|
|
# 生成0.1-0.5之间的随机数作为氨氮值,保留2位小数
|
|
|
ammonia_nitrogen=round(random.uniform(0.1, 0.5), 2),
|
|
|
# 生成10.0-30.0之间的随机数作为浊度值,保留2位小数
|
|
|
turbidity=round(random.uniform(10.0, 30.0), 2),
|
|
|
timestamp=timestamp # 设置时间戳
|
|
|
)
|
|
|
# 将新创建的监控数据添加到数据库会话中
|
|
|
db.session.add(data)
|
|
|
|
|
|
# 提交数据库事务,将所有监控数据保存到数据库
|
|
|
db.session.commit()
|
|
|
# 打印测试数据创建成功的消息
|
|
|
print('测试数据创建成功!')
|
|
|
|
|
|
# 打印统计信息
|
|
|
# 查询监控点总数
|
|
|
points_count = MonitorPoint.query.count()
|
|
|
# 查询监控数据总数
|
|
|
data_count = MonitorData.query.count()
|
|
|
# 输出监控点数量
|
|
|
print(f'已创建 {points_count} 个监控点')
|
|
|
# 输出监控数据数量
|
|
|
print(f'已创建 {data_count} 条监控数据')
|
|
|
|
|
|
# 主程序入口:当脚本直接运行时执行create_test_data函数
|
|
|
if __name__ == '__main__':
|
|
|
create_test_data()
|