Anaconda 利用python 向redis寫入資料小程式
阿新 • • 發佈:2018-12-25
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 12 11:27:05 2018
@author: guo
"""
import numpy as np
import redis ,datetime
def randomf(x): #產生任意個隨即浮點數,保留三位精度
y = np.zeros(x)
z = x
for i in range(z):
x = np.random.uniform(2,20,size=(z))
y[i] = round(x[i],3)
return y
def randomint(x): #產生任意個隨機整數
y = 5
x1 = np.random.uniform(2,20,y)
z = np.random.randint(2,20,size=(x))
return z
def lianjie(x,y ): #x 整數個數 , y 浮點數個數,將他們連線在一起
y1 = np.zeros((x+y))
a = randomf(x)
b = randomint(y)
i = 0
for i in range (x):
y1[i] = a[i]
for j in range(x,x+y): #range(5,10) j的範圍時 5 到 9
y1[j] = b[j-5]
return y1
def rediswrite2(x) : #向redis中按照屬性,拆開寫入資料 ,不迴圈
conn1 = redis.StrictRedis(host="localhost",port="6379",decode_responses=True) #和資料庫連線,最後一個引數解決 輸出帶有 b問題
f = randomint(5)
for i in range(x):
c = ":Game"
d1 = str(i) + c # +str(nowtime)
nowtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
dict1 = {"Time":nowtime,"Gamestate:1":f,"Gamestate:2":f,"Gamestate:3":f,"Gamestate:4":f}
conn1.hmset(d1,dict1)
conn1.hmget(d1,"Time")
if (i%100) == 0: #每個100列印一次
print(i)
# conn2.hset(d,"Runstate",a[i])
# y = np.zeros(21)
# y = conn1.hkeys("1:TRainInfo") #取得所有的鍵值
# x = conn1.hvals("1:TRainInfo") #取得所有的值 values
# print(x)
# print(y)
return 0
rediswrite2(3)