KeyError at /webhook/ 'HTTP_STRIPE_SIGNATURE' - django

Following is my code for webhook with a Django application
#csrf_exempt
def webhook(request):
webhook_secret = STRIPE_WEBHOOK_SECRET
payload = request.body.decode('utf-8')
signature = request.META["HTTP_STRIPE_SIGNATURE"]
try:
event = stripe.Webhook.construct_event(
payload=payload, sig_header=signature, secret=webhook_secret)
data = event['data']
except Exception as e:
return e
event_type = event['type']
data_object = data['object']
if event_type == 'invoice.paid':
webhook_object = data["object"]
stripe_customer_id = webhook_object["customer"]
stripe_sub = stripe.Subscription.retrieve(webhook_object["subscription"])
stripe_price_id = stripe_sub["plan"]["id"]
current_period_end = stripe_sub["current_period_end"]
current_period_end = datetime.datetime.fromtimestamp(current_period_end, tz=None)
pricing = Pricing.objects.get(stripe_price_id=stripe_price_id)
user = User.objects.get(stripe_customer_id=stripe_customer_id)
subscription = Subscription.objects.get(user=user)
subscription.status = stripe_sub["status"]
subscription.stripe_subscription_id = webhook_object["subscription"]
subscription.pricing = pricing
subscription.current_period_end = current_period_end
subscription.save()
if event_type == 'customer.subscription.deleted':
webhook_object = data["object"]
stripe_customer_id = webhook_object["customer"]
stripe_sub = stripe.Subscription.retrieve(webhook_object["id"])
user = User.objects.get(stripe_customer_id=stripe_customer_id)
subscription = Subscription.objects.get(user=user)
subscription.status = stripe_sub["status"]
subscription.save()
return HttpResponse()
and the url is
path('webhook/', webhook, name='webhook')
if I check the path https://example.com/webhook/, I am getting the error
Exception Type: KeyError at /webhook/
Exception Value: 'HTTP_STRIPE_SIGNATURE'
and in strpe account I am getting 500 error

It takes the POST request, whenever you hit the URL then it will show you this error because of the GET request.
run these commands:
$ stripe login
$ stripe listen --forward-to localhost:8000/webhook
you can follow this said by stripe itself.

Related

MultiValueDictKeyError django, views.py error

I'm getting MultiValueDictKeyError while using the POST method with Django.
this is my views.py submit function.
it seems like there is an error with the candidateId field and I don't understand why.
def submit_dept_member_application(request, application_id):
cv = request.FILES['cv']
letter = request.FILES['letter']
candidate_id = request.data['candidateId']
rank_id = request.data['requestedRankId']
application_state = {
'candidate_id': candidate_id,
'rank_id': rank_id,
'cv_filename': cv.name,
'letter_filename': letter.name,
}
creator = Profile.objects.get(user=request.user.id)
department = creator.department
applicant = Profile.objects.get(user=candidate_id)
rank = Rank.objects.get(id=rank_id)
try:
application = Application.objects.get(id=application_id)
# TODO - update application
except Application.DoesNotExist:
application = None
if application is None:
application = Application(creator=creator, applicant=applicant, desired_rank=rank,
application_state=application_state, department=department
)
application.save()
create_application_directory(application.id)
ApplicationStep.objects.update_or_create(
application=application, step_name=Step.STEP_1,
defaults={'can_update': True, 'can_cancel': True, 'currentStep': True}
)
copy_to_application_directory(cv, application.id)
copy_to_application_directory(letter, application.id)
addresee = 'devasap08#gmail.com' # TODO: change email to admin address
email_headline = 'New Application Created'
wanted_action = 'application_created'
sendEmail(addresee, email_headline, wanted_action, creator)
addresee = 'devasap08#gmail.com' # TODO: change email to creator address
email_headline = 'Application Successfully Created'
wanted_action = 'application_received'
sendEmail(addresee, email_headline, wanted_action, applicant)
return Response(application.id, status=status.HTTP_200_OK)
any suggestions on how to solve it?
Thank you!

how to embed the text to link

