Created
June 16, 2021 23:22
-
-
Save dalegaspi/f65397f4d987782cede4dfaf3c396eaf to your computer and use it in GitHub Desktop.
Flask Redis PUT/GET Endpoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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