Mercurial > public > tweet-analysis
comparison src/handlers/sentiment.py @ 6:db2ce7097ff3
add string parameters
author | Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com> |
---|---|
date | Fri, 17 Sep 2021 17:42:42 +0200 |
parents | cfd876570008 |
children |
comparison
equal
deleted
inserted
replaced
5:54e71cf6e324 | 6:db2ce7097ff3 |
---|---|
1 import json | |
2 import requests | 1 import requests |
3 import boto3 | 2 |
4 import base64 | 3 # noinspection PyUnresolvedReferences |
5 from botocore.exceptions import ClientError | 4 from secrets_controller import get_secret |
5 # noinspection PyUnresolvedReferences | |
6 from event_controller import unwrap_sentiment_string_parameters | |
7 # noinspection PyUnresolvedReferences | |
8 from url_controller import create_twitter_url | |
6 | 9 |
7 | 10 |
8 def get_tweet_sentiment(event, context): | 11 def get_tweet_sentiment(event, context): |
9 """ | 12 """ |
10 :param event: dict, required | 13 :param event: dict, required |
13 Lambda Context runtime methods and attributes | 16 Lambda Context runtime methods and attributes |
14 :return: dict | 17 :return: dict |
15 API Gateway Lambda Proxy Output Format | 18 API Gateway Lambda Proxy Output Format |
16 """ | 19 """ |
17 | 20 |
18 twitter_url = create_twitter_url(user='dennisconcep') | 21 # Unwrap query string parameters |
19 twitter_key = get_twitter_key() | 22 twitter_user, number_of_tweets = unwrap_sentiment_string_parameters(event) |
20 bearer_token = twitter_key['BEARER'] | 23 |
21 twitter_header = {"Authorization": "Bearer {}".format(bearer_token)} # Auth header | 24 # URL creation & authentication |
25 twitter_url = create_twitter_url(twitter_user, number_of_tweets) | |
26 twitter_key = get_secret(secret_name='tweet-analysis-keys') | |
27 twitter_header = {"Authorization": "Bearer {}".format(twitter_key['BEARER'])} | |
28 | |
29 # Request tweets to Twitter | |
22 twitter_response = requests.request("GET", twitter_url, headers=twitter_header) | 30 twitter_response = requests.request("GET", twitter_url, headers=twitter_header) |
31 | |
32 # Analyse tweets with AWS Comprehend | |
23 | 33 |
24 return { | 34 return { |
25 "statusCode": 200, | 35 "statusCode": 200, |
26 "body": json.dumps({ | 36 "body": { |
27 "message": "hello world", | |
28 "tweets": twitter_response.json() | 37 "tweets": twitter_response.json() |
29 }), | 38 } |
30 } | 39 } |
31 | |
32 | |
33 def create_twitter_url(user, max_results=100): | |
34 """ | |
35 Create url to fetch `max_results` of tweets from `user` | |
36 :param user: string, required | |
37 :param max_results: int, optional, default 100 | |
38 :return: string url | |
39 """ | |
40 | |
41 formatted_max_results = 'max_results={}'.format(max_results) | |
42 formatted_user = 'query=from:{}'.format(user) | |
43 url = "https://api.twitter.com/2/tweets/search/recent?{}&{}".format(formatted_max_results, formatted_user) | |
44 | |
45 return url | |
46 | |
47 | |
48 def get_twitter_key(): | |
49 """ | |
50 Get Twitter Api Key from AWS Secrets Manager | |
51 :return: | |
52 """ | |
53 secret_name = "tweet-analysis-keys" | |
54 region_name = "eu-west-2" | |
55 | |
56 # Create a Secrets Manager client | |
57 session = boto3.session.Session() | |
58 client = session.client( | |
59 service_name='secretsmanager', | |
60 region_name=region_name | |
61 ) | |
62 | |
63 try: | |
64 get_secret_value_response = client.get_secret_value(SecretId=secret_name) | |
65 except ClientError as e: | |
66 if e.response['Error']['Code'] == 'DecryptionFailureException': | |
67 # Secrets Manager can't decrypt the protected secret text using the provided KMS key. | |
68 # Deal with the exception here, and/or rethrow at your discretion. | |
69 raise e | |
70 elif e.response['Error']['Code'] == 'InternalServiceErrorException': | |
71 # An error occurred on the server side. | |
72 # Deal with the exception here, and/or rethrow at your discretion. | |
73 raise e | |
74 elif e.response['Error']['Code'] == 'InvalidParameterException': | |
75 # You provided an invalid value for a parameter. | |
76 # Deal with the exception here, and/or rethrow at your discretion. | |
77 raise e | |
78 elif e.response['Error']['Code'] == 'InvalidRequestException': | |
79 # You provided a parameter value that is not valid for the current state of the resource. | |
80 # Deal with the exception here, and/or rethrow at your discretion. | |
81 raise e | |
82 elif e.response['Error']['Code'] == 'ResourceNotFoundException': | |
83 # We can't find the resource that you asked for. | |
84 # Deal with the exception here, and/or rethrow at your discretion. | |
85 raise e | |
86 else: | |
87 # Decrypts secret using the associated KMS CMK. | |
88 # Depending on whether the secret is a string or binary, one of these fields will be populated. | |
89 if 'SecretString' in get_secret_value_response: | |
90 secret = get_secret_value_response['SecretString'] | |
91 else: | |
92 secret = base64.b64decode(get_secret_value_response['SecretBinary']) | |
93 | |
94 return json.loads(secret) |