from flask import Flask
import pybreaker
import statsd
from datetime import datetime, timedelta
app = Flask(__name__)
client = statsd.StatsClient('localhost', '8125')
db_breaker = pybreaker.CircuitBreaker(client, reset_timeout=5, buffer_reset_flag=True
                                      )

opened_at = datetime.utcnow()
timeout = timedelta(seconds=10)


@app.route('/')
@db_breaker
def hello_word():
    time_now = datetime.utcnow()
    while time_now < (opened_at + timeout):
        raise NotImplementedError()
    return "Total : {0}\nFail : {1}\nSuccess : {2}\nState : {3}" \
        .format(db_breaker._state_storage._total_calls, db_breaker._state_storage.fail_counter,
                db_breaker._state_storage.success_counter, db_breaker.current_state)




@app.route('/err')
@db_breaker
def test():
    print db_breaker.current_state
    raise NotImplementedError()


if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=8082)

