Best Python code snippet using localstack_python
HttpSigServer.py
Source:HttpSigServer.py
...63# digest = self.hasher_constructor(request.body).digest()64# request.headers["Digest"] = "SHA-256=" + base64.b64encode(digest).decode()65#66# @classmethod67# def get_string_to_sign(self, request, headers):68# sts = []69# for header in headers:70# if header == "(request-target)":71# path_url = requests.models.RequestEncodingMixin.path_url.fget(request)72# sts.append("(request-target): {} {}".format(request.method.lower(), path_url))73# else:74# if header.lower() == "host":75# value = request.headers.get("host", urlparse(request.url).hostname)76# else:77# value = request.headers[header]78# sts.append("{k}: {v}".format(k=header.lower(), v=value))79# return "\n".join(sts).encode()80#81# def __call__(self, request):82# self.add_date(request)83# self.add_digest(request)84# raw_sig = Crypto(self.algorithm).sign(string_to_sign=self.get_string_to_sign(request, self.headers),85# key=self.key,86# passphrase=self.passphrase)87# sig = base64.b64encode(raw_sig).decode()88# sig_struct = [("keyId", self.key_id),89# ("algorithm", self.algorithm),90# ("headers", " ".join(self.headers)),91# ("signature", sig)]92# request.headers["Authorization"] = "Signature " + ",".join('{}="{}"'.format(k, v) for k, v in sig_struct)93# return request94#95# @classmethod96# def get_sig_struct(self, request):97# scheme, sig_struct = request.headers["Authorization"].split(" ", 1)98# return {i.split("=", 1)[0]: i.split("=", 1)[1].strip('"') for i in sig_struct.split(",")}99#100# @classmethod101# def verify(self, request, key_resolver):102# assert "Authorization" in request.headers, "No Authorization header found"103# msg = 'Unexpected scheme found in Authorization header (expected "Signature")'104# assert request.headers["Authorization"].startswith("Signature "), msg105# sig_struct = self.get_sig_struct(request)106# for field in "keyId", "algorithm", "signature":107# assert field in sig_struct, 'Required signature parameter "{}" not found'.format(field)108# assert sig_struct["algorithm"] in self.known_algorithms, "Unknown signature algorithm"109# headers = sig_struct.get("headers", "date").split(" ")110# sig = base64.b64decode(sig_struct["signature"])111# sts = self.get_string_to_sign(request, headers)112# key = key_resolver(key_id=sig_struct["keyId"], algorithm=sig_struct["algorithm"])113# Crypto(sig_struct["algorithm"]).verify(sig, sts, key)114#115# class HTTPSignatureHeaderAuth(HTTPSignatureAuth):116# """117# https://tools.ietf.org/html/draft-cavage-http-signatures-08#section-4118#119# Using "Signature" header instead of "Authorization" header.120# """121#122# def __call__(self, request):123# self.add_date(request)124# self.add_digest(request)125# raw_sig = Crypto(self.algorithm).sign(string_to_sign=self.get_string_to_sign(request, self.headers),126# key=self.key,127# passphrase=self.passphrase)128# sig = base64.b64encode(raw_sig).decode()129# sig_struct = [("keyId", self.key_id),130# ("algorithm", self.algorithm),131# ("headers", " ".join(self.headers)),132# ("signature", sig)]133# request.headers["Signature"] = ",".join('{}="{}"'.format(k, v) for k, v in sig_struct)134# return request...
test__init__.py
Source:test__init__.py
...7 secret = b'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'8 signature = sign(secret, string)9 assert(signature == expected_signature)10def test_sign_get():11 string = get_string_to_sign("GET","", "", "Tue, 27 Mar 2007 19:36:42 +0000", {}, "/johnsmith/photos/puppy.jpg")12 expected_string = "GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/johnsmith/photos/puppy.jpg".encode('utf-8')13 expected_signature = b"bWq2s1WEIj+Ydj0vQ697zp+IXMU="14 validate_signature(string, expected_string, expected_signature)15def test_sign_put():16 string = get_string_to_sign("PUT", "", "image/jpeg", "Tue, 27 Mar 2007 21:15:45 +0000", {}, "/johnsmith/photos/puppy.jpg" )17 expected_string = "PUT\n\nimage/jpeg\nTue, 27 Mar 2007 21:15:45 +0000\n/johnsmith/photos/puppy.jpg".encode('utf-8')18 expected_signature = b"MyyxeRY7whkBe+bq8fHCL/2kKUg="19 validate_signature(string, expected_string, expected_signature)20def test_sign_list():21 string = get_string_to_sign("GET","", "", "Tue, 27 Mar 2007 19:42:41 +0000", {}, "/johnsmith/")22 expected_string = "GET\n\n\nTue, 27 Mar 2007 19:42:41 +0000\n/johnsmith/".encode('utf-8')23 expected_signature = b"htDYFYduRNen8P9ZfE/s9SuKy0U="24 validate_signature(string, expected_string, expected_signature)25@pytest.mark.skip()26def test_sign_copy():27 string = get_string_to_sign("PUT", "", "", "Wed, 20 Feb 2008 22:12:21 +0000", {"x-amz-copy-source":"/pacific/flotsam"}, "/atlantic/jetsam")28 expected_string = "PUT\n\n\nWed, 20 Feb 2008 22:12:21 +0000\nx-amz-copy-source:/pacific/flotsam\n/atlantic/jetsam".encode('utf-8')29 expected_signature = b"ENoSbxYByFA0UGLZUqJN5EUnLDg="30 validate_signature(string, expected_string, expected_signature)31def test_s3_request_arg():32 assert s3lib._calculate_query_arg_str({}) == ""33 assert s3lib._calculate_query_arg_str({'k':None}) == "?k"34 assert s3lib._calculate_query_arg_str({'k':'v'}) == "?k=v"35 assert s3lib._calculate_query_arg_str({'k':'v', 'f':None}) == "?f&k=v"36 two_args = s3lib._calculate_query_arg_str({'k1':'v1', 'k2':'v2'}) 37 assert re.findall("k2=v2", two_args) and re.findall("k1=v1", two_args)38 # Test url-encoding.39 assert s3lib._calculate_query_arg_str({"b@dkey": "b@dvalue$$"}) == "?b%40dkey=b%40dvalue%24%24"...
ddnsqcloud2.py
Source:ddnsqcloud2.py
...14import random15import requests16secret_id = ""17secret_key = ""18def get_string_to_sign(method, endpoint, params):19 s = method + endpoint + "/?"20 query_str = "&".join("%s=%s" % (k, params[k]) for k in sorted(params))21 return s + query_str22def sign_str(key, s, method):23 hmac_str = hmac.new(key.encode("utf8"), s.encode("utf8"), method).digest()24 return base64.b64encode(hmac_str)25if __name__ == '__main__':26 ipv6Addr = '2409:8a62:287:9ab0:b128:51fd:fd4c:d4e3' # getIPAddress()27 timestamp = int(time.time())28 nonce = random.randint(1000, 9999)29 endpoint = "cns.api.qcloud.com/v2/index.php"30 data = {31 'Action': 'RecordList',32 'Nonce': nonce,33 'Region': 'ap-chengdu',34 'SecretId': secret_id,35 'SignatureMethod': 'HmacSHA256',36 'Timestamp': timestamp,37 'domain': 'qpanda.vip',38 'length': '20',39 'offset': '0'40 }41 s = get_string_to_sign("GET", endpoint, data)42 data["Signature"] = sign_str(secret_key, s, hashlib.sha256)43 print(data["Signature"])44 # æ¤å¤ä¼å®é
è°ç¨ï¼æååå¯è½äº§ç计费45 resp = requests.get("https://" + endpoint, params=data)46 print(resp.url)47 print('-----------------------------------')...
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!!