Get started learning how to build your first-ever Python Labs Client App, a web application that leverages the power of serverless computing. This creative application is primarily designed to cater to individuals eager to enhance their Python programming skills. By using the flexibility and scalability of AWS Lambda, you’ll be able to create dynamic and interactive web experiences without the hassle of managing infrastructure. This Python Code Playground will be a valuable tool for developers of all levels, providing a hands-on environment to experiment with Python code and learn new concepts. Explore our TechKubo Tutorials for a comprehensive collection of Python code examples and in-depth explanations.
What is Cross-Origin Resource Sharing(CORS)?
CORS (Cross-Origin Resource Sharing) is a security system built into web browsers. It helps control how web pages from one site can access resources from a different site. Typically, browsers block cross-origin access to protect users and security concerns. But sometimes, if you want to share resources with the public, such as APIs, web services, or data across different websites. In such instances, you need to manually enable CORS explicitly.
When using AWS Lambda, you can run your code in response to things like web requests through Lambda Function URLs. These URLs let you access your Lambda function directly over the web without needing API Gateway. However, if you’re trying to access the Lambda function from a different website, the browser will block the request unless CORS is set up correctly.
Setting up CORS is important when you want to make your Lambda services, such as APIs or public resources like Python projects, accessible to other websites. This makes sure the resources can be used safely from different sites while following browser security rules.
In this tutorial, you’ll learn how to enable CORS for a Lambda Function URL so you can securely share public resources, like Python projects, across multiple websites.
Creating Lambda Function
Step 1: Create a new function on AWS Lambda
-
Choose “Author from Scratch“
-
Execution Role: “Create a new role with basic Lambda permissions.”
- Under the Advanced Settings:
-
Tick the “Enable function URL”
-
Auth Type: NONE
-
Invoke Mode: BUFFERED
-
Enable “Configure cross-origin resource sharing (CORS)“
- Once done, you can click “Create function“
-
Step 2: Once you have successfully created a function. We can now modify the code and configuration.
-
Under the Code Source section, copy and paste the following code snippet:
[python] import sys import io import json import os def lambda_handler(event, context): code =json.loads(event['body'])['code'] old_stdout = sys.stdout new_stdout = io.StringIO() sys.stdout = new_stdout try: exec_globals = {} exec_locals = {} exec(code, exec_globals, exec_locals) output = new_stdout.getvalue().strip() print('Output:') print(output) if not output: # If exec does not print anything, indicate successful execution output = 'Tutorials Dojo Code executed successfully.' except Exception as e: print(e) output = str(e) finally: # Reset standard output sys.stdout = old_stdout return { 'statusCode': 200, 'body': json.dumps({ 'output': output }) } [/python]
Step 3: Once done, click the “Deploy” button to apply the changes.
Creating a Python Labs Client App
Step 1: Create an HTML file with the following code.
[python]
Python Code Playground
Output:
[/python]
Step 2: Copy the Lambda function URL of our newly created Lambda function.
Step 3: Paste the Lambda function URL to your newly created HTML file:
Step 4: Return to the new Lambda function and configure the CORS settings in the ‘Function URL’ section by clicking the ‘Edit’ button.
Step 5: Edit the Function URL:
- Add the following in the Expose Headers and Allow Headers section
-
-
content-type
-
access-control-allow-origin
-
access-control-allow-methods
-
- Set the “Allow methods” section to permit ALL HTTP Methods using the * wildcard.
- The Max Age is “Optional”
Step 6: Once done, ensure that the added values are correct. You can now click ‘Save’ to apply the changes.
Testing the Python Labs Client App
- Run your HTML code and check the Network tab in DevTools in your browser.
-
-
Two domains have status and type.
- Fetch request
- Preflight
-
-
-
The preflight request occurs because the browser checks with the server to see if cross-origin requests are allowed, as indicated by the CORS settings in the previous image.
-
We can verify the added values in Expose Headers and Allow headers in the header section.
-
We can also verify that we have used the wildcard – * in the Allow Methods and Allow Origin.
-
-
-
-
The fetch request is the actual request that retrieves data (usually GET or POST) from the server after the preflight request has confirmed that the CORS settings are correct.
-
Final Remarks
After configuring CORS for your Lambda function URL, your Lambda service will now be accessible from different websites without any cross-origin issues. The CORS settings ensure that the browser allows the necessary requests and responses between different origins, letting you securely share your Lambda resources, such as public APIs or Python projects. Please note that CORS is important for protecting users and ensuring that only allowed sites can access your resources. So make sure you always review your settings carefully, especially when it comes to what methods and headers you’re allowing. By using this tutorial guide, you now have a functioning Python Labs Client App that can safely communicate with your Lambda function, handling cross-origin requests as needed. You can always return to the CORS settings to make adjustments if you need to further refine how external websites can interact with your resources.