Best Python code snippet using localstack_python
s3_starter.py
Source:s3_starter.py
...113 headers["x-amz-bucket-region"] = bucket.region_name114 return code, headers, body115 _bucket_response_head_orig = s3_responses.ResponseObject._bucket_response_head116 s3_responses.ResponseObject._bucket_response_head = _bucket_response_head117 def _bucket_response_get(self, bucket_name, querystring, *args, **kwargs):118 result = _bucket_response_get_orig(self, bucket_name, querystring, *args, **kwargs)119 # for some reason in the "get-bucket-location" call, moto doesn't return a code, headers, body triple as a result120 if isinstance(result, tuple) and len(result) == 3:121 code, headers, body = result122 bucket = s3_models.s3_backend.get_bucket(bucket_name)123 headers["x-amz-bucket-region"] = bucket.region_name124 return result125 _bucket_response_get_orig = s3_responses.ResponseObject._bucket_response_get126 # note: method type is only required when the method is part of an object instance (make a method out of a function)127 s3_responses.ResponseObject._bucket_response_get = _bucket_response_get128 # patch S3Bucket.get_bucket(..)129 def delete_bucket(self, bucket_name, *args, **kwargs):130 bucket_name = s3_listener.normalize_bucket_name(bucket_name)131 s3_listener.remove_bucket_notification(bucket_name)132 return delete_bucket_orig(bucket_name, *args, **kwargs)133 delete_bucket_orig = s3_models.s3_backend.delete_bucket134 s3_models.s3_backend.delete_bucket = types.MethodType(delete_bucket, s3_models.s3_backend)135 # patch _key_response_post(..)136 def s3_key_response_post(self, request, body, bucket_name, query, key_name, *args, **kwargs):137 result = s3_key_response_post_orig(138 request, body, bucket_name, query, key_name, *args, **kwargs139 )140 s3_update_acls(self, request, query, bucket_name, key_name)141 try:142 if query.get("uploadId"):143 if (bucket_name, key_name) in TMP_TAG:144 key = self.backend.get_object(bucket_name, key_name)145 self.backend.set_key_tags(146 key, TMP_TAG.get((bucket_name, key_name), None), key_name147 )148 TMP_TAG.pop((bucket_name, key_name))149 except Exception:150 pass151 if query.get("uploads") and request.headers.get("X-Amz-Tagging"):152 tags = self._tagging_from_headers(request.headers)153 TMP_TAG[(bucket_name, key_name)] = tags154 return result155 s3_key_response_post_orig = s3_responses.S3ResponseInstance._key_response_post156 s3_responses.S3ResponseInstance._key_response_post = types.MethodType(157 s3_key_response_post, s3_responses.S3ResponseInstance158 )159 # patch _key_response_put(..)160 def s3_key_response_put(161 self, request, body, bucket_name, query, key_name, headers, *args, **kwargs162 ):163 result = s3_key_response_put_orig(164 request, body, bucket_name, query, key_name, headers, *args, **kwargs165 )166 s3_update_acls(self, request, query, bucket_name, key_name)167 return result168 s3_key_response_put_orig = s3_responses.S3ResponseInstance._key_response_put169 s3_responses.S3ResponseInstance._key_response_put = types.MethodType(170 s3_key_response_put, s3_responses.S3ResponseInstance171 )172 # patch DeleteObjectTagging173 def s3_key_response_delete(self, headers, bucket_name, query, key_name, *args, **kwargs):174 # Fixes https://github.com/localstack/localstack/issues/1083175 if query.get("tagging"):176 self._set_action("KEY", "DELETE", query)177 self._authenticate_and_authorize_s3_action()178 key = self.backend.get_object(bucket_name, key_name)179 key.tags = {}180 self.backend.tagger.delete_all_tags_for_resource(key.arn)181 return 204, {}, ""182 result = s3_key_response_delete_orig(headers, bucket_name, query, key_name, *args, **kwargs)183 return result184 s3_key_response_delete_orig = s3_responses.S3ResponseInstance._key_response_delete185 s3_responses.S3ResponseInstance._key_response_delete = types.MethodType(186 s3_key_response_delete, s3_responses.S3ResponseInstance187 )188 action_map = s3_responses.ACTION_MAP189 action_map["KEY"]["DELETE"]["tagging"] = (190 action_map["KEY"]["DELETE"].get("tagging") or "DeleteObjectTagging"191 )192 # patch _key_response_get(..)193 # https://github.com/localstack/localstack/issues/2724194 class InvalidObjectState(S3ClientError):195 code = 400196 def __init__(self, *args, **kwargs):197 super(InvalidObjectState, self).__init__(198 "InvalidObjectState",199 "The operation is not valid for the object's storage class.",200 *args,201 **kwargs,202 )203 def s3_key_response_get(self, bucket_name, query, key_name, headers, *args, **kwargs):204 resp_status, resp_headers, resp_value = s3_key_response_get_orig(205 bucket_name, query, key_name, headers, *args, **kwargs206 )207 if resp_headers.get("x-amz-storage-class") == "DEEP_ARCHIVE" and not resp_headers.get(208 "x-amz-restore"209 ):210 raise InvalidObjectState()211 return resp_status, resp_headers, resp_value212 s3_key_response_get_orig = s3_responses.S3ResponseInstance._key_response_get213 s3_responses.S3ResponseInstance._key_response_get = types.MethodType(214 s3_key_response_get, s3_responses.S3ResponseInstance215 )216 # patch max-keys217 def s3_truncate_result(self, result_keys, max_keys):218 return s3_truncate_result_orig(result_keys, max_keys or 1000)219 s3_truncate_result_orig = s3_responses.S3ResponseInstance._truncate_result220 s3_responses.S3ResponseInstance._truncate_result = types.MethodType(221 s3_truncate_result, s3_responses.S3ResponseInstance222 )223 # patch _bucket_response_delete_keys(..)224 # https://github.com/localstack/localstack/issues/2077225 s3_delete_keys_response_template = """<?xml version="1.0" encoding="UTF-8"?>226 <DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01">227 {% for k in deleted %}228 <Deleted>229 <Key>{{k.key}}</Key>230 <VersionId>{{k.version_id}}</VersionId>231 </Deleted>232 {% endfor %}233 {% for k in delete_errors %}234 <Error>235 <Key>{{k}}</Key>236 </Error>237 {% endfor %}238 </DeleteResult>"""239 def s3_bucket_response_delete_keys(self, request, body, bucket_name):240 template = self.response_template(s3_delete_keys_response_template)241 elements = minidom.parseString(body).getElementsByTagName("Object")242 if len(elements) == 0:243 raise MalformedXML()244 deleted_names = []245 error_names = []246 keys = []247 for element in elements:248 if len(element.getElementsByTagName("VersionId")) == 0:249 version_id = None250 else:251 version_id = element.getElementsByTagName("VersionId")[0].firstChild.nodeValue252 keys.append(253 {254 "key_name": element.getElementsByTagName("Key")[0].firstChild.nodeValue,255 "version_id": version_id,256 }257 )258 for k in keys:259 key_name = k["key_name"]260 version_id = k["version_id"]261 success = self.backend.delete_object(262 bucket_name, undo_clean_key_name(key_name), version_id263 )264 if success:265 deleted_names.append({"key": key_name, "version_id": version_id})266 else:267 error_names.append(key_name)268 return (269 200,270 {},271 template.render(deleted=deleted_names, delete_errors=error_names),272 )273 s3_responses.S3ResponseInstance._bucket_response_delete_keys = types.MethodType(274 s3_bucket_response_delete_keys, s3_responses.S3ResponseInstance275 )276 # Patch _handle_range_header(..)277 # https://github.com/localstack/localstack/issues/2146278 s3_response_handle_range_header_orig = s3_responses.S3ResponseInstance._handle_range_header279 def s3_response_handle_range_header(self, request, headers, response_content):280 rs_code, rs_headers, rs_content = s3_response_handle_range_header_orig(281 request, headers, response_content282 )283 if rs_code == 206:284 for k in ["ETag", "last-modified"]:285 v = headers.get(k)286 if v and not rs_headers.get(k):287 rs_headers[k] = v288 return rs_code, rs_headers, rs_content289 s3_responses.S3ResponseInstance._handle_range_header = types.MethodType(290 s3_response_handle_range_header, s3_responses.S3ResponseInstance291 )292 # Patch utils_is_delete_keys293 # https://github.com/localstack/localstack/issues/2866294 # https://github.com/localstack/localstack/issues/2850295 # https://github.com/localstack/localstack/issues/3931296 # https://github.com/localstack/localstack/issues/4015297 utils_is_delete_keys_orig = s3bucket_path_utils.is_delete_keys298 def utils_is_delete_keys(request, path, bucket_name):299 return "/" + bucket_name + "?delete=" in path or utils_is_delete_keys_orig(300 request, path, bucket_name301 )302 def s3_response_is_delete_keys(self, request, path, bucket_name):303 if self.subdomain_based_buckets(request):304 # Temporary fix until moto supports x-id and DeleteObjects (#3931)305 query = self._get_querystring(request.url)306 is_delete_keys_v3 = (307 query and ("delete" in query) and get_safe(query, "$.x-id.0") == "DeleteObjects"308 )309 return is_delete_keys_v3 or is_delete_keys(request, path, bucket_name)310 else:311 return utils_is_delete_keys(request, path, bucket_name)312 s3_responses.S3ResponseInstance.is_delete_keys = types.MethodType(313 s3_response_is_delete_keys, s3_responses.S3ResponseInstance314 )315 def parse_bucket_name_from_url(self, request, url):316 path = urlparse(url).path317 return s3_utils.extract_bucket_name(request.headers, path)318 s3_responses.S3ResponseInstance.parse_bucket_name_from_url = types.MethodType(319 parse_bucket_name_from_url, s3_responses.S3ResponseInstance320 )321 def subdomain_based_buckets(self, request):322 return s3_utils.uses_host_addressing(request.headers)323 s3_responses.S3ResponseInstance.subdomain_based_buckets = types.MethodType(324 subdomain_based_buckets, s3_responses.S3ResponseInstance325 )326 s3_responses_bucket_response_get_orig = s3_responses.S3ResponseInstance._bucket_response_get327 def s3_bucket_response_get(self, bucket_name, querystring):328 try:329 return s3_responses_bucket_response_get_orig(bucket_name, querystring)330 except NotImplementedError:331 if "uploads" not in querystring:332 raise333 multiparts = list(self.backend.get_all_multiparts(bucket_name).values())334 if "prefix" in querystring:335 prefix = querystring.get("prefix", [None])[0]336 multiparts = [upload for upload in multiparts if upload.key_name.startswith(prefix)]337 upload_ids = [upload_id for upload_id in querystring.get("uploads") if upload_id]338 if upload_ids:339 multiparts = [upload for upload in multiparts if upload.id in upload_ids]340 template = self.response_template(S3_ALL_MULTIPARTS)341 return template.render(bucket_name=bucket_name, uploads=multiparts)...
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!!