Skip to content

Instantly share code, notes, and snippets.

@staybuzz
Created May 9, 2020 03:23
Show Gist options
  • Save staybuzz/56a56943d99bc78a1ca8ae5ad4efaecd to your computer and use it in GitHub Desktop.
Save staybuzz/56a56943d99bc78a1ca8ae5ad4efaecd to your computer and use it in GitHub Desktop.
Flask + Redis
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST">
<input type="text" name="username" placeholder="Your name">
<input type="submit" value="submit">
</form>
</body>
</html>
from flask import Flask, render_template, request, make_response
from redis import Redis
from datetime import datetime
import base64
import M2Crypto
app = Flask(__name__)
app.debug = True
redis = Redis(host='localhost', port=6379, decode_responses=True)
# ref: https://stackoverflow.com/questions/817882/unique-session-id-in-python
def _generate_session_id(num_bytes=32):
return base64.b64encode(M2Crypto.m2.rand_bytes(num_bytes))
# ref: https://www.yoheim.net/blog.php?q=20160506
def _set_cookie(response, key, value):
max_age = 60 * 60 * 24
expires = int(datetime.now().timestamp()) + max_age
response.set_cookie(key, value=value, max_age=max_age, expires=expires)
return response
@app.route('/')
def index():
sessid = request.cookies.get('sessid')
if not sessid:
response = render_template('index.html')
else:
response = f'welcome back, {redis.get(sessid)}'
return make_response(response)
@app.route('/', methods=['POST'])
def hello_name():
sessid = _generate_session_id()
response = make_response(f"hello {request.form['username']}")
response = _set_cookie(response, 'sessid', sessid)
redis.set(sessid, request.form['username'])
return response
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment