0
0

More than 1 year has passed since last update.

Redis の WebAPI (Bottle)

Last updated at Posted at 2020-11-13

こちらで定めた仕様を満たすサーバーサイドのプログラムです。
Redis の WebAPI を作成

インストール

yay python-redis
yay python-hiredis
bottle_redis.py
#! /usr/bin/python
#
#	bottle_redis.py
#
#						Nov/13/2020
#
# --------------------------------------------------------
from bottle import route, run, post, request
import redis
import json
import sys
# --------------------------------------------------------
@post('/read')
def read():
	key = request.forms.get('key')

	json_str = ""
	try:
		rr = redis.Redis(host='localhost', port=6379, db=0)
		json_str = rr.get(key).decode()
	except Exception as ee:
		sys.stderr.write("*** error *** in rr.get ***\n")
		sys.stderr.write(str(ee) + "\n")

	return json_str
#
# --------------------------------------------------------
@post('/insert')
def insert():
	key = request.forms.key
	json_str = request.forms.value
#
	sys.stderr.write(key + "\n")
	sys.stderr.write(json_str + "\n")
#
	if json_str != "0000":
		rr = redis.Redis(host='localhost', port=6379, db=0)
		rr.set(key, json_str)
#
	str_out = ""
	str_out += key + " *** "
	str_out += json_str + " *** "

	return str_out
#
# --------------------------------------------------------
@post('/list')
def list():
	keys = []
	json_str = ""
#
	try:
		rr = redis.Redis(host='localhost', port=6379, db=0)
		keys = rr.keys('*')
	except Exception as ee:
		sys.stderr.write("*** error *** in rr.keys ***\n")
		sys.stderr.write(str(ee) + "\n")
#
	keys_str = []
	for key in keys:
		key_str = key.decode('utf-8')
		keys_str.append(key_str)
#
	try:
		json_str = json.dumps(keys_str)
	except Exception as ee:
		sys.stderr.write("*** error *** in json.dumps ***\n")
		sys.stderr.write(str(ee) + "\n")
#
	return json_str
#
# --------------------------------------------------------
run(host='localhost', port=8080, debug=True)
# --------------------------------------------------------

サーバーの起動

$ ./bottle_redis.py 
Bottle v0.12.19 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.

読み出し

curl -X POST -d key=t1855 http://localhost:8080/read

書き込み

curl -X POST \
	-d key=t1855 \
-d value='{"name": "宇都宮","population": 87516,"date_mod": "2001-3-16"}' \
http://localhost:8080/insert

key の一覧

curl -X POST http://localhost:8080/list
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