import flask                  # simple framework to develop web-based apps
import flask_restful          # extension to implement RESTful services
import redis                  # in-memory storage

# flask_app.run() will start the web service listening on default port 5000
flask_app = flask.Flask(__name__)
flask_api = flask_restful.Api(flask_app)

# redis will run on a separate container, so the host is the name of
# that container (see compose.yaml), instead of the default "localhost",
# and the port is the default 6379
redis_db = redis.Redis(host='my_redis_db')  

# the following class will handle GET requests at URL '/'
#
# Note that this is not strict REST, since GET is supposed to be idempotent
# We adopt this compromise for simplicity, but to be fully REST the application should separate 
# the request for incrementing the counter (e.g. PUT request issued from javascript) and
# the request for showing the value (e.g. by redirecting the page to issue a GET request)
class Counter(flask_restful.Resource):
    def get(self):       # callback function for GET requests
        hits = redis_db.incr('hits')
        return f"I have been hit {format(hits)} times.\n"

flask_api.add_resource(Counter, '/')
