簡體   English   中英

使用python調用rest api將數據推送到kinesis

[英]Call rest api to push data to kinesis using python

我是python和aws的新手。我不太知道如何在stackoverflow中提問。

請不要阻止我。

我正在嘗試發送 HTTP Post 請求以將記錄放入 Amazon Kinesis Stream。

我在 kinesis 中創建了一個流 mystream。 我使用方法帖子。

我嘗試了以下鏈接來設置網關 api,它運行良好。

https://docs.aws.amazon.com/kinesis/latest/APIReference/API_CreateStream.html

我正在嘗試使用請求使用 python 代碼來完成它。

但我收到以下提到的錯誤:

以下是我的代碼:

import sys, os, base64, datetime, hashlib, hmac 
import requests # pip install requests

# ************* REQUEST VALUES *************
method = 'POST'
service = 'kinesis'
host = 'kinesis.eu-west-1.amazonaws.com'
region = 'eu-west-1'
endpoint = 'https://kinesis.eu-west-1.amazonaws.com'

content_type = 'application/x-amz-json-1.1'
amz_target = 'Kinesis_20181114.PutRecord'
request_parameters = '{'
request_parameters += '"StreamName": mystream,'
request_parameters += '"Data":  + base64.b64encode(test) + ,'
request_parameters += '"PartitionKey": 1234 '
request_parameters += '}'


# Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4- 
examples.html#signature-v4-examples-python
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key,datestamp,region,service):
kDate = sign(('AWS4' +key ).encode('utf-8'), datestamp)
kRegion = sign(kDate,region)
kService = sign(kRegion,service)
kSigning = sign(kService, 'aws4_request')
return kSigning

# Read AWS access key from env. variables or configuration file. Best 
practice is NOT
# to embed credentials in code.
with open ('C:\\Users\\Connectm\\Desktop\\acesskeyid.txt') as f:
       contents = f.read().split('\n')
       access_key = contents[0]
       secret_key = contents[1]


 if access_key is None or secret_key is None:
 print('No access key is available.')
 sys.exit()

# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope

canonical_uri = '/'

canonical_querystring = ''

canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + 
'\n' + 'x-amz-date:' + amzdate + '\n' + 'x-amz-target:' + amz_target + '\n'

signed_headers = 'content-type;host;x-amz-date;x-amz-target'

payload_hash = hashlib.sha256(request_parameters).hexdigest()

canonical_request = method + '\n' + canonical_uri + '\n' + 
canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + 
'\n' + payload_hash

algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 
'aws4_request'
 string_to_sign = algorithm + '\n' +  amzdate + '\n' +  credential_scope + 
'\n' +  hashlib.sha256(canonical_request).hexdigest()

signing_key = getSignatureKey(secret_key, datestamp, region, service)

 signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), 
hashlib.sha256).hexdigest()

 authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + 
credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 
'Signature=' + signature
print authorization_header;


headers = {'Content-Type':content_type,
       'X-Amz-Date':amzdate,
       'X-Amz-Target':amz_target,
       'Authorization':authorization_header}
 # ************* SEND THE REQUEST *************
print '\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++'
print 'Request URL = ' + endpoint
r = requests.post(endpoint, data=request_parameters, headers=headers)
print '\nRESPONSE++++++++++++++++++++++++++++++++++++'
print 'Response code: %d\n' % r.status_code
print r.text

我收到以下錯誤

AWS4-HMAC-SHA256憑證= AKIAI5C357A6YSKQFXEA / 20181114 / EU-West - 臨近1 /室壁運動/ aws4_request,SignedHeaders =內容類型;主機; X-AMZ-日期; X-amz-目標,簽名= 1d7d463e77beaf86930806812188180db9cc7cff082663ad547f647a9c6d545a

開始請求++++++++++++++++++++++++++++++++++++ 請求 URL = https://kinesis.eu-west-1.amazonaws.com

響應++++++++++++++++++++++++++++++++++++ 響應代碼:400

{"__type":"SerializationException"}

請有人解釋我如何糾正上述錯誤?

代碼連接到流了嗎?數據序列化有問題嗎?

您收到SerializationException的事實意味着您的代碼正在與 kinesis 對話,但您在test提供的數據可能不是有效的 JSON。

那說:

我強烈建議不要自己做請求邏輯的事情,而是使用 AWS 的軟件開發工具包 (SDK),稱為 boto3。

import json

import boto3

kinesis = boto3.client("kinesis")

response = kinesis.put_record(
    StreamName="my-fancy-kinesis-stream",
    Data=json.dumps({
        'example': 'payload',
        'yay': 'data',
        'hello': 'world'
    }),
    PartitionKey="AdjustAsNeeded"
)
print response

這將使用您機器上的憑據(通過實例元數據或 ~/.aws/config)或環境變量實例化 kinesis 客戶端。

然后它需要一個簡單的字典並將其轉儲到數據的 JSON 字符串中。

您可以在此處找到有關分區鍵的很多內容。

另外,請查看boto3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM