Skip to content

Instantly share code, notes, and snippets.

@calderonroberto
Last active June 1, 2022 20:06
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save calderonroberto/f4d8badb94c01e9020db to your computer and use it in GitHub Desktop.
Save calderonroberto/f4d8badb94c01e9020db to your computer and use it in GitHub Desktop.
Flask Redis Example
#!/bin/python
# Dependencies:
# pip install flask
# pip install redis
from flask import Flask
from flask import request
import flask
import redis
import time
import json
from flask import Response, stream_with_context
app = Flask(__name__)
app.debug = True
db = redis.Redis('localhost') #connect to server
ttl = 31104000 #one year
def isInt(s):
try:
int(s)
return True
except ValueError:
return False
@app.route('/', defaults={'path': ''}, methods = ['PUT', 'GET'])
@app.route('/<path:path>', methods = ['PUT', 'GET'])
def home(path):
if (request.method == 'PUT'):
event = request.json
event['last_updated'] = int(time.time())
event['ttl'] = ttl
db.delete(path) #remove old keys
db.hmset(path, event)
db.expire(path, ttl)
return json.dumps(event), 201
if not db.exists(path):
return "Error: thing doesn't exist"
event = db.hgetall(path)
event["ttl"] = db.ttl(path)
#cast integers accordingly, nested arrays, dicts not supported for now :(
dict_with_ints = dict((k,int(v) if isInt(v) else v) for k,v in event.iteritems())
return json.dumps(dict_with_ints), 200
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment