Skip to content

Instantly share code, notes, and snippets.

@JohnLockwood
Created January 1, 2016 23:26
Show Gist options
  • Save JohnLockwood/d9fa9393be269322df1a to your computer and use it in GitHub Desktop.
Save JohnLockwood/d9fa9393be269322df1a to your computer and use it in GitHub Desktop.
#
# A proof of concept for an alternative to Flask-restful that supports GET (for an id) and GET (for a list of objects) on the same
# object -- not to mention POST (don't-know-the-id-yet) and PUT (sure I do).
#
# Usage in the file that defines the Blueprint looks like:
# api_v1_root = '/api/v1'
# v1_api = Blueprint('api/v1', __name__, url_prefix=api_v1_root)
# poc = ProofOfConcept("/poc")
# poc.register_routes(v1_api)
class ProofOfConcept(object):
def __init__(self, root):
if not root.startswith("/"):
self.root = "/" + root
else:
self.root = root
def one_item_router(self, id):
method = request.method
if (method == 'GET'):
return self.get_one(id)
elif(method == 'PUT'):
return self.put(id)
else:
return self.delete(id)
def many_item_router(self):
method = request.method
if (method == 'GET'):
return self.get_many()
elif(method == 'POST'):
return self.post()
def get_one(self, id):
message = {"status": "Proof of concept - get one, open for business, id = " + id}
return jsonify(message)
def get_many(self):
message = {"status": "Proof of concept - get many, open for business"}
return jsonify(message)
def post(self):
return jsonify({"status": "Proof of concept POST"})
def put(self, id):
return jsonify({"status": "Proof of concept PUT, id = " + id })
def delete(self, id):
return jsonify({"status": "Proof of concept DELETE, id = " + id })
def register_routes(self, blueprint):
many_item_route = self.root
one_item_route = self.root + "/<string:id>"
routes = [
dict(rule=one_item_route, endpoint= one_item_route, view_func=self.one_item_router, methods=["PUT", "GET", "DELETE"]),
dict(rule=many_item_route, endpoint= many_item_route, view_func=self.many_item_router, methods=["GET", "POST"]),
]
for r in routes:
blueprint.add_url_rule(r["rule"], endpoint=r["endpoint"], view_func=r["view_func"], methods=r["methods"])
@JohnLockwood
Copy link
Author

Just seeing how one would comment on a gist.

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