|
| 1 | +from flask import Flask |
| 2 | +import time |
| 3 | +import random |
| 4 | +import boto3 |
| 5 | + |
| 6 | + |
| 7 | +app = Flask(__name__) |
| 8 | + |
| 9 | +# Initialize AWS CloudWatch client |
| 10 | +cloudwatch = boto3.client('cloudwatch', region_name='us-east-1') |
| 11 | + |
| 12 | +# Sample product data for our online store |
| 13 | +products = { |
| 14 | + '1': {'name': 'Product 1', 'price': 10.99}, |
| 15 | + '2': {'name': 'Product 2', 'price': 19.99}, |
| 16 | + '3': {'name': 'Product 3', 'price': 5.49} |
| 17 | +} |
| 18 | + |
| 19 | +@app.route('/') |
| 20 | +def index(): |
| 21 | + start_time = time.time() |
| 22 | + |
| 23 | + # Simulate processing time |
| 24 | + time.sleep(random.uniform(0.1, 0.5)) |
| 25 | + |
| 26 | + # Log the page view metric to CloudWatch |
| 27 | + log_metric('PageViews', 1) |
| 28 | + |
| 29 | + # Log the response time metric to CloudWatch |
| 30 | + response_time = (time.time() - start_time) * 1000 |
| 31 | + log_metric('ResponseTime', response_time) |
| 32 | + |
| 33 | + return "Welcome to our Online Store!" |
| 34 | + |
| 35 | +@app.route('/product/<product_id>') |
| 36 | +def product(product_id): |
| 37 | + start_time = time.time() |
| 38 | + |
| 39 | + # Simulate processing time |
| 40 | + time.sleep(random.uniform(0.2, 0.8)) |
| 41 | + |
| 42 | + # Log the page view metric to CloudWatch |
| 43 | + log_metric('PageViews', 1) |
| 44 | + |
| 45 | + # Log the response time metric to CloudWatch |
| 46 | + response_time = (time.time() - start_time) * 1000 |
| 47 | + log_metric('ResponseTime', response_time) |
| 48 | + |
| 49 | + if product_id in products: |
| 50 | + return f"Product: {products[product_id]['name']}, Price: ${products[product_id]['price']}" |
| 51 | + else: |
| 52 | + return "Product not found." |
| 53 | + |
| 54 | +def log_metric(metric_name, value): |
| 55 | + # Send custom metric to CloudWatch |
| 56 | + cloudwatch.put_metric_data( |
| 57 | + Namespace='OnlineStore', |
| 58 | + MetricData=[{ |
| 59 | + 'MetricName': metric_name, |
| 60 | + 'Value': value, |
| 61 | + 'Unit': 'Count' |
| 62 | + }] |
| 63 | + ) |
| 64 | + |
| 65 | +if __name__ == '__main__': |
| 66 | + app.run(host='0.0.0.0', port=5000) |
0 commit comments