0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python3: JSON 形式の Post で受け取ったデータを redis に入れる

Posted at

こちらのプログラムを改造しました。
Python3: JSON 形式の Post を処理する方法

サーバープログラム (CGI)

redis_post.py
# ! /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)
# ---------------------------------------------------------------------

テストスクリプト

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?