Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Amazon SNS与Python_Python_Amazon Web Services_Urllib2_Amazon Sns - Fatal编程技术网

Amazon SNS与Python

Amazon SNS与Python,python,amazon-web-services,urllib2,amazon-sns,Python,Amazon Web Services,Urllib2,Amazon Sns,尝试开始使用亚马逊SNS。API是非常简单的REST。我好像挂断了电话的签名部分。API示例为: http://sns.us-east-1.amazonaws.com/ ?Subject=My%20first%20message &TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A698519295917%3AMy-Topic &Message=Hello%20world%21 &Action=Publish &SignatureVer

尝试开始使用亚马逊SNS。API是非常简单的REST。我好像挂断了电话的签名部分。API示例为:

http://sns.us-east-1.amazonaws.com/
?Subject=My%20first%20message
&TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A698519295917%3AMy-Topic
&Message=Hello%20world%21
&Action=Publish
&SignatureVersion=2
&SignatureMethod=HmacSHA256
&Timestamp=2010-03-31T12%3A00%3A00.000Z
&AWSAccessKeyId=AKIAJHS4T6XPF7XIURNA
&Signature=9GZysQ4Jpnz%2BHklqM7VFTvEcjR2LIUtn6jW47054xxE%3D
我一直在跟踪,所以我在尝试:

from time import strftime,gmtime,time
import urllib2
import hmac
import hashlib
import base64
import string

def publichSNSMsg(Subject,TopicArn,Message,AWSAccessKeyId,privatekey):
  #http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/
  amzsnshost = 'sns.us-east-1.amazonaws.com'
  values = {'Subject' : Subject,
            'TopicArn' : TopicArn,
            'Message' :Message,
            'Timestamp' : strftime("%Y-%m-%dT%H:%M:%S.000Z", gmtime(time())),
            'AWSAccessKeyId' : AWSAccessKeyId,
            'Action' : 'Publish',
            'SignatureVersion' : '2',
            'SignatureMethod' : 'HmacSHA256',
            }

  amazquote=lambda v: urllib2.quote(v).replace('%7E','~')
  cannqs=string.join(["%s=%s"%(amazquote(key),amazquote(values[key])) for key in sorted(values.keys(),key=str.lower)],'&')
  string_to_sign=string.join(["GET",amzsnshost,"/",cannqs],'\n')

  sig=base64.encodestring(hmac.new(privatekey,string_to_sign,hashlib.sha1).digest())
  querystring = "%s&Signature=%s"%(cannqs,amazquote(sig))
  url="http://%s/?%s"%(amzsnshost,querystring)

  try:
    return urllib2.urlopen(url).read()
  except urllib2.HTTPError, exception:
    return "Error %s (%s):\n%s"%(exception.code,exception.msg,exception.read())
回到这里:

<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/"> 
  <Error> 
    <Type>Sender</Type> 
    <Code>SignatureDoesNotMatch</Code> 
    <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message> 
  </Error> 
  <RequestId>8d6e5a41-dafb-11df-ac33-f981dc4e6c50</RequestId> 
</ErrorResponse> 
有什么想法吗?

噢,很简单

查询字符串中的键应该是字节顺序排序的,而不是不区分大小写的排序(对于版本1签名)


上有稍微更新(现在是正确的)代码。

我发现这个示例非常有用,所以我用C#重新编写了它。由于AWS没有用于SNS的WP7库,这可能会对某些人有所帮助:

我建议您将boto3用于SNS。有关文件可在以下网址找到:。以下代码片段可用于获取JSON签名

import boto3
from django.views.decorators.csrf import csrf_exempt
topic_arn = <your topic>
client = boto3.client('sns',region_name="us-west-2")

#Call this to publish
def sns_publish(arg1,arg2):
    response = client.publish(
                        TopicArn=topic_arn,
                        Message=arg2,
                        Subject=arg2
                    )

#Function to subscribe to topic
@csrf_exempt
def sns_parse(request):
    print request.body.decode('utf-8')
    if request.method == "POST":
        response = json.loads(request.body.decode('utf-8'))
        type = response.get('Type')
        if type == 'Subscription':
            print(type)
            return("Subscription URL: "+<Url obtained>)
        elif type == 'Notification':
            return HttpResponse(type.get('Signature'))
    else:
        return HttpResponse('Not a POST object')
导入boto3
从django.views.decorators.csrf导入csrf_豁免
主题=
客户=两个客户(“sns”,地区名称=“us-west-2”)
#称此为发布
def sns_发布(arg1、arg2):
响应=client.publish(
TopicArn=主题,
消息=arg2,
主题=arg2
)
#订阅主题的函数
@豁免
def sns_解析(请求):
打印请求.正文.解码('utf-8')
如果request.method==“POST”:
response=json.load(request.body.decode('utf-8'))
type=response.get('type')
如果类型==“订阅”:
打印(打印)
返回(“订阅URL:+)
elif类型==“通知”:
返回HttpResponse(type.get('Signature'))
其他:
返回HttpResponse('不是POST对象')

虽然这只是一个模板代码,但是的,bot3确实很有用。

还有一个非常完整的python AWS库,名为。