1+ import boto3
2+ import logging
3+ import os
4+
5+ from random import randrange
6+ from urllib .request import urlopen
7+
8+ # It is not recommended to enable DEBUG logs in production,
9+ # this is just to show an example of a recommendation
10+ # by Amazon CodeGuru Profiler.
11+ logging .getLogger ('botocore' ).setLevel (logging .DEBUG )
12+
13+ SITE = 'http://www.python.org/'
14+ CW_NAMESPACE = 'ProfilerPythonDemo'
15+ S3_BUCKET = os .environ ['S3_BUCKET' ]
16+
17+
18+ def lambda_handler (event , context ):
19+ # Make some network calls using urllib and s3 client.
20+ with urlopen (SITE ) as response :
21+ s3_client = boto3 .client ('s3' )
22+ s3_client .put_object (Body = response .read (),
23+ Bucket = S3_BUCKET ,
24+ Key = 'response.txt' )
25+
26+ # Publish metrics.
27+ content_length = int (response .headers ['Content-Length' ])
28+ put_metric ('ResponseContentLength' , content_length )
29+ put_metric (str (response .status )[0 ] + 'xxStatus' , 1 )
30+
31+ # Generate some CPU-intensive work.
32+ num = randrange (content_length )
33+ count = 0
34+ for _ in range (num ):
35+ x = randrange (num )
36+ if check_prime (x ):
37+ count += 1
38+
39+ return count
40+
41+
42+ def put_metric (name , value ):
43+ cw_client = boto3 .client ('cloudwatch' )
44+ metric_data_num = [{'MetricName' : name , 'Value' : value }]
45+ cw_client .put_metric_data (Namespace = CW_NAMESPACE , MetricData = metric_data_num )
46+
47+
48+ def check_prime (num ):
49+ if num == 1 or num == 0 :
50+ return False
51+ sq_root = 2
52+ while sq_root * sq_root <= num :
53+ if num % sq_root == 0 :
54+ return False
55+ sq_root += 1
56+ return True
0 commit comments