How to send data from to local server - python

I am working on wireless hand gesture bot project. I want to send output of hand gesture to bot.
I created a server on raspberry pi using flask and trying to send data through request module but its showing '405 Method Not Allowed
Method Not Allowed
The method is not allowed for the requested URL.'
On client side
import requests
r = requests.post("http://192.168.43.133/", data={'foo': 'bar'})
# And done.
print(r.text) # displays the result body.
on server side
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello"
if __name__ == "__main__":
app.run(host='0.0.0.0',port=80,debug= True)

Ref: http://flask.pocoo.org/docs/1.0/api/#flask.Flask.route
#app.route("/")
def index():
return "Hello"
The app.route("/") only maps the GET http verb by default. You're trying to do a POST. So it won't work.
Try this:
#app.route("/", methods=['GET', 'POST'])
def index():
return "Hello"

thanks. i have a variable 'fingers' whose value changes . Can u tell how to send value of finger to server.

Related

Twilio & Flask SMS response never being triggered

We are working on a bot that sends and receives SMS with a conditional response system. Using Twilio, we've followed the documentation to give us the below code. Our group has limited experience with both Flask and Twilio and we're not sure which this is a question of, but our incoming_sms() method is never called. The documentation seems to lack a direct calling of this so we assume it's an event triggered on a text coming into our Twilio number, but when we test this nothing is done. Our web hook shows that the message is being picked up (shown below).
Are we missing a step to trigger the incoming_sms() function?
from twilio.rest import Client
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
from twilio import twiml
app = Flask(__name__)
#app.route("/sms", methods=['GET', 'POST'])
def incoming_sms():
body = request.values.get('Body', None)
resp = twiml.Response()
if body == 'Hello':
resp.message("Answer 1")
else:
resp.message("Answer 2")
return str(resp)
app.run(debug=True)
POST method picked up by Webhook:
ToCountry=US
ToState=FL
SmsMessageSid=SM8990a3baba3e88f412c9eed1b1f4ae14
NumMedia=0
ToCity=
FromZip=07960
SmsSid=SM8990a3baba3e88f412c9eed1b1f4ae14
FromState=XX
SmsStatus=received
FromCity=XXXXX
Body=Oh+Jac&FromCountry=US
To=%2B12393091468
ToZip=
NumSegments=1
ReferralNumMedia=0
MessageSid=SM8990a3baba3e88f412c9eed1b1f4ae14
AccountSid=AC87f189511d21d6480cdc84350cbbbb84
From=+1XXXXXXXXX
ApiVersion=2010-04-01

How to trigger a function in a Python REST API

I have a local Flask REST API that runs some queries and return JSON responses. My idea is to send a POST request to the API and trigger a function capable of updating my database.
The inspiration behind this idea is the way we create resources in a public Cloud. Example: let's say we create a Virtual Cloud Network on any public cloud. The cloud architecture has several APIs for each module and the creation of a VCN trigger the creation of NAT Gateways, Route Tables, Security Lists, Subnets and so on through a GET or POST request to each resource type.
So inspired by this architecture, I want to do this in a simplified and local manner. My first guess is to use the multiprocessing library to spawn processes as soon as a request hits the endpoint, but I don't know if this the best way or a good practice. Can anyone give me an idea on how to do this or if I am in the right path.
i dont really understand... but i can try to help you,
the following code is a code that is the same API but you can get different responses, i dont know what are you going to do with so i added my own examples.
from flask import *
app = Flask(__name__)
#app.route('/api/route/1', methods=['POST'])
def api_1():
if request.method == 'POST':
# Some code here
#Eg:
# data = request.get_json()
# print(data)
#return data.thing
#OR
return "Hello from route 1"
#app.route('/api/route/2', methods=['POST'])
def api_2():
if request.method == 'POST':
# Some code here
#Eg:
# data = request.get_json()
# print(data)
#return data.thing
#OR
return "Hello from route 2"
#app.route('/api/route/3', methods=['POST'])
def api_3():
if request.method == 'POST':
# Some code here
#Eg:
# data = request.get_json()
# print(data)
#return data.thing
#OR
return "Hello from route 3"
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000, debug=True)

Dialogflow fulfillment webhook using Azure web app gives error

I have created fulfillment code for Dialogflow with Python Flask and deployed it as Azure Web App. Code is working fine with the url provided by Azure.
But if I use the same url in Dialog Flow's Fulfillment webhook, I get an error saying "Webhook call failed. Error: UNKNOWN."
Here's my simple Python Flask Code which is deployed in Azure as Web App.
from flask import Flask, request, make_response, jsonify
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
#app.route("/webhook")
def webhook():
return jsonify("Webhook Successfull")
if __name__ == "__main__":
app.run()
Webhook url in DialogFlow:
For your python code, there are two issues I think you met. First is that the route in the Flask just set to support the GET in default. So you need to set for the POST request manually. See the details here for the parameters:
By default a rule just listens for GET (and implicitly HEAD). Starting
with Flask 0.6, OPTIONS is implicitly added and handled by the
standard request handling.
Another is that you return the message via the function jsonify. It turns the JSON output into a Response object with the application/json mime-type, but you just give ita string. So the POST response will meet the conflict. This may be the problem you met.
You can change the code like this:
from flask import Flask, request, make_response, jsonify
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def hello():
return "Hello World!"
#app.route("/webhook", methods=["GET", "POST"])
def webhook():
return jsonify(response="Webhook Successfull")
if __name__ == "__main__":
app.run()

Calling Python file in an Ajax Call

So I have established a pretty decent understanding of the simple architecture of an angularjs app, calling $http and posting to a php page, and receiving data back.
What I'm wondering, is how to do the same type of function with python. Is it possible to have python act the same, with self contained script files that accept post data and echo json back?
$username = $_POST['username'];
type variable assignment at the beginning of the script, and:
echo json_encode(response);
type response.
I'm wanting to use Python for some Internal Tools for my company, as it offers better libraries for remotely running powershell scripts (as the tools are all linux hosted) and overall just has libraries that fit my needs. I'm just having a difficult time finding a concise answer to how this could be set up.
---EDIT------
So I set up a quick example using the information below.
the angular:
var app = angular.module("api");
app.controller("MainController", ["$scope","$http",MainController]);
function MainController($scope,$http){
$http.post('/api',{test: "hello"})
.then(function(response){
console.log(response.data);
})
}
The flask:
from flask import Flask, request
import json
app = Flask(__name__)
#app.route('/api', methods=['POST', 'GET'])
def api():
if request.method == 'POST':
request.data
return 'You made it' # Just so I originally could see that the flask page
if __name__ == "__main__":
app.run()
I'm getting a 404 for that URL. If I change the angular to look at 'localhost:5000/api' (where my flask app is running),it gives me the error of "Unsupported URL Type".
I am seeing when I do the first case, it tries to look at http://localhost/api , which is correct! except for the port. Which is why I tried to specify the port.
Any suggestions for a next step?
Use flask.
You could host your app on a flask "server" and return the content you'd like too with a python processing.
http://flask.pocoo.org/
Use the documentation to setup a route where you'll POST your data using jquery or whatever, then on the route you can do your python stuff and return a JSON to your angular app if you need to.
from flask import request
#app.route('/test', methods=['POST', 'GET'])
def test():
if request.method == 'POST':
print request.data['your_field']
return your_json_data

Incoming SMS with Python SMPP

I'm an new to using SMPP. I am not quite sure incoming messages works. I am implementing this in Python 2.7 using smpplib.I was able to connect to the SMPP service and send out SMS using a bind_transmitter.
In the example there is a function call recv_handler, however I don't see it call for anywhere. Here is the function:
def recv_handler(self, **args):
print 'Message received:', args
Any help would be great. Thank you.
Megan from Twilio here.
I know this question is a bit old. But for someone who lands here looking how to deal with incoming SMS you can get started quickly here:
from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def hello_monkey():
resp = twilio.twiml.Response()
resp.message("Hello, Mobile Monkey")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Hope this helps!

Categories