Skip to content

Instantly share code, notes, and snippets.

@cemoody
Last active June 29, 2023 18:19
Show Gist options
  • Save cemoody/caece9f076125e019cf0 to your computer and use it in GitHub Desktop.
Save cemoody/caece9f076125e019cf0 to your computer and use it in GitHub Desktop.
Simple SQLDict-backed Key Value Store
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
from sqlitedict import SqliteDict
from flask import jsonify, request
import json
data = SqliteDict('./data.sqlite', autocommit=True)
app = Flask(__name__)
api = Api(app)
def abort_doesnt_exist(key):
if key not in data:
abort(404, message="Key {} doesn't exist".format(key))
parser = reqparse.RequestParser()
parser.add_argument('task')
class Table(Resource):
def get(self, key):
abort_doesnt_exist(key)
print key, data[key]
return jsonify(data[key])
def delete(self, key):
abort_doesnt_exist(key)
print key, data[key]
del data[key]
return '', 204
def put(self, key):
if not request.data:
abort(400)
args = parser.parse_args()
val = json.loads(request.data)
data[key] = val
print key, args, data[key]
return val, 201
api.add_resource(Table, '/table/<key>', methods=['PUT', 'GET'])
if __name__ == '__main__':
app.run(debug=True)
@cemoody
Copy link
Author

cemoody commented Nov 13, 2015

Run like:

gunicorn -w 1 -b 0.0.0.0:4001 server:app -t 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment