用Python3将以JSON形式收到的数据存入redis中
我对这个程序进行了修改。
Python3:处理JSON格式的Post方法。
服务器程序(CGI)
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# redis_post.py
#
# Jul/26/2021
#
# ---------------------------------------------------------------------
import os
import sys
import json
import cgi
import datetime
import redis
#
# ---------------------------------------------------------------------
def redis_insert_proc(key,json_str):
rr = redis.Redis(host='localhost', port=6379, db=0)
rr.set(key, json_str)
# ---------------------------------------------------------------------
if os.environ['REQUEST_METHOD'] == 'POST':
length, _ = cgi.parse_header(os.environ['CONTENT_LENGTH'])
data = sys.stdin.buffer.read(int(length))
#
json_str = data.decode("utf-8")
#
dt = datetime.datetime.now()
key = "%02d%02d%02d" % (dt.hour,dt.minute,dt.second)
redis_insert_proc(key,json_str)
#
data_aa = {}
data_aa['key'] = key
data_aa['value'] = json_str
str_aa = json.dumps(data_aa)
#
print('Content-Type: text/json; charset=utf-8')
print("Access-Control-Allow-Origin: *\r\n")
print(str_aa)
# ---------------------------------------------------------------------
测试脚本 (Tè shì
URL="http://localhost/redis_post/redis_post.py"
#
curl -X POST -H "Content-Type: application/json" \
-d '{"aa":"32","bb":"56"}' $URL
使用reis-cli进行确认
$ redis-cli
127.0.0.1:6379> keys *
1) "145859"
127.0.0.1:6379> get 145859
"{\"aa\":\"32\",\"bb\":\"56\"}"
127.0.0.1:6379> exit