I am trying to embed the link of the issue id from JIRA.
I want JIRA issue id to be an embedded link to the JIRA.
class ComplainceServer():
def __init__(self, jira_server, username, password, encoding='utf-8'):
if jira_server is None:
error('No server provided.')
#print(jira_server)
self.jira_server = jira_server
self.username = username
self.password = password
self.encoding = encoding
def checkComplaince(self, appid, toAddress):
query = "/rest/api/2/search?jql=issuetype = \"Application Security\" AND \"Prod Due Date\" < now()
request = self._createRequest()
response = request.get(query, contentType='application/json')
# Parse result
if response.status == 200 and action == "warn":
data = Json.loads(response.response)
print "#### Issues found"
issues = {}
msg = "WARNING: The below tickets are non-complaint in fortify, please fix them or raise exception.\n"
issue1 = data['issues'][0]['key']
for item in data['issues']:
issue = item['key']
issues[issue] = item['fields']['summary']
print u"* {0} - {1}".format(self._link(issue), item['fields']['summary'])
print "\n"
data = u" {0} - {1}".format(self._link(issue), item['fields']['summary'])
msg += '\n'+ data
SOCKET_TIMEOUT = 30000 # 30s
email = SimpleEmail()
email.setHostName('smtp.com')
email.setSmtpPort(25)
email.setSocketConnectionTimeout(SOCKET_TIMEOUT);
email.setSocketTimeout(SOCKET_TIMEOUT);
email.setFrom('R#group.com')
for toAddress in toAddress.split(','):
email.addTo(toAddress)
email.setSubject('complaince report')
email.addHeader('X-Priority', '1')
email.setMsg(str(msg))
email.send()
def _createRequest(self):
return HttpRequest(self.jira_server, self.username, self.password)
def _link(self, issue):
return '[{0}]({1}/browse/{0})'.format(issue, self.jira_server['url'])
This is the calling function. APPid and toAddress will be passed in from different UI.
from Complaince import ComplainceServer
jira = ComplainceServer(jiraServer, username, password)
issues = jira.checkComplaince(appid, toAddress)
I want issueid to be an embedded link.
currently the email sends as below:
MT-4353(https://check.com/login/browse/MT-4353) - Site Sc: DM isg_cq5
but i want [MT-4353] as hyperlink to the URL https://check.com/login/browse/MT-4353

Has anyone done a Twitter sentiment analysis using PySpark?

Has anyone done a Twitter sentiment analysis using Apache Spark?I have tried this
class Tweet(dict):
def __init__(self, tweet_in, encoding = 'utf-8'):
super(Tweet, self).__init__(self)
if tweet_in and 'delete' not in tweet_in:
self['id'] = tweet_in['id']
self['geo'] = tweet_in['geo']['coordinates'] if tweet_in['geo'] else None
self['text'] = tweet_in['text'].encode(encoding)
self['user_id'] = tweet_in['user']['id']
self['hashtags'] = [x['text'].encode(encoding) for x in tweet_in['entities']['hashtags']]
self['timestamp'] = dateutil.parser.parse(tweet_in[u'created_at']).replace(tzinfo=None).isoformat()
self['screen_name'] = tweet_in['user']['screen_name'].encode(encoding)
def connect_twitter():
consumer_key = "personal_info"
consumer_secret = "personal_info"
access_token = "personal_info"
access_secret = "personal_info"
auth = twitter.OAuth(token = access_token,
token_secret = access_secret,
consumer_key = consumer_key,
consumer_secret = consumer_secret)
return twitter.TwitterStream(auth=auth)
def get_next_tweet(twitter_stream, i ):
block = False # True
stream = twitter_stream.statuses.sample(block=False)
tweet_in = None
while not tweet_in or 'delete' in tweet_in:
tweet_in = stream.next()
tweet_parsed = Tweet(tweet_in)
return json.dumps(tweet_parsed)
def process_rdd_queue(twitter_stream, nb_tweets = 5):`enter code here`
rddQueue = []
for i in range(nb_tweets):
json_twt = get_next_tweet(twitter_stream, i )
dist_twt = ssc.sparkContext.parallelize([json_twt], 5)
rddQueue += [dist_twt]
lines = ssc.queueStream(rddQueue, oneAtATime=False)
lines.pprint()
enter code here
try : sc.stop()
except : pass
sc = SparkContext(appName="PythonStreamingQueueStream")
ssc = StreamingContext(sc, 1)
twitter_stream = connect_twitter()
process_rdd_queue(twitter_stream)
try : ssc.stop(stopSparkContext=True, stopGraceFully=True)
except : pass
ssc.start()
time.sleep(2)
ssc.stop(stopSparkContext=True, stopGraceFully=True)
Do I need to have a static file where I need positive and negative words for sentiment analysis mechanism.
I am a beginner at this.

django twilio for number phone confirmation returns exception in send function

I got an exception when i create a sms to send
here is my functions
def send_sms(to_number, body):
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
twilio_number = '+15005550006'
client = TwilioRestClient(account_sid, auth_token)
try :
client.messages.create(to=to_number,
from_=twilio_number,
body=body)
except Exception as e:
print e.message
def generate_code():
return str(random.randrange(100000, 999999))
def send_confirmation_code(request,to_number):
verification_code = generate_code()
send_sms(to_number, verification_code)
request.session['verification_code'] = verification_code
return verification_code

Strange response from the mandrill server

I have a django app and I use mandrill for mails sending.
Till recently, I was sending simple mails and it was working great.
But now, I want to send mails with attachments, so I changed my message
construction to this:
def construct_message(self):
content = self.get_content()
attachments = self.kwargs.get('attachments', None)
message = {} if not attachments else MIMEMultipart()
message['subject'] = content['subject']
message['text'] = content['txt']
message['html'] = content['html']
message['from_email'] = self.sender
message['from_name'] = '***'
recipients = self._get_recipients()
if attachments:
message['to'] = ", ".join([r["email"] for r in recipients])
else:
message['to'] = recipients
message['cc'] = []
message['bcc'] = []
if attachments:
for a in attachments:
part = MIMEApplication(open(a,"rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(a))
message.attach(part)
message = message.as_string()
return message
def send_message(self, message):
"""Actually send the message."""
api_key = settings.MANDRILL_API_KEY_INTERNAL if self.is_internal else settings.MANDRILL_API_KEY_EXTERNAL
key_type_str = "internal" if self.is_internal else "external"
logging.debug("Sending mail through %s API key %s" % (key_type_str, api_key))
mandrill_client = mandrill.Mandrill(api_key)
return mandrill_client.messages.send(message=message)
And since then, I get the following response from mandrill API call:
ValidationError: Validation error: {"message":"Please enter an array"}
Do you have an idea, what am I doing wrong?
Thanks, Alex A.