Best Python code snippet using localstack_python
router_asf.py
Source:router_asf.py
...11from localstack.services.apigateway.helpers import get_api_region12from localstack.services.apigateway.invocations import invoke_rest_api_from_request13from localstack.utils.aws.aws_responses import LambdaResponse14LOG = logging.getLogger(__name__)15def to_invocation_context(16 request: Request, url_params: Dict[str, Any] = None17) -> ApiInvocationContext:18 """19 Converts an HTTP Request object into an ApiInvocationContext.20 :param request: the original request21 :param url_params: the parameters extracted from the URL matching rules22 :return: the ApiInvocationContext23 """24 if url_params is None:25 url_params = {}26 method = request.method27 path = request.full_path if request.query_string else request.path28 data = restore_payload(request)29 headers = Headers(request.headers)30 # adjust the X-Forwarded-For header31 x_forwarded_for = headers.getlist("X-Forwarded-For")32 x_forwarded_for.append(request.remote_addr)33 x_forwarded_for.append(request.host)34 headers["X-Forwarded-For"] = ", ".join(x_forwarded_for)35 # set the x-localstack-edge header, it is used to parse the domain36 headers[HEADER_LOCALSTACK_EDGE_URL] = request.host_url.strip("/")37 # FIXME: Use the already parsed url params instead of parsing them into the ApiInvocationContext part-by-part.38 # We already would have all params at hand to avoid _all_ the parsing, but the parsing39 # has side-effects (f.e. setting the region in a thread local)!40 # It would be best to use a small (immutable) context for the already parsed params and the Request object41 # and use it everywhere.42 return ApiInvocationContext(method, path, data, headers, stage=url_params.get("stage"))43def convert_response(result: RequestsResponse) -> Response:44 """45 Utility function to convert a response for the requests library to our internal (Werkzeug based) Response object.46 """47 if result is None:48 return Response()49 if isinstance(result, LambdaResponse):50 headers = Headers(dict(result.headers))51 for k, values in result.multi_value_headers.items():52 for value in values:53 headers.add(k, value)54 else:55 headers = dict(result.headers)56 response = Response(status=result.status_code, headers=headers)57 if isinstance(result.content, dict):58 response.set_json(result.content)59 elif isinstance(result.content, (str, bytes)):60 response.data = result.content61 else:62 raise ValueError(f"Unhandled content type {type(result.content)}")63 return response64class ApigatewayRouter:65 """66 Simple implementation around a Router to manage dynamic restapi routes (routes added by a user through the67 apigateway API).68 """69 router: Router[Handler]70 def __init__(self, router: Router[Handler]):71 self.router = router72 self.registered = False73 def register_routes(self) -> None:74 """Registers parameterized routes for API Gateway user invocations."""75 if self.registered:76 LOG.debug("Skipped API gateway route registration (routes already registered).")77 return78 self.registered = True79 LOG.debug("Registering parameterized API gateway routes.")80 self.router.add(81 "/",82 host="<api_id>.execute-api.<regex('.*'):server>",83 endpoint=self.invoke_rest_api,84 defaults={"path": "", "stage": None},85 )86 self.router.add(87 "/<stage>/",88 host="<api_id>.execute-api.<regex('.*'):server>",89 endpoint=self.invoke_rest_api,90 defaults={"path": ""},91 )92 self.router.add(93 "/<stage>/<path:path>",94 host="<api_id>.execute-api.<regex('.*'):server>",95 endpoint=self.invoke_rest_api,96 )97 # add the localstack-specific _user_request_ routes98 self.router.add(99 "/restapis/<api_id>/<stage>/_user_request_",100 endpoint=self.invoke_rest_api,101 defaults={"path": ""},102 )103 self.router.add(104 "/restapis/<api_id>/<stage>/_user_request_/<path:path>",105 endpoint=self.invoke_rest_api,106 )107 def invoke_rest_api(self, request: Request, **url_params: Dict[str, Any]) -> Response:108 if not get_api_region(url_params["api_id"]):109 return Response(status=404)110 invocation_context = to_invocation_context(request, url_params)111 result = invoke_rest_api_from_request(invocation_context)112 if result is not None:113 return convert_response(result)...
provider_asf.py
Source:provider_asf.py
...23 @handler("TestInvokeMethod", expand=False)24 def test_invoke_method(25 self, context: RequestContext, request: TestInvokeMethodRequest26 ) -> TestInvokeMethodResponse:27 invocation_context = to_invocation_context(context.request)28 invocation_context.method = request["httpMethod"]29 if data := parse_json_or_yaml(to_str(invocation_context.data or b"")):30 orig_data = data31 if path_with_query_string := orig_data.get("pathWithQueryString"):32 invocation_context.path_with_query_string = path_with_query_string33 invocation_context.data = data.get("body")34 invocation_context.headers = orig_data.get("headers", {})35 result = invoke_rest_api_from_request(invocation_context)36 # TODO: implement the other TestInvokeMethodResponse parameters37 # * multiValueHeaders: Optional[MapOfStringToList]38 # * log: Optional[String]39 # * latency: Optional[Long]40 return TestInvokeMethodResponse(41 status=result.status_code,...
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!!