Skip to content

Instantly share code, notes, and snippets.

@adorsk
Created April 24, 2015 18:51
Show Gist options
  • Save adorsk/70abf10b2b732e4229df to your computer and use it in GitHub Desktop.
Save adorsk/70abf10b2b732e4229df to your computer and use it in GitHub Desktop.
Math Engine
#!/usr/bin/env python
"""
A Flask-powered math engine microservice.
"""
from flask import Flask, request, jsonify, Response
import json
import datetime
app = Flask(__name__)
# Very basic history storage. In a proper app, this would be
# something a bit more robust, eh?
history = []
@app.route("/")
def hello():
return "Hellooooo Math!"
@app.route("/math_engine")
def math_engine():
"""Calculate sum/product for a given set of values."""
raw_values = request.args['values']
parsed_values = [float(v) for v in json.loads(raw_values)]
values_sum = 0
values_product = 1
for v in parsed_values:
values_sum += v
values_product *= v
result = {'sum': values_sum, 'product': values_product}
_add_to_history(request, parsed_values, result)
return jsonify(result)
def _add_to_history(request, parsed_values, result):
"""Save a request/result to the history."""
history_item = {
"ip": request.remote_addr,
"timestamp": datetime.datetime.now().isoformat(),
"values": parsed_values,
}
history_item.update(result)
history.append(history_item)
@app.route("/history")
def get_history():
"""Get history items. If 'num_items' argument
is not specified, returns max(10,len(history)) items."""
num_items = int(request.args.get('num_items', 10))
result = list(reversed(history[-1*num_items:]))
return Response(json.dumps(result), mimetype='application/json')
if __name__ == "__main__":
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment