Can't send http request using python, only sends to https - python

I have the request below:
#app.route('/solve', methods=['POST'])
def solve():
if request.method == "POST":
token = request.form.get('g-recaptcha-response', '')
print('Posted Token : ' + token)
Thread(target = tokenremoval, args = [token]).start()
return('Success')
I want to send this post request to http://127.0.0.1:5000/solve , but it seems like it is sending to https://127.0.0.1:5000/solve. When I make the post request it sends it to that link above and i get:
This site can’t provide a secure connection
127.0.0.1 sent an invalid response.
Try running Windows Network Diagnostics.
ERR_SSL_PROTOCOL_ERROR
Why can't i send the post request to the http link?

Related

Always receiving 400:Bad request when Twilio webhook is configured

I want to maintain seperate twilio phone unsubscribers list and this can be done when webhook is configured via twilio console to receive incoming messages. I would parse only those messages when some one types "STOP". I have successfully configured webhook
Now from my phone when i type "STOP" to my twilio number, I am receiving always bad request. My code looks as follows
#app.route('/twilio/unsubscribes_incremental', methods=['POST', 'GET'])
def phone_unsubscribes_incremental():
print("start")
print("The arguments are ", request.args)
payload = request.get_json(force=True)
print("The payload is ", payload)
#resp = MessagingResponse()
if payload.get('Body') in twilio_unsubscribe_list:
stream_data_to_bq(payload)
#resp.message("")
#return str(resp)
return jsonify({"status":"ok"})
My python console shows as follows
My ngrok console shows as follows
My twilio console logs shows as follows
For some reason iam unable to parse request object sent to my webhook. This account is in free trial. Can any one point out to me right documentation to parse incoming messages.
Twilio developer evangelist here.
As Alan points out, Twilio webhook requests send data in the form application/x-www-form-urlencoded, the same format that a web form will post data. It is not JSON. Twilio also expects your application's response to be application/xml.
So, you should read the data from request.form and, since it doesn't look like you are expecting to tell Twilio to do anything further with the request, return an empty <Response> TwiML element.
Something like this should work:
#app.route('/twilio/unsubscribes_incremental', methods=['POST', 'GET'])
def phone_unsubscribes_incremental():
print("start")
print("The arguments are ", request.args)
payload = request.form
print("The payload is ", payload)
if payload.get('Body') in twilio_unsubscribe_list:
stream_data_to_bq(payload)
resp = MessagingResponse()
return str(resp), { 'Content-Type': 'application/xml' }
The webhook is application/x-www-form-urlencoded
Webhook FAQ
For inbound text messages, Twilio will send an HTTP POST request to
your server with a body that uses the
application/x-www-form-urlencoded encoding. View the list of
parameters sent in that request.

How to send data from localhost to server using Python requests?

I am trying to send data from localhost to an API in remote server using Python Requests & Django through an API: /api/send-data/
Path for /api/send-data/ in urls.py is path('send-data/',view_send_data.send_data,name='send_data')
This is my view_send_data.py in my localhost:
#api_view(('POST',))
#renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def send_data():
# defining the API-endpoint
API_ENDPOINT = "http://68.183.89.234/api/screen/"
# data to be sent to API
data = {'data':1234}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
print(r.json())
return Response({"success": True}, status=status.HTTP_200_OK)
Path for api at http://68.183.89.234/api/screen/ in urls.py is path('screen/',views_fr.screen_display,name='screen')
This is my views_fr.py in my remote server:
#api_view(['POST'])
def screen_display(request):
if request.method == 'POST':
return Response({"success": True,
"response": request.data}, status=status.HTTP_200_OK)
When I call "http://127.0.0.1:8000/api/send-data/" in my browser, I am getting 405 Method Not Allowed
Is this the correct way to do it or am I missing something? Thank you.
The error you are getting is because the remote server API only accepts POST method, but you can't make a POST request using the browser url call. Test the API using postman or curl so you can set the correct method for request.

