Best Python code snippet using localstack_python
cors_tests.py
Source:cors_tests.py  
...58        # Get the CORS config (none yet). 59        # Should get 404 Not Found, with "NoSuchCORSConfiguration" in the body.60        try :    61            self.tester.debug("Getting (empty) CORS config")62            bucket.get_cors()63            #self.tester.s3.delete_bucket(test_bucket)64            #LPT self.fail("Did not get an S3ResponseError getting CORS config when none exists yet.")65        except S3ResponseError as e:66            if (e.status == 404 and e.reason == "Not Found" and e.code == "NoSuchCORSConfiguration"):67                self.tester.debug("Caught S3ResponseError with expected contents, " + 68                                  "getting CORS config when none exists yet.")69            else:70                self.tester.s3.delete_bucket(test_bucket)71                self.fail("Caught S3ResponseError getting CORS config when none exists yet," +72                          "but exception contents were unexpected: " + str(e))73        # Set a simple CORS config.74        try :    75            self.tester.debug("Setting a CORS config")76            bucket_cors_set = CORSConfiguration()77            bucket_rule_id = "ManuallyAssignedId1"78            bucket_allowed_methods = ['GET', 'PUT']79            bucket_allowed_origins = ['*']80            bucket_allowed_headers = ['*']81            bucket_max_age_seconds = 300082            #bucket_expose_headers = []83            bucket_cors_set.add_rule(bucket_allowed_methods, 84                                     bucket_allowed_origins, 85                                     bucket_rule_id,86                                     bucket_allowed_headers, 87                                     bucket_max_age_seconds)88            bucket.set_cors(bucket_cors_set)89        except S3ResponseError as e:90            self.tester.s3.delete_bucket(test_bucket)91            self.fail("Caught S3ResponseError setting CORS config: " + str(e))92                    93        # Get the CORS config. Should get the config we just set.94        try :    95            self.tester.debug("Getting the CORS config we just set")96            bucket_cors_retrieved = bucket.get_cors()97            assert (bucket_cors_retrieved.to_xml() == bucket_cors_set.to_xml()), 'Bucket CORS config: Expected ' + bucket_cors_set.to_xml() + ', Retrieved ' + bucket_cors_retrieved.to_xml()98            99        except S3ResponseError as e:100            self.tester.s3.delete_bucket(test_bucket)101            self.fail("Caught S3ResponseError getting CORS config, after setting it successfully: " + str(e))102        103        # Delete the CORS config.104        try :    105            self.tester.debug("Deleting the CORS config")106            bucket.delete_cors()107        except S3ResponseError as e:108            self.tester.s3.delete_bucket(test_bucket)109            self.fail("Caught S3ResponseError deleting CORS config, after setting and validating it successfully: " + str(e))110        # Get the CORS config (none anymore). 111        # Should get 404 Not Found, with "NoSuchCORSConfiguration" in the body.112        try :    113            self.tester.debug("Getting (empty again) CORS config")114            bucket.get_cors()115            self.tester.s3.delete_bucket(test_bucket)116            self.fail("Did not get an S3ResponseError getting CORS config after being deleted.")117        except S3ResponseError as e:118            self.tester.s3.delete_bucket(test_bucket)119            if (e.status == 404 and e.reason == "Not Found" and e.code == "NoSuchCORSConfiguration"):120                self.tester.debug("Caught S3ResponseError with expected contents, " + 121                                  "getting CORS config after being deleted.")122            else:123                self.fail("Caught S3ResponseError getting CORS config after being deleted," +124                          "but exception contents were unexpected: " + str(e))125    def test_cors_preflight_requests(self):126        '''127        Method: Tests creating a bucket, 128        setting up a complex CORS config,...midlewares.py
Source:midlewares.py  
...6from aiohttp.web_middlewares import middleware7from pydantic import ValidationError8from aore import log9from aore.exceptions import FiasException10def get_cors(origin: str, method: str) -> Dict[str, str]:11    if not origin:12        return {}13    return {14        'Access-Control-Allow-Origin': origin,15        'Access-Control-Allow-Methods': ', '.join(["OPTIONS", method]),16        'Access-Control-Allow-Credentials': 'true',17        'Access-Control-Allow-Headers': '*'18    }19@middleware20async def error_middleware(request: web.Request, handler: Handler) -> web.StreamResponse:21    cors = get_cors(request.headers.get('origin', ''), request.method)22    try:23        return await handler(request)24    except asyncio.exceptions.CancelledError:25        return web.json_response(status=504, data={"error": 'Gateway timeout'}, headers=cors)26    except HTTPNotFound as e:27        return web.json_response(status=404, data={"error": str(e)}, headers=cors)28    except ValidationError as e:29        result = ', '.join([f'{err._loc}: {err.exc}' for err in e.raw_errors])  # type: ignore30        return web.json_response(status=422, data={"error": result}, headers=cors)31    except FiasException as e:32        return web.json_response(status=e.code, data={"error": str(e)}, headers=cors)33    except BaseException as e:34        log.error("Unhandled exception", exc_info=e)35        return web.json_response(status=500, data={"error": 'Internal server error'}, headers=cors)36@middleware37async def cors_middleware(request: web.Request, handler: Handler) -> web.StreamResponse:38    response = await handler(request)39    if request.headers.get('Origin', ''):40        response.headers.update(get_cors(request.headers.get('Origin', ''), request.method))...config.py
Source:config.py  
1"""HIS configuration."""2from functools import cache, partial3from configlib import load_config4__all__ = [5    'CONFIG_FILE',6    'CORS_FILE',7    'RECAPTCHA_FILE',8    'get_config',9    'get_cors',10    'get_recaptcha'11]12CONFIG_FILE = 'his.d/his.conf'13CORS_FILE = 'his.d/cors.json'14RECAPTCHA_FILE = 'his.d/recaptcha.json'15load_config = cache(load_config)16get_config = partial(load_config, CONFIG_FILE)17get_cors = partial(load_config, CORS_FILE)...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!!
