#NEWLINE# def sign_request( access_key , secret_key , method = 'post' , service = 'apigateway' , host = 'apigateway.us-east-1.amazonaws.com' , region = 'us-east-1' , request_parameters = '' , request_body = None , canonical_uri = '/restapis' ) : #NEWLINE# #INDENT# request_body = ( json . dumps ( request_body ) if request_body else '' ) #NEWLINE# endpoint = ( ( 'https://' + host ) + canonical_uri ) #NEWLINE# if ( ( access_key is None ) or ( secret_key is None ) ) : #NEWLINE# #INDENT# raise Exception ( 'No access key or secret available' ) #NEWLINE# #UNINDENT# t = datetime . datetime . utcnow ( ) #NEWLINE# amzdate = t . strftime ( '%Y%m%dT%H%M%SZ' ) #NEWLINE# datestamp = t . strftime ( '%Y%m%d' ) #NEWLINE# canonical_querystring = request_parameters #NEWLINE# canonical_headers = ( ( ( ( ( 'host:' + host ) + '\n' ) + 'x-amz-date:' ) + amzdate ) + '\n' ) #NEWLINE# signed_headers = 'host;x-amz-date' #NEWLINE# payload_hash = hashlib . sha256 ( request_body ) . hexdigest ( ) #NEWLINE# canonical_request = ( ( ( ( ( ( ( ( ( ( method . upper ( ) + '\n' ) + canonical_uri ) + '\n' ) + canonical_querystring ) + '\n' ) + canonical_headers ) + '\n' ) + signed_headers ) + '\n' ) + payload_hash ) #NEWLINE# algorithm = 'AWS4-HMAC-SHA256' #NEWLINE# credential_scope = ( ( ( ( ( ( datestamp + '/' ) + region ) + '/' ) + service ) + '/' ) + 'aws4_request' ) #NEWLINE# string_to_sign = ( ( ( ( ( ( algorithm + '\n' ) + amzdate ) + '\n' ) + credential_scope ) + '\n' ) + hashlib . sha256 ( canonical_request ) . hexdigest ( ) ) #NEWLINE# signing_key = getSignatureKey ( secret_key , datestamp , region , service ) #NEWLINE# signature = hmac . new ( signing_key , string_to_sign . encode ( 'utf-8' ) , hashlib . sha256 ) . hexdigest ( ) #NEWLINE# authorization_header = ( ( ( ( ( ( ( ( ( ( ( algorithm + ' ' ) + 'Credential=' ) + access_key ) + '/' ) + credential_scope ) + ', ' ) + 'SignedHeaders=' ) + signed_headers ) + ', ' ) + 'Signature=' ) + signature ) #NEWLINE# headers = { #NEWLINE# #INDENT# 'x-amz-date' : amzdate , #NEWLINE# 'Authorization' : authorization_header , #NEWLINE# #UNINDENT# } #NEWLINE# request_url = endpoint #NEWLINE# if canonical_querystring : #NEWLINE# #INDENT# request_url += ( '?' + canonical_querystring ) #NEWLINE# #UNINDENT# if ( method == 'delete' ) : #NEWLINE# #INDENT# r = requests . delete ( request_url , headers = headers ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( method == 'get' ) : #NEWLINE# #INDENT# r = requests . get ( request_url , headers = headers ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( method == 'put' ) : #NEWLINE# #INDENT# r = requests . put ( request_url , headers = headers , data = request_body ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# r = requests . post ( request_url , headers = headers , data = request_body ) #NEWLINE# #UNINDENT# #UNINDENT# #UNINDENT# return r