Skip to content

Instantly share code, notes, and snippets.

@dalegaspi
Created June 16, 2021 23:22
Show Gist options
  • Save dalegaspi/f65397f4d987782cede4dfaf3c396eaf to your computer and use it in GitHub Desktop.
Save dalegaspi/f65397f4d987782cede4dfaf3c396eaf to your computer and use it in GitHub Desktop.
Flask Redis PUT/GET Endpoints
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
@app.route('/api/guestbook/message', methods=['POST', 'PUT'])
def api_put_message():
form_data = request.form
id = str(uuid.uuid4())
data = {
'ts': round(time.time() * 1000),
'id': id,
'email': form_data['email'],
'name': form_data['name'],
'msg': form_data['message']
}
r.lpush('ids', id)
r.ltrim('ids', 0, 9)
json_data = json.dumps(data)
r.set(id, json_data)
return Response(json.dumps({'status': 'ok'}), content_type='application/json')
@app.route('/api/guestbook/messages')
def api_get_messages():
ids = r.lrange('ids', -10, 5)
records = [r.get(i) for i in ids]
json_records = '[' + ','.join(records) + ']'
response = Response(json_records, content_type='application/json')
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment