Flask Session, AWS-Redis

This article is talking about the flask micro service framework. Same like others web framework, flask do provide the session object to each individual request and this implementation is on top of cookies for you to sign the cookies cryptophgraphically. This made sure the user can view but not able to modify unless they know the secret key that application is used for signing. Therefore setting up and store the application secret key is important.

Generate Random Secret Key

python -c 'import os; print(os.urandom(16))' 

Simple App without Blueprint

With simple app without blueprint, you can set your application secret key right after application instantiation. Eg

from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)
app.secret_key = b'your_secret_key'

@app.route('/')
def index():
pass

@app.route('/home')
def home():
pass

Simple App with Blueprint

def create_app(config_class=Config):
# Define the WSGI application object
app = Flask(__name__)
app.config.from_object(config_class)

class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'guess'
SESSION_TYPE = 'redis'

Troubleshooting

In case if you’re getting below message, event though you’ve set the proper app.secret_key. That could be the reason by raise of NullSessionInterface. The default session used by Flask-Session extension.

RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.

This stack overflow explain in very details.

RedisSessionInterface

Flask-Session ext does not supply SESSION_REDIS_HOST or SESSION_REDIS_PORT configuration. We need to configure SESSION_REDIS for redis.Redis instance. Eg, In your Config.py

SESSION_TYPE = 'redis'    
SESSION_REDIS = os.environ.get('AWS_REDIS_HOST') or 'redis://'

Flask Session Interface

Session instance cannot be used directly, flask session provides vary session interface such as

  • NullSessionInterface
  • RedisSessionInterface
  • MemcachedSessionInterface
  • FileSystemSessionInterface
  • MongoDBSessionInterface
  • SqlAlchemySessionInterface

You can not use Session instance directly, what Session does is just change the session_interface attribute on your Flask applications.

Redis Local

config.py
###########
import os
from dotenv import load_dotenv
import redis

basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))

class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'guess'
SESSION_TYPE = 'redis'
SESSION_REDIS = redis.from_url(os.environ.get('SESSION_REDIS'))
SESSION_PERMANENT = False
SESSION_KEY_PREFIX = 'MINGCH'



__init__.py
###########

import os
from flask import Flask, render_template
from config import Config
from flask_session import Session
from redis import Redis

sess = Session()

def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
sess.init_app(app)

from app.user import bp as user_blueprint
app.register_blueprint(user_blueprint)


app/user/__init__.py
####################

from flask import Blueprint
bp = Blueprint('user', __name__)
from app.user import views


app/user/view.py
#################

from flask import Flask, session, request
from app.user import bp

@bp.route("/set", methods = ['GET'])
def set_key():
session['key'] = 'Hello World'
return 'ok'

@bp.route("/get", methods = ['GET'])
def get_key():
return session.get('key', 'N/A')


.env
#################
SESSION_REDIS=redis://

Redis AWS

By testing ElasticCache – Redis, therefore few thing need to be get done before you can test it out.

  • Security – Custom TCP Rule TCP 6379 0.0.0.0/0
  • EC2 with the same VPC
  • Primary Endpoint of your redis
redis-cli -h testing-staging-001.abcd.0001.apse1.cache.amazonaws.com -p 6379

.env
=====
SESSION_REDIS=redis://testing-abcd.0001.apse1.cache.amazonaws.com:6379

Reference

Flask Session, AWS-Redis

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.