Best Python code snippet using localstack_python
lambda_api.py
Source:lambda_api.py  
...857            del region.event_source_mappings[i]858            i -= 1859        i += 1860    return {}861def get_lambda_url_config(api_id, region=None):862    lambda_backend = LambdaRegion.get(region)863    url_configs = lambda_backend.url_configs.values()864    lambda_url_configs = [config for config in url_configs if config.get("CustomId") == api_id]865    return lambda_url_configs[0]866def event_for_lambda_url(api_id, path, data, headers, method) -> dict:867    raw_path = path.split("?")[0]868    raw_query_string = path.split("?")[1] if len(path.split("?")) > 1 else ""869    query_string_parameters = (870        {} if not raw_query_string else dict(urllib.parse.parse_qsl(raw_query_string))871    )872    now = datetime.utcnow()873    readable = timestamp(time=now, format=TIMESTAMP_READABLE_FORMAT)874    if not any(char in readable for char in ["+", "-"]):875        readable += "+0000"876    source_ip = headers.get("Remote-Addr", "")877    request_context = {878        "accountId": "anonymous",879        "apiId": api_id,880        "domainName": headers.get("Host", ""),881        "domainPrefix": api_id,882        "http": {883            "method": method,884            "path": raw_path,885            "protocol": "HTTP/1.1",886            "sourceIp": source_ip,887            "userAgent": headers.get("User-Agent", ""),888        },889        "requestId": long_uid(),890        "routeKey": "$default",891        "stage": "$default",892        "time": readable,893        "timeEpoch": mktime(ts=now, millis=True),894    }895    content_type = headers.get("Content-Type", "").lower()896    content_type_is_text = any(text_type in content_type for text_type in ["text", "json", "xml"])897    is_base64_encoded = not (data.isascii() and content_type_is_text) if data else False898    body = base64.b64encode(data).decode() if is_base64_encoded else data899    ignored_headers = ["connection", "x-localstack-tgt-api", "x-localstack-request-url"]900    event_headers = {k.lower(): v for k, v in headers.items() if k.lower() not in ignored_headers}901    event_headers.update(902        {903            "x-amzn-tls-cipher-suite": "ECDHE-RSA-AES128-GCM-SHA256",904            "x-amzn-tls-version": "TLSv1.2",905            "x-forwarded-proto": "http",906            "x-forwarded-for": source_ip,907            "x-forwarded-port": str(config.EDGE_PORT),908        }909    )910    event = {911        "version": "2.0",912        "routeKey": "$default",913        "rawPath": raw_path,914        "rawQueryString": raw_query_string,915        "headers": event_headers,916        "queryStringParameters": query_string_parameters,917        "requestContext": request_context,918        "body": body,919        "isBase64Encoded": is_base64_encoded,920    }921    if not data:922        event.pop("body")923    return event924def handle_lambda_url_invocation(925    request: Request, api_id: str, region: str, **url_params: Dict[str, str]926) -> HttpResponse:927    response = HttpResponse(headers={"Content-type": "application/json"})928    try:929        lambda_url_config = get_lambda_url_config(api_id, region)930    except IndexError as e:931        LOG.warning(f"Lambda URL ({api_id}) not found: {e}")932        response.set_json({"Message": None})933        response.status = "404"934        return response935    event = event_for_lambda_url(936        api_id, request.full_path, request.data, request.headers, request.method937    )938    try:939        result = process_lambda_url_invocation(lambda_url_config, event)940    except Exception as e:941        LOG.warning(f"Lambda URL ({api_id}) failed during execution: {e}")942        response.set_json({"Message": "lambda function failed during execution"})943        response.status = "403"...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
