Last active
September 15, 2015 10:53
-
-
Save mcchae/77daa658fec14e5f0a7a to your computer and use it in GitHub Desktop.
FlaskRedisSession
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
from uuid import uuid4 | |
from datetime import datetime, timedelta | |
from flask.sessions import SessionInterface, SessionMixin | |
from werkzeug.datastructures import CallbackDict | |
from flask import Flask, session, url_for, redirect | |
import redis | |
import cPickle | |
######################################################################################### | |
# This is a session object. It is nothing more than a dict with some extra methods | |
class RedisSession(CallbackDict, SessionMixin): | |
def __init__(self, initial=None, sid=None): | |
CallbackDict.__init__(self, initial) | |
self.sid = sid | |
self.modified = False | |
######################################################################################### | |
# Session interface is responsible for handling logic related to sessions | |
# i.e. storing, saving, etc | |
class RedisSessionInterface(SessionInterface): | |
#==================================================================================== | |
# Init connection | |
def __init__(self, host='localhost', port=6379, db=0, timeout=3600): | |
self.store = redis.StrictRedis(host=host, port=port, db=db) | |
self.timeout = timeout | |
#==================================================================================== | |
def open_session(self, app, request): | |
# Get session id from the cookie | |
sid = request.cookies.get(app.session_cookie_name) | |
# If id is given (session was created) | |
if sid: | |
# Try to load a session from Redisdb | |
stored_session = None | |
ssstr = self.store.get(sid) | |
if ssstr: | |
stored_session = cPickle.loads(ssstr) | |
if stored_session: | |
# Check if the session isn't expired | |
if stored_session.get('expiration') > datetime.utcnow(): | |
return RedisSession(initial=stored_session['data'], | |
sid=stored_session['sid']) | |
# If there was no session or it was expired... | |
# Generate a random id and create an empty session | |
sid = str(uuid4()) | |
return RedisSession(sid=sid) | |
#==================================================================================== | |
def save_session(self, app, session, response): | |
domain = self.get_cookie_domain(app) | |
# We're requested to delete the session | |
if not session: | |
response.delete_cookie(app.session_cookie_name, domain=domain) | |
return | |
# Refresh the session expiration time | |
# First, use get_expiration_time from SessionInterface | |
# If it fails, add 1 hour to current time | |
if self.get_expiration_time(app, session): | |
expiration = self.get_expiration_time(app, session) | |
else: | |
expiration = datetime.utcnow() + timedelta(hours=1) | |
# Update the Redis document, where sid equals to session.sid | |
ssd = { | |
'sid': session.sid, | |
'data': session, | |
'expiration': expiration | |
} | |
ssstr = cPickle.dumps(ssd) | |
self.store.setex(session.sid, self.timeout, ssstr) | |
# Refresh the cookie | |
response.set_cookie(app.session_cookie_name, session.sid, | |
expires=self.get_expiration_time(app, session), | |
httponly=True, domain=domain) | |
######################################################################################### | |
# Create an application | |
app = Flask(__name__) | |
app.session_interface = RedisSessionInterface() | |
######################################################################################### | |
@app.route("/") | |
def index(): | |
session.permanent = False | |
if not 'refreshed'in session: | |
session['refreshed'] = 0 | |
text = "You refreshed the page %d times" % ( session['refreshed'] ) | |
text += '<br/><a href="/kill">Reset</a>' | |
text += '<br/>dbname="%s"' % session.get('dbname','NULL') | |
session['refreshed'] = session['refreshed'] + 1 | |
return text | |
######################################################################################### | |
@app.route("/dbset/<dbname>") | |
def dbset(dbname): | |
session['dbname']=dbname | |
return redirect(url_for('index')) | |
######################################################################################### | |
@app.route("/kill") | |
def kill(): | |
session.clear() | |
return redirect(url_for('index')) | |
app.debug = True | |
######################################################################################### | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=8080) |
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
#!/usr/bin/env python | |
#coding=utf8 | |
########################################################################################## | |
import os | |
#import logging | |
#import logging.handlers | |
import traceback | |
from flask.ext.restful import reqparse, abort, Api, Resource | |
from flask import Flask, request | |
from uuid import uuid4 | |
from datetime import datetime, timedelta | |
from flask.sessions import SessionInterface, SessionMixin | |
from werkzeug.datastructures import CallbackDict | |
from flask import Flask, session, url_for, redirect | |
import redis | |
import cPickle | |
######################################################################################### | |
# This is a session object. It is nothing more than a dict with some extra methods | |
class RedisSession(CallbackDict, SessionMixin): | |
def __init__(self, initial=None, sid=None): | |
CallbackDict.__init__(self, initial) | |
self.sid = sid | |
self.modified = False | |
######################################################################################### | |
# Session interface is responsible for handling logic related to sessions | |
# i.e. storing, saving, etc | |
class RedisSessionInterface(SessionInterface): | |
#==================================================================================== | |
# Init connection | |
def __init__(self, host='localhost', port=6379, db=0, timeout=3600): | |
self.store = redis.StrictRedis(host=host, port=port, db=db) | |
self.timeout = timeout | |
#==================================================================================== | |
def open_session(self, app, request): | |
# Get session id from the cookie | |
sid = request.cookies.get(app.session_cookie_name) | |
# If id is given (session was created) | |
if sid: | |
# Try to load a session from Redisdb | |
stored_session = None | |
ssstr = self.store.get(sid) | |
if ssstr: | |
stored_session = cPickle.loads(ssstr) | |
if stored_session: | |
# Check if the session isn't expired | |
if stored_session.get('expiration') > datetime.utcnow(): | |
return RedisSession(initial=stored_session['data'], | |
sid=stored_session['sid']) | |
# If there was no session or it was expired... | |
# Generate a random id and create an empty session | |
sid = str(uuid4()) | |
return RedisSession(sid=sid) | |
#==================================================================================== | |
def save_session(self, app, session, response): | |
domain = self.get_cookie_domain(app) | |
# We're requested to delete the session | |
if not session: | |
response.delete_cookie(app.session_cookie_name, domain=domain) | |
return | |
# Refresh the session expiration time | |
# First, use get_expiration_time from SessionInterface | |
# If it fails, add 1 hour to current time | |
if self.get_expiration_time(app, session): | |
expiration = self.get_expiration_time(app, session) | |
else: | |
expiration = datetime.utcnow() + timedelta(hours=1) | |
# Update the Redis document, where sid equals to session.sid | |
ssd = { | |
'sid': session.sid, | |
'data': session, | |
'expiration': expiration | |
} | |
ssstr = cPickle.dumps(ssd) | |
self.store.setex(session.sid, self.timeout, ssstr) | |
# Refresh the cookie | |
response.set_cookie(app.session_cookie_name, session.sid, | |
expires=self.get_expiration_time(app, session), | |
httponly=True, domain=domain) | |
########################################################################################## | |
app = Flask(__name__) | |
app.session_interface = RedisSessionInterface() | |
api = Api(app) | |
######################################################################################### | |
@app.route("/") | |
def index(): | |
session.permanent = False | |
if not 'refreshed'in session: | |
session['refreshed'] = 0 | |
text = "You refreshed the page %d times" % ( session['refreshed'] ) | |
text += '<br/><a href="/kill">Reset</a>' | |
text += '<br/>dbname="%s"' % session.get('dbname','NULL') | |
session['refreshed'] = session['refreshed'] + 1 | |
return text | |
######################################################################################### | |
@app.route("/dbset/<dbname>") | |
def dbset(dbname): | |
session['dbname']=dbname | |
return redirect(url_for('index')) | |
##############################################################tt########################### | |
@app.route("/kill") | |
def kill(): | |
session.clear() | |
return redirect(url_for('index')) | |
########################################################################################## | |
class ZoneInfo(Resource): | |
def get(self): | |
app.logger.info("ZoneInfo.get start...") | |
try: | |
stmt = "select zone,ou,pool,in_ip,ex_ip FROM tm_zone" | |
dlist = [ | |
{'id':1, 'zone':'서울'}, | |
{'id':2, 'zone':'대전'}, | |
{'id':3, 'zone':'부산'}, | |
] | |
rd = { | |
'dbname':session['dbname'] if 'dbname' in session else 'None', | |
'result':dlist | |
} | |
return rd | |
except Exception, e: | |
app.logger.error('ZoneInfo.get: Error: %s: %s' % (e, traceback.format_exc())) | |
rd = { | |
'result':[] | |
} | |
return rd | |
finally: | |
rdstr = str(rd) | |
if len(rdstr) > 1024: | |
rdstr = rdstr[:1024] + '...' | |
app.logger.info("ZoneInfo.get return: %s" % rdstr) | |
########################################################################################## | |
## Actually setup the Api resource routing here | |
########################################################################################## | |
api.add_resource(ZoneInfo, '/zoneInfo') | |
########################################################################################## | |
if __name__ == '__main__': | |
app.logger.info("Start RestAPI : listen %s:%s" % ('0.0.0.0', 8440)) | |
app.run( | |
host='0.0.0.0', | |
port=8440, | |
debug = True, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment