Skip to content

Syntax Error in AWS Lambda

0

I'm currently working on AWS Lambda (Python 3.12). Basically I want to create a Login and Notification function for my backend (DJango Rest Framework).

So the order is as follows:

  1. I use my Login function to get the Token from my backend and then use my Notification function to avoid getting any 401 (Unauthorized) errors.
  2. I use my Notification feature to be able to communicate directly with my Backend.

The error comes directly from my Notification function. Obviously I've already checked all the environment variables I use and everything is ok!

Here goes the code:

def login_backend():
headers = {
    "Content-Type": "application/json"
}
data = {
    'username': os.environ['USERNAME_BACKEND'],
    'password': os.environ['PASSWORD_BACKEND']
}
url = os.environ['URL_BACKEND_LOGIN']
try:
    encoded_data = json.dumps(data).encode('utf-8')
    response = http.request(
        'POST',
        url,
        body=encoded_data,
        headers=headers
    )
    if response.status == 200:
        response_data = json.loads(response.data.decode('utf-8'))
        token = response_data.get('token')
        if token:
            logger.info('LOGIN EXITOSO')
            return token
        else:
            logger.info("Error: Token not received in response")
            return None
    else:
        logger.info(f"Error logging in: {response.status} {response.data.decode('utf-8')}")
        return None
except Exception as e:
    logger.info(f"Error logging in: {e}")
    return None

Here goes my Notification function:

def notify_backend(stage, channel_name, token):
headers = {
    'Content-Type': 'application/json'
    'Authorization': f'Token {token}'
}
data = {
    'stage': stage,
    'channel_name': channel_name
}
url = os.environ['URL_BACKEND_NOTIFY']
try:
    encoded_data = json.dumps(data).encode('utf-8')
    response = http.request(
        'POST',
        url,
        body=encoded_data,
        headers=headers
    )
    if response.status == 200:
        logger.info("Notification sent successfully")
    else:
        logger.info(f"Error sending notification: {response.status} {response.data.decode('utf-8')}")
except Exception as e:
    logger.info(f"Error sending notification: {e}")

Now I will show you the handler function and how I intend to use my algorithm.:

def lambda_handler(event, context):
channel_name = event['channel_name']

token = login_backend()
if not token:
    return {
        'statusCode': 500,
        'body': 'Error getting authentication token'
    }

notify_backend('download_files', channel_name, token)

What is the error I am having? Well, it seems to be a syntax error in the code, which I do not understand completely.: Response: { "errorMessage": "Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 65)", "errorType": "Runtime.UserCodeSyntaxError", "requestId": "", "stackTrace": [ " File "/var/task/lambda_function.py" Line 65\n "Authorization": f'Token {token}'\n" ] }

From what I understand the error is indicated by the line: 'Authorization': f'Token {token}' I have tried to fix it with the f-string variant, but it still doesn't work: "Authorization": "Token {}".format(token) output: Response: { "errorMessage": "Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 65)", "errorType": "Runtime.UserCodeSyntaxError", "requestId": "", "stackTrace": [ " File "/var/task/lambda_function.py" Line 65\n 'Authorization': 'Token {}'.format(token)\n" ] } Do you have any idea why this error might occur? Is there something I'm missing?

asked 2 years ago612 views

1 Answer
2
Accepted Answer

The syntax error you're encountering is due to a missing comma in the headers dictionary in your notify_backend function. In Python, when defining a dictionary with multiple key-value pairs, you need to separate each pair with a comma. Here's the corrected version of the headers dictionary:

headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Token {token}'
}

Notice the comma after 'application/json'. This was missing in your original code, which is causing the syntax error.

The reason why changing to the .format() method didn't solve the issue is that the fundamental problem was not with the f-string, but with the dictionary syntax.

It's worth noting that in Python 3.12, which you're using, f-strings are fully supported and are often preferred for their readability. So your original approach using f'Token {token}' is perfectly valid once you add the missing comma.

Also, make sure that the indentation in your actual code matches what you've shown here, as Python is sensitive to indentation.

After making this correction, your notify_backend function should work as expected. If you encounter any further issues, double-check that all your environment variables are correctly set and that your login_backend function is successfully retrieving a token.

Remember to test your changes locally if possible before deploying to AWS Lambda, as this can help catch syntax errors earlier in the development process.
Sources
Building Lambda functions with Python - AWS Lambda
Python 3.12 runtime now available in AWS Lambda | AWS Compute Blog

answered 2 years ago

EXPERT

reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.