diff --git a/compose/gettingstarted.md b/compose/gettingstarted.md index 471c26e00a..df2af5f0b7 100644 --- a/compose/gettingstarted.md +++ b/compose/gettingstarted.md @@ -26,21 +26,50 @@ Define the application dependencies. 2. Create a file called `app.py` in your project directory and paste this in: + import time + + import redis from flask import Flask - from redis import Redis + app = Flask(__name__) - redis = Redis(host='redis', port=6379) + cache = redis.Redis(host='redis', port=6379) + + + def get_hit_count(): + retries = 5 + while True: + try: + return cache.incr('hits') + except redis.exceptions.ConnectionError as exc: + if retries == 0: + raise exc + retries -= 1 + time.sleep(0.5) + @app.route('/') def hello(): - count = redis.incr('hits') + count = get_hit_count() return 'Hello World! I have been seen {} times.\n'.format(count) if __name__ == "__main__": app.run(host="0.0.0.0", debug=True) - In this example, `redis` is the hostname of the redis container on the application's network. We use the default port for Redis, `6379`. + + In this example, `redis` is the hostname of the redis container on the + application's network. We use the default port for Redis, `6379`. + + > Handling transient errors + > + > Note the way the `get_hit_count` function is written. This basic retry + > loop lets us attempt our request multiple times if the redis service is + > not available. This is useful at startup while the application comes + > online, but also makes our application more resilient if the Redis + > service has to be restarted anytime during the app's lifetime. In a + > cluster, this also helps handling momentary connection drops between + > nodes. + 3. Create another file called `requirements.txt` in your project directory and paste this in: @@ -87,8 +116,6 @@ the following: build: . ports: - "5000:5000" - links: - - redis redis: image: "redis:alpine"