redis_tools.py:
定义一个获取redis连接对象和一个用get命令获取数据的方法
import redis
def get_redis_client(host="xxx.xxx.xxx.xxx", port=6379):
"""
获取redis信息
:param host: 服务器ip
:param port: 端口号
:return:
"""
client = redis.Redis(host=host, port=port, decode_responses=True)
return client
def get_redis_data(client, operate, key):
"""
:param client:
:param operate: 请求方法
:param key: key值
:return:
"""
if operate == 'get':
return client.get(key)
redisapi.py:
from flask import Flask, request
from redis_tools import *
app = Flask(__name__)
return_dict = {'code': '200'}
@app.route('/redisapi/get', methods=['GET'])
def redisapi_get():
if request.method == 'POST':
return_dict['code'] = '405'
return_dict['message'] = 'Method not allowed'
if request.args is None:
return_dict['code'] = '400'
return_dict['message'] = '请求参数key不能为空'
elif "key" in request.args.to_dict().keys():
get_data = request.args.to_dict()
key = get_data['key']
r = get_redis_client()
result = get_redis_data(r, 'get', key)
return_dict['data'] = result
return return_dict
if __name__ == '__main__':
app.run(debug=True)
运行redisapi.py脚本后,就可以在浏览器查询redis中的数据了:
http://127.0.0.1:5000/redisapi/get?key=backup3
?
|