I use the following code in Python to generate authorization headers for getting an object in an S3 bucket (where AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_DEFAULT_REGION, and DEFAULT_BUCKET are all set via environment variables in another piece of code)
def get_s3_headers(object_name):
'''Get authorization headers required to access a certain object in S3.'''
headers = _sig_v4_headers(pre_auth_headers={},
service='s3',
host=f'{DEFAULT_BUCKET}.s3.amazonaws.com',
method='GET',
path='/' + object_name,
query={ 'X-Amz-Expires' : '120' },
payload=b'')
return headers
def _sig_v4_headers(pre_auth_headers, service, host, method, path, query, payload):
# Define use of signature v4
algorithm = 'AWS4-HMAC-SHA256'
now = datetime.datetime.utcnow()
amzdate = now.strftime('%Y%m%dT%H%M%SZ')
datestamp = now.strftime('%Y%m%d')
payload_hash = hashlib.sha256(payload).hexdigest()
credential_scope = f'{datestamp}/{AWS_DEFAULT_REGION}/{service}/aws4_request'
pre_auth_headers_lower = {
header_key.lower(): ' '.join(header_value.split())
for header_key, header_value in pre_auth_headers.items()
}
required_headers = {
'host': host,
'x-amz-content-sha256': payload_hash,
'x-amz-date': amzdate,
}
headers = {**pre_auth_headers_lower, **required_headers}
header_keys = sorted(headers.keys())
signed_headers = ';'.join(header_keys)
def signature():
def canonical_request():
canonical_uri = urllib.parse.quote(path, safe='/~')
quoted_query = sorted(
(urllib.parse.quote(key, safe='~'), urllib.parse.quote(value, safe='~'))
for key, value in query.items()
)
canonical_querystring = '&'.join(f'{key}={value}' for key, value in quoted_query)
canonical_headers = ''.join(f'{key}:{headers[key]}\n' for key in header_keys)
print(canonical_querystring)
return f'{method}\n{canonical_uri}\n{canonical_querystring}\n' + \
f'{canonical_headers}\n{signed_headers}\n{payload_hash}'
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
string_to_sign = f'{algorithm}\n{amzdate}\n{credential_scope}\n' + \
hashlib.sha256(canonical_request().encode('utf-8')).hexdigest()
date_key = sign(('AWS4' + AWS_SECRET_ACCESS_KEY).encode('utf-8'), datestamp)
region_key = sign(date_key, AWS_DEFAULT_REGION)
service_key = sign(region_key, service)
request_key = sign(service_key, 'aws4_request')
return sign(request_key, string_to_sign).hex()
return {
'uri' : f'https://{host}{path}',
'headers' : {
**pre_auth_headers,
'x-amz-date': amzdate,
'x-amz-content-sha256': payload_hash,
'Authorization': f'{algorithm} Credential={AWS_ACCESS_KEY_ID}/{credential_scope}, '
f'SignedHeaders={signed_headers}, Signature=' + signature(),
}
}
Calling get_s3_headers with a valid object key returns something similar to the following:
"headers": {
"Authorization": "AWS4-HMAC-SHA256 Credential=AKIAYS3VM3EBIFL7FKE5/20220324/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=<string of characters>",
"x-amz-content-sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"x-amz-date": "20220324T193132Z"
},
"uri": "https://hotspot-storage.s3.amazonaws.com/posts/61e0dd8056716196cf357434"
Calling GET on https://hotspot-storage.s3.amazonaws.com/posts/61e0dd8056716196cf357434?X-Amz-Expires=120 returns the correct image with no expiration errors. Changing X-Amz-Expires to any other value returns a "Signature not valid" exception as expected. However, I can still use the link and the headers after 120 seconds, as if X-Amz-Expires doesn't actually do anything. I have zero clue why this is not working, so any help would be much appreciated.
EDIT
Changing X-Amz-Expires to 0 in both the query string and Python code still allows access to the link. The expiration time always defaults to 15 minutes.
Related
Hello and thanks in advance for any help
I used this post (How to fix <Response [400]> error when making a request to the Bitget Futures Rest API in Python?) to get me well on my way to creating a post buy limit order for the Bitget API.
I keep getting this error though: {'code': '40409', 'msg': 'wrong format', 'requestTime': 1673551362880, 'data': None}
Looking up that error code suggests it's the time - I presume that used for the nonce - which is incorrect somehow?
For my post order I've tried using exactly the same format as the very useful answer provided by Tariq - https://stackoverflow.com/users/12907359/tarique in the above post - (Thanks Tariq!) ...therefore, effectively the only things that change from his code (which works for me), is the fact that mine a POST rather than a GET, and the 'query' content is different.
I'm posting below Tariq's code which works and my own as well where I'm getting the error. Any ideas very welcome, thanks!
I have commented where appropriate to highlight Tariq's original code and where I have created similar functions of my own.
import hashlib
import hmac
import base64
import requests
import time
import json
api_passphrase = "your secret"
api_key = "api key"
api_sec = "api secret"
api_url = "https://api.bitget.com"
#symbol = "BTCUSDT_UMCBL" # this is futures
symbol = 'BTC/USDT' # this is spot - I've added this here
def parse_params_to_str(params):
url = '?'
for key, value in params.items():
url = url + str(key) + '=' + str(value) + '&'
return url[0:-1]
def get_signature(message):
mac = hmac.new(bytes(api_sec, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
d = mac.digest()
return base64.b64encode(d)
def bitget_request_info(request_path, body, query, method): # this is Tariq's
std_time = time.time() * 1000
new_time = int(std_time)
if str(body) == '{}' or str(body) == 'None':
converted_body = ''
else:
converted_body = json.dumps(body)
message = str(new_time) + method + request_path + parse_params_to_str(query) + converted_body
headers = {"ACCESS-KEY": api_key,
"ACCESS-SIGN": get_signature(message),
"ACCESS-TIMESTAMP": str(new_time),
"ACCESS-PASSPHRASE": api_passphrase,
"Content-Type": "application/json",
"Locale": "en-US"
}
if method == "GET":
request_resp = requests.get((api_url + request_path), headers=headers, params=query)
return request_resp
def bitget_post_buy_order(request_path, body, query, method): # This is my version for the post buy order
std_time = time.time() * 1000
new_time = int(std_time)
if str(body) == '{}' or str(body) == 'None':
converted_body = ''
else:
converted_body = json.dumps(body)
message = str(new_time) + method + request_path + parse_params_to_str(query) + converted_body
headers = {"ACCESS-KEY": api_key,
"ACCESS-SIGN": get_signature(message),
"ACCESS-TIMESTAMP": str(new_time),
"ACCESS-PASSPHRASE": api_passphrase
"Content-Type": "application/json",
"Locale": "en-US"
}
if method == "POST":
request_resp = requests.post((api_url + request_path), headers=headers, params=query)
return request_resp
def get_info(): # this was Tariq's (I put it in a def)
order_resp = bitget_request_info("/api/mix/v1/account/account", None, query, "GET")
print(order_resp.json())
def place_buy_order(): # this is my version
place_order = bitget_post_buy_order("/api/spot/v1/trade/orders", None, query, "POST")
print(place_order.json())
def get_query_deets(): # this was Tariq's original
global query
query = {
"symbol": symbol,
"marginCoin": "USDT"
}
return(query)
def buy_order_deets(): # this is mine for the post buy order query
global query
query = {
'symbol': symbol,
'side': 'buy',
'orderType': 'limit',
'price': 9999,
'quantity': 0.01
}
return(query)
def main():
buy_order_deets()
place_buy_order()
#get_query_deets()
#get_info()
main()
When I make requests to the 'Inventory' or 'Sales' endpoints, I get successful responses. This confirms that my signature and IAM are correct. I am manually signing the requests because I am not sure how to use boto3 to create the signature.
I am not sure why, but when making POST requests, the response will state The Canonical String for this request should have been... and provides the payload_hash below. I am copy/pasting the string provides. Once I do this, I then get the InvalidInput response. However, when using GET requests, I am able to use payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest() as seen below and it works fine.
This is the same response as with GET_SALES_AND_TRAFFIC_REPORT and other reports.
CREATING CANONICAL STRING :
t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d')
canonical_querystring = '/reports/2021-06-30/reports'
signed_headers = 'host;user-agent;x-amz-access-token;x-amz-date'
payload_hash = 'deda182f2e780e6c5e6abb9b19a087a8db6c620c39e784bf4a3384e76d742278'
# payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()
canonical_request = method + '\n' + canonical_querystring + '\n' + '\n' + 'host:' + host + '\n' + 'user-agent:python-requests/2.27.1' + '\n' + 'x-amz-access-token:' + access + '\n' + 'x-amz-date:' + amzdate + '\n' + '\n' + signed_headers + '\n' + payload_hash
REQUEST:
headers = {
'x-amz-access-token': access,
'x-amz-date':amzdate,
'Authorization':authorization_header,
'Content-Type': 'application/json'
}
data = {
'marketplaceIds':'ATVPDKIKX0DER',
'reportType': 'GET_SALES_AND_TRAFFIC_REPORT',
'dataStartTime':'2022-03-10T20:11:24.000Z',
'dataEndTime':'2022-03-20T20:11:24.000Z',
'reportOptions':{
'dateGranularity':'WEEK',
'asinGranularity':'CHILD'
}
}
r = requests.post(
'https://sellingpartnerapi-na.amazon.com/reports/2021-06-30/reports',
headers = headers,
data = data
)
print(r)
print(r.text)
RESPONSE:
<Response [400]>
{
"errors": [
{
"code": "InvalidInput",
"message": "Invalid Input",
"details": ""
}
]
}
Took me awhile to get the signing stuff to work in postman, just looking at your request I believe MarketplaceIds needs to be an array, although you would get a specific error if that was the main problem:
"marketplaceIds": [
"ATVPDKIKX0DER"
]
I was just working on this. So, I used AWS4Auth for creating a canonical string just to be sure that I'm not messing with any of it.
A way to do that: (Assuming you have already generated LWA access token, which I can see in your header as 'access')
import json
import boto3
from requests_aws4auth.aws4auth import AWS4Auth
client = boto3.client('sts')
aws_account_id = 'YOUR_ACCOUNT_ID'
iamrole = 'arn:aws:iam::'+aws_account_id+':role/YOU_ROLE_NAME'
response = client.assume_role(
RoleArn= iamrole,
RoleSessionName='SPAPIRoleSession'
)
# Initializing AccessKey, SecretKey and SessionToken variables to be used in signature signing.
AccessKeyId = response['Credentials']['AccessKeyId']
SecretAccessKey = response['Credentials']['SecretAccessKey']
SessionToken = response['Credentials']['SessionToken']
#add your region accordingly: my region is us-east-1
auth = AWS4Auth(AccessKeyId, SecretAccessKey, 'us-east-1', 'execute-api', session_token=SessionToken)
# Create headers to add to SP API request. Headers should include: content_type and "x-amz-access-token"(b)
headers = {'content-type': 'application/json','Accept': 'application/json','x-amz-access-token':access}
#your params: I made a small change to 'dataEndTime', if you mentioned the granularity as a week, make sure the start and end dates are 7 days apart. Look at the AWS documentation for more details
data = {
'marketplaceIds':'ATVPDKIKX0DER',
'reportType': 'GET_SALES_AND_TRAFFIC_REPORT',
'dataStartTime':'2022-03-10T20:11:24.000Z',
'dataEndTime':'2022-03-17T20:11:24.000Z',
'reportOptions':{
'dateGranularity':'WEEK',
'asinGranularity':'CHILD'}
}
# Change data to json and add auth as additional parameter
reportId = requests.post("https://sellingpartnerapi-na.amazon.com/reports/2021-06-30/reports",
json=(data),
headers=headers,
auth=auth)
print(reportId)
print(reportId.json())
RESPONSE:
<Response [202]>
{'reportId': '54120019456'}
This should result in giving you the reportId required. Let me know if this helps. Thanks
I am trying to send an authentificated message over an API at iconomi.com.
I am used to sign message when dealing with other exchange API, but can't be authentificated with this specific one.
I read the official documentation for authentification:
You generate the ICN-SIGN header by creating a sha512 HMAC using the
base64-decoded secret key on the prehash string timestamp + method +
requestPath + body (where + represents string concatenation) and
base64-encode the output, where:
the timestamp value is the same as the ICN-TIMESTAMP header. the body
is the request body string or omitted if there is no request body
(typically for GET requests). method must always be in upper case
Example: base64_encode(HMAC_SHA512(secret_key, timestamp + upper_case(method) + requestPath + body))
I found also a java client example on the official github, please see bellow signature generation in java :
private String generateServerDigest(String method, String uri, long timestamp, String body) {
//return timestamp + request.getMethodValue() + uri + body;
String checkDigestString = timestamp + method + uri + body;// "GET+/v1/daa-list+123123123"; //timestamp in epoch milliseconds
// hash server composited digest with algorithm and apikeys secret
SecretKeySpec signingKey = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA512");
Mac mac;
try {
mac = Mac.getInstance(signingKey.getAlgorithm());
mac.init(signingKey);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
log.warn("Could not ={}", signingKey.getAlgorithm());
return null;
}
return Base64.getEncoder().encodeToString(mac.doFinal(checkDigestString.getBytes()));
}
Please note that checkDigestString code timestamp + method + uri + body and comment GET+/v1/daa-list+123123123 are already different on the official doc.
And this is my python implementation attempt :
def sign(timestamp,method,requestPath,body):
global api_secret
base64_decoded_secret_key = base64.b64decode(api_secret)
content_to_hash = (str(timestamp) + method.upper() + requestPath + body).encode('utf-8')
sign_digest = hmac.new(base64_decoded_secret_key, content_to_hash , hashlib.sha512).digest()
return base64.b64encode(sign_digest).decode('utf-8')
When I try this signature method with requestPath = "/v1/user/balance" (which required to be authentificated), it fail without error...
Does any one used with both java and python may help me to convert this signature method to python ?
This code will work for GET:
import time,requests
import hashlib,hmac,base64
api_key = "my api key"
api_secret = "my api secret"
defaut_encoding = "utf8"
uri = "https://api.iconomi.com"
requestPath = "/v1/user/balance"
api_url_target = uri+requestPath # https://api.iconomi.com/v1/user/balance
method="GET"
body=""
icn_timestamp = int(1000.*time.time())
message = (str(icn_timestamp) + method.upper() + requestPath + body).encode(defaut_encoding)
signature_digest = hmac.new(api_secret.encode(defaut_encoding), message, hashlib.sha512).digest() #here digest is byte
b64_signature_digest= base64.b64encode(signature_digest).decode(defaut_encoding)
headers_sign= {
"ICN-API-KEY":api_key,
"ICN-SIGN":b64_signature_digest,
"ICN-TIMESTAMP":str(icn_timestamp)
}
s=requests.session()
res = s.get(api_url_target,headers=headers_sign,timeout=3, verify=True).content
print (res)
Update for #Karl comment, this code will work for POST:
import time,requests
import hashlib,hmac,base64,json
api_key = "my api key"
api_secret = "my api secret"
ticker = "my ticker strategy"
defaut_encoding = "utf8"
uri = "https://api.iconomi.com"
requestPath = "/v1/strategies/"+ticker+"/structure"
api_url_target = uri+requestPath # https://api.iconomi.com/v1/strategies/{my ticker strategy}/structure
method="POST"
body="{'ticker': ticker, 'values': [{'rebalancedWeight': 1., 'targetWeight':1., 'assetTicker': 'XMR', 'assetName': 'Monero', 'assetCategory': 'Privacy'}]}"
icn_timestamp = int(1000.*time.time())
message = (str(icn_timestamp) + method.upper() + requestPath + body).encode(defaut_encoding)
signature_digest = hmac.new(api_secret.encode(defaut_encoding), message, hashlib.sha512).digest() #here digest is byte
b64_signature_digest= base64.b64encode(signature_digest).decode(defaut_encoding)
headers_sign= {
"ICN-API-KEY":api_key,
"ICN-SIGN":b64_signature_digest,
"ICN-TIMESTAMP":str(icn_timestamp)
}
s=requests.session()
res = s.post(api_url_target,headers=headers_sign,json = json.loads(body), timeout=3, verify=True).content
print (res)
I'm working on a project with Python(3.6) & Django(1.10) in which I need to create a function at Google cloud using API request.
How can upload code in the form of a zip archive while creating that function?
Here's what I have tried:
From views.py :
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = forms.SlsForm(post_data, request.FILES)
print('get post request')
if form.is_valid():
func_obj = form
func_obj.user = request.user
func_obj.project = form.cleaned_data['project']
func_obj.fname = form.cleaned_data['fname']
func_obj.fmemory = form.cleaned_data['fmemory']
func_obj.entryPoint = form.cleaned_data['entryPoint']
func_obj.sourceFile = form.cleaned_data['sourceFile']
func_obj.sc_github = form.cleaned_data['sc_github']
func_obj.sc_inline_index = form.cleaned_data['sc_inline_index']
func_obj.sc_inline_package = form.cleaned_data['sc_inline_package']
func_obj.bucket = form.cleaned_data['bucket']
func_obj.save()
service = discovery.build('cloudfunctions', 'v1', http=views.getauth(), cache_discovery=False)
requ = service.projects().locations().functions().generateUploadUrl(parent='projects/' + func_obj.project + '/locations/us-central1', body={})
resp = requ.execute()
print(resp)
try:
auth = views.getauth()
# Prepare Request Body
req_body = {
"CloudFunction": {
"name": func_obj.fname,
"entryPoint": func_obj.entryPoint,
"timeout": '60s',
"availableMemoryMb": func_obj.fmemory,
"sourceArchiveUrl": func_obj.sc_github,
},
"sourceUploadUrl": func_obj.bucket,
}
service = discovery.build('cloudfunctions', 'v1beta2', http=auth, cachce_dicovery=False)
func_req = service.projects().locations().functions().create(location='projects/' + func_obj.project
+ '/locations/-',
body=req_body)
func_res = func_req.execute()
print(func_res)
return HttpResponse('Submitted',)
except:
return HttpResponse(status=500)
return HttpResponse('Sent!')
Updated Code below:
if form.is_valid():
func_obj = form
func_obj.user = request.user
func_obj.project = form.cleaned_data['project']
func_obj.fname = form.cleaned_data['fname']
func_obj.fmemory = form.cleaned_data['fmemory']
func_obj.entryPoint = form.cleaned_data['entryPoint']
func_obj.sourceFile = form.cleaned_data['sourceFile']
func_obj.sc_github = form.cleaned_data['sc_github']
func_obj.sc_inline_index = form.cleaned_data['sc_inline_index']
func_obj.sc_inline_package = form.cleaned_data['sc_inline_package']
func_obj.bucket = form.cleaned_data['bucket']
func_obj.save()
#######################################################################
# FIRST APPROACH FOR FUNCTION CREATION USING STORAGE BUCKET
#######################################################################
file_name = os.path.join(IGui.settings.BASE_DIR, 'media/archives/', func_obj.sourceFile.name)
print(file_name)
service = discovery.build('cloudfunctions', 'v1')
func_api = service.projects().locations().functions()
url_svc_req = func_api.generateUploadUrl(parent='projects/'
+ func_obj.project
+ '/locations/us-central1',
body={})
url_svc_res = url_svc_req.execute()
print(url_svc_res)
upload_url = url_svc_res['uploadUrl']
print(upload_url)
headers = {
'content-type': 'application/zip',
'x-goog-content-length-range': '0,104857600'
}
print(requests.put(upload_url, headers=headers, data=func_obj.sourceFile.name))
auth = views.getauth()
# Prepare Request Body
name = "projects/{}/locations/us-central1/functions/{}".format(func_obj.project, func_obj.fname,)
print(name)
req_body = {
"name": name,
"entryPoint": func_obj.entryPoint,
"timeout": "3.5s",
"availableMemoryMb": func_obj.fmemory,
"sourceUploadUrl": upload_url,
"httpsTrigger": {},
}
service = discovery.build('cloudfunctions', 'v1')
func_api = service.projects().locations().functions()
response = func_api.create(location='projects/' + func_obj.project + '/locations/us-central1',
body=req_body).execute()
pprint.pprint(response)
Now the function has been created successfully, but it fails because the source code doesn't upload to storage bucket, that's maybe something wrong at:
upload_url = url_svc_res['uploadUrl']
print(upload_url)
headers = {
'content-type': 'application/zip',
'x-goog-content-length-range': '0,104857600'
}
print(requests.put(upload_url, headers=headers, data=func_obj.sourceFile.name))
In the request body you have a dictionary "CloudFunction" inside the request. The content of "CloudFunction" should be directly in request.
request_body = {
"name": parent + '/functions/' + name,
"entryPoint": entry_point,
"sourceUploadUrl": upload_url,
"httpsTrigger": {}
}
I recomend using "Try this API" to discover the structure of projects.locations.functions.create .
"sourceArchiveUrl" and "sourceUploadUrl" can't appear together. This is explained in Resorce Cloud Function:
// Union field source_code can be only one of the following:
"sourceArchiveUrl": string,
"sourceRepository": { object(SourceRepository) },
"sourceUploadUrl": string,
// End of list of possible types for union field source_code.
In the rest of the answer I assume that you want to use "sourceUploadUrl". It requires you to pass it a URL returned to you by .generateUploadUrl(...).execute(). See documentation:
sourceUploadUrl -> string
The Google Cloud Storage signed URL used for source uploading,
generated by [google.cloud.functions.v1.GenerateUploadUrl][]
But before passing it you need to upload a zip file to this URL:
curl -X PUT "${URL}" -H 'content-type:application/zip' -H 'x-goog-content-length-range: 0,104857600' -T test.zip
or in python:
headers = {
'content-type':'application/zip',
'x-goog-content-length-range':'0,104857600'
}
print(requests.put(upload_url, headers=headers, data=data))
This is the trickiest part:
the case matters and it should be lowercase. Because the signature is calculated from a hash (here)
you need 'content-type':'application/zip'. I deduced this one logically, because documentation doesn't mention it. (here)
x-goog-content-length-range: min,max is obligatory for all PUT requests for cloud storage and is assumed implicitly in this case. More on it here
104857600, the max in previous entry, is a magical number which I didn't found mentioned anywhere.
where data is a FileLikeObject.
I also assume that you want to use the httpsTrigger. For a cloud function you can only choose one trigger field. Here it's said that trigger is a Union field. For httpsTrigger however that you can just leave it to be an empty dictionary, as its content do not affect the outcome. As of now.
request_body = {
"name": parent + '/functions/' + name,
"entryPoint": entry_point,
"sourceUploadUrl": upload_url,
"httpsTrigger": {}
}
You can safely use 'v1' instead of 'v1beta2' for .create().
Here is a full working example. It would be to complicated if I presented it to you as part of your code, but you can easily integrate it.
import pprint
import zipfile
import requests
from tempfile import TemporaryFile
from googleapiclient import discovery
project_id = 'your_project_id'
region = 'us-central1'
parent = 'projects/{}/locations/{}'.format(project_id, region)
print(parent)
name = 'ExampleFunctionFibonacci'
entry_point = "fibonacci"
service = discovery.build('cloudfunctions', 'v1')
CloudFunctionsAPI = service.projects().locations().functions()
upload_url = CloudFunctionsAPI.generateUploadUrl(parent=parent, body={}).execute()['uploadUrl']
print(upload_url)
payload = """/**
* Responds to any HTTP request that can provide a "message" field in the body.
*
* #param {Object} req Cloud Function request context.
* #param {Object} res Cloud Function response context.
*/
exports.""" + entry_point + """= function """ + entry_point + """ (req, res) {
if (req.body.message === undefined) {
// This is an error case, as "message" is required
res.status(400).send('No message defined!');
} else {
// Everything is ok
console.log(req.body.message);
res.status(200).end();
}
};"""
with TemporaryFile() as data:
with zipfile.ZipFile(data, 'w', zipfile.ZIP_DEFLATED) as archive:
archive.writestr('function.js', payload)
data.seek(0)
headers = {
'content-type':'application/zip',
'x-goog-content-length-range':'0,104857600'
}
print(requests.put(upload_url, headers=headers, data=data))
# Prepare Request Body
# https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions#resource-cloudfunction
request_body = {
"name": parent + '/functions/' + name,
"entryPoint": entry_point,
"sourceUploadUrl": upload_url,
"httpsTrigger": {},
"runtime": 'nodejs8'
}
print('https://{}-{}.cloudfunctions.net/{}'.format(region,project_id,name))
response = CloudFunctionsAPI.create(location=parent, body=request_body).execute()
pprint.pprint(response)
Open and upload a zip file like following:
file_name = os.path.join(IGui.settings.BASE_DIR, 'media/archives/', func_obj.sourceFile.name)
headers = {
'content-type': 'application/zip',
'x-goog-content-length-range': '0,104857600'
}
with open(file_name, 'rb') as data:
print(requests.put(upload_url, headers=headers, data=data))
I try to obtain list of friends and actually CAN'T use any api, like twitter and OAuth (it's studying task actually)
I successfully do request_token and access_token. But after it i try to get friends/list.json and get 401 (32 we couldn't authorize you)
def get_friends(self):
address = "https://api.twitter.com/1.1/friends/list.json?" + self.user_id
params = {
'oauth_token': self.token,
'oauth_timestamp': int(time.time()),
'oauth_nonce': self.get_nonce(),
'oauth_signature_method': 'HMAC-SHA1',
'oauth_version': '1.0',
'oauth_consumer_key': self.consumer_key
}
params['oauth_signature'] = self.get_sign(address, params, 'GET')
http_request = Request(address)
http_request.add_header("Authorization", self.get_header(params))
try:
received = (urlopen(http_request,
bytes('', 'ascii')).read())
except Exception as e:
print(e.read())
def get_sign(self, address, params, method):
sorted_params = sorted(params.items())
params_string = ''
for param in sorted_params:
params_string += '{}={}&'.format(param[0], param[1])
params_string = quote(params_string[:-1], '')
string = method + '&' + quote(address, '') + '&' + params_string
raw = string.encode()
decoder = (self.cons_secret + '&').encode()
hashed = hmac.new(decoder, raw, sha1)
sign = quote(str(b64encode(hashed.digest()))[2:-1])
return sign
Verify your OAuth credentials and sometimes even if everything is correct you will get some errors like 'Peer not authenticated' or 'Unauthorised access'. This is because calls to that api version will have endpoints.