Twilio whatapp bot not responding to keywords

I am trying to build a whatsapp bot on Twilio following the Twilio tutorial.
I have written the flask program to create a test bot:
from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route('/bot', methods=['POST'])
def bot():
incoming_msg = request.values.get('Body', '').lower()
resp = MessagingResponse()
msg = resp.message()
responded = False
if 'quote' in incoming_msg:
# return a quote
r = requests.get('https://api.quotable.io/random')
if r.status_code == 200:
data = r.json()
quote = f'{data["content"]} ({data["author"]})'
else:
quote = 'I could not retrieve a quote at this time, sorry.'
msg.body(quote)
responded = True
if 'cat' in incoming_msg:
# return a cat pic
msg.media('https://cataas.com/cat')
responded = True
if not responded:
msg.body('I only know about famous quotes and cats, sorry!')
return str(resp)
if __name__ == '__main__':
app.run()
The app is running on http://127.0.0.1:5000/
When I click this link this is what I see
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Installed and run ngrok. I pasted the url under forwarding (there are two I copied the first), pasted this url to my Twilio sandbox (when a message comes in URL) and added /bot to the path.
However when I try and type cat on whatsapp (I have added my whatsapp number to my sandbox) I do not get a response (from my understanding I should be getting a picture of a cat if I type the keyword cat).
Not sure what I am doing wrong.
I copied the same code here from the blog here (is this the blog you used), Build a WhatsApp Chatbot With Python, Flask and Twilio, and updated the WhatsApp sandbox When A Message Comes In URL to point to the Ngrok URL which exposes it to the Internet and it works.
Can you check your Twilio Debugger, to see if there were any errors?
You cannot use your web browser to visit the Flask URL, since it is expecting an HTTP POST and your browser is using an HTTP GET. You can use a tool like Postman to do a POST to your URL, and see what response you get.
You should get this response when visit the URL and sending in the Body POST parameter of cat.
You could also check the Ngrok debug URL, http://127.0.0.1:4040/, to see what you are getting from Twilio when you send an inbound WhatsApp sandbox message, and debug from there.

Test GET and POST calls

I need to test POST and GET calls against an NGINX server.
I need to capture the error codes and verify the response. I was able to test the GET requests by hitting localhost:8080 (NGINX is running on docker exposing 8080), but I'm not sure how to test the POST calls.
Can we construct a dummy request and test POST call? NGINX runs with default page.
Below is one way to make a post request to an endpoint in python
import requests
API_ENDPOINT = "http://pastebin.com/api/api_post.php"
data = {param1:value1,
param2:value2}
#sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
#extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)

Splunk Python Connection Lost

I'm using python to execute a splunk search query and return the results. I connect with the following string:
service = client.connect(
host=HOST,
port=PORT,
username=USERNAME,
password=PASSWORD
)
The variables have been tested to work, and it connects to splunk, but sometimes, when I run these lines of code:
print "Installed App Names \n"
for app in service.apps:
print app.name
It returns this error:
Request Failed: Session is not logged in
About 50% of the time, the code works, and it executes. Is this inconsistency in code results do to the service = lines of code not actually connecting to the splunk server? Can these connections time out?
connect can take an autologin=True argument to allow the bindings to try to re-connect when authentication fails, instead of raising that error immediately.
Probably you should get the token and session id of splunk using your python code. Please find the below code if this could help you.
import json,os,sys,requests
BASE_URL = "https://SPLUNKLB / SPLUNK WEB URL"
def getToken():
# body for token request
payload = {'username': "",'password': ""}
TOKEN_URL = "/services/auth/login?output_mode=json"
# post token request
res = requests.post(BASE_URL+TOKEN_URL, data=payload, verify=False)
if (res.status_code == 200):
# Get token out of response
resJson = json.loads(res.content)
return resJson.get('sessionKey')
else:
print res.status_code, res.content

Categories