如何通过python脚本向redis和mongoDB传点位数据
- 向MongoDB传数据
from pymongo import MongoClient #导入库对应的库localhost = "172.16.0.203" #数据库IP地址
baseName = "GreenNagoya"
client = MongoClient(localhost, 27017, username="admin", password="zdiai@123") #数据库端口、账号及密码database = client["Repo_history"] #需要链接到具体哪个数据库
collection = database[baseName] #需要链接数据库中的哪张表#data里面是需要传入的key值,key的话需要根据产品提供的key来
data = {"engineSpeed":100,"rotationRate":120,"speedOnWater":11,"seaFuel":121,"hostPower":123,"groundSpeed":122,"totalPower":144,"shipSlipRate":134,"rudderAngle":12,"shipBow":32,"somskey1":333,"test_somekey02":34,"test_somekey":12,"fuelEfficiency":56,}
collection.insert_one(data)
2.向redis传入数据
import redis# 连接到 Redis 的 2 号库
try:r = redis.Redis(host='172.16.2.225',port=6379,password='zdiai@123',db=2,decode_responses=True)# 测试连接r.ping()print("成功连接到 Redis 的 2 号库")# 要发送的数据data = {"GJDV000000507": 0.0,"GJAQ000000184": 135.78398387830148,"GJAQ000000185": 210.68863292915802,"GJAQ000000182": 0.0,"GJAQ000000183": -19.183531240737473,"GJAQ000000180": 0.0,"GJAQ000000181": 0.0,"GJAQ000000179": 0.0,"WaterDepth": 11.63,"GJAQ000000153": 5.35572092959191,"timestamp": 1744801910,"GJAQ000000162": 0.0,"GJAQ000000163": 0.0,}# 往 Redis 中设置数据for key, value in data.items():r.set(key, value)print("数据已成功发送到 Redis 的 2 号库")except redis.exceptions.ConnectionError:print("无法连接到 Redis,请检查主机、端口和密码。")
except redis.exceptions.AuthenticationError:print("Redis 认证失败,请检查密码。")
except Exception as e:print(f"发生未知错误: {e}")