Redis正在计算根上的点击次数。我添加了一个arg“名称”,我的代码如下:
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis', port=6379)
@app.route('/')
@app.route('/<name>')
def hello(name):
count = redis.incr('hits')
return 'Hello {} I have been seen {} times.\n'.format(name,count)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
我想存储并返回一个不同的计数,我希望链接到“ name”变量。我当时正在考虑使用数组,但不确定如何实现。
答案 0 :(得分:1)
一种简单的方法是存储一个代表用户及其人数字典的json字符串,如下所示:
import json
@app.route('/')
@app.route('/<name>')
def hello(name):
counts = json.loads(redis.get('hits') or '{}')
try:
counts[name] += 1
except KeyError:
counts[name] = 1
redis.set('hits', json.dumps(counts))
return 'Hello {} I have been seen {} times.\n'.format(name,counts[name])