Im this tutorial we simply configured redis locally through docker. We can easily configure it with the command below.
$ docker pull redis:latest $ docker run -d -p 6379:6379 --name session_storage redis:latest
We can check the status of the redis container by entering the command below.
$ docker ps CONTAINER ID
Below is a simple web application that uses Python flask to store and retrieve information in sessions.
import redis
from flask import *
from flask_session import Session
app = Flask(__name__)
app.secret_key = 'Skills39Test'
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_REDIS'] = redis.from_url('redis://localhost:6379')
server_session = Session(app)
@app.route('/info', methods=['GET','POST'])
def set():
if request.method == 'GET':
username = session['username']
name = session['name']
message = session['message']
return jsonify({'username':username,'name':name,'message':message})
else:
session['username'] = request.form.get('username')
session['name'] = request.form.get('name')
session['message'] = request.form.get('message')
return jsonify({'upload':'success'})
app.run(host='0.0.0.0', port=8080)
Create the below file for dependencies:
# requirements.txt
flask
flask_session
redis
To check, run the below code using python to check the endpoint response
import requests
res = requests.post("http://localhost:8080/customer", data={'username':'sysops1', 'name':'Bagus Santosa', 'message': 'Hallo World'})
print(res.status_code)
requests.get("http://localhost:8080/info", cookies={'session':session})
print(res.json())
To check inside the Redis. We can access the redis container using the command below.
$ docker exec -it session_storage redis- 127.0.0.1:6379> keys * 1) "session:session_id"
We can view the information stored in the session by entering the command below.
127.0.0.1:6379> get session:session_id
Thank you.
Comments
Post a Comment