Dialogflow fulfillment webhook using Azure web app gives error - python

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()

Related

Flask Web Server not working with SocketIO

POST UPDATE
I tested this same code on a different machine and it worked perfectly so it is probably a problem with some dependencies or something similar.
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/')
def index():
return render_template("index.html")
#socketio.on('test')
def test(message):
print(message)
if __name__ == '__main__':
socketio.run(app,host='0.0.0.0',port=8080,debug=True)
I saw in the documentation that you can run the web and socket server just by using
the SocketIO.run method.
When I execute my app.py it runs the server but I cannot access with my browser to webpage.
I saw somewhere that using async_mode='eventlet' on the SocketIO constructor could help but it threw an error.
ValueError: Invalid async_mode specified

Deploying test flask API in pythonanywhere

I'm trying to deploy example flask API app given in flask document in pythonanywhere.
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
todos = {}
class TodoSimple(Resource):
def get(self, todo_id):
return {todo_id: todos[todo_id]}
def put(self, todo_id):
todos[todo_id] = request.form['data']
return {todo_id: todos[todo_id]}
api.add_resource(TodoSimple, '/<string:todo_id>')
if __name__ == '__main__':
app.run()
When I was testing this app locally in pycharm, I executed app successfully by sending data using
curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT
command in pycharm terminal.
The result I got is
{
"todo1": "Remember the milk"
}
But when I tested the deployment using Postman the result I got is
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again
Parameters used in Query params in Postman are:
key:data
value:"Remember the milk"
The result got when executed the app in locally is the correct result.
What am I doing wrong?
PS:
When using the pythonanywhere I used
http://www.mydomain.pythonanywhere.com
You need to replace http://localhost:5000/ with the url from pythonanywhere, e.g.
http://yourusername.pythonanywhere.com
That is assuming you didn't pay and configure your own domain
Data has to be send in 'Body' tab, not in 'Param' tab.

Flask_dance with Google API; Missing required parameter: refresh_token

I trid to make authorization system with flask_dance and Google.
I was successful in authorize first but after a while, the program caused this error even though I didn't change it at all.
My whole code is here (It's almost the same as the tutorial one though
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_google_blueprint(
client_id="",
client_secret="",
scope=["profile", "email"]
)
app.register_blueprint(blueprint, url_prefix="/login")
#app.route("/")
def index():
if not google.authorized:
return redirect(url_for("google.login"))
resp = google.get("/oauth2/v2/userinfo")
assert resp.ok, resp.text
return "You are {email} on Google".format(email=resp.json()["email"])
if __name__ == "__main__":
app.run()
How can I fix this error?
This problem seems to be the one referenced in this Github issue. The suggested solution is to request offline access:
google_blueprint = make_google_blueprint(
client_id='',
client_secret='',
scope=['profile', 'email'],
offline=True
)

Python flask Dockerized Web application api not return response ERROR:BrokenFilesystemWarning

I am using python 2.7 and flask that returns a complete response to my local setup. Now the application is dockerized the and deployed in Google kubernetes container. This is a sample API of POST method which takes inputs as application/json, currently the internal function able to fetch the data in JSON format but its not return to the client end.
Python part:
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin
import sys
from runmodel import run
reload(sys) # Reload is a hack
sys.setdefaultencoding('UTF8')
app = Flask(__name__, static_url_path='/static')
CORS(app)
#app.route("/modelrun", methods=['POST'])
def modelrun():
"""TO run the model and get data to populate"""
req_data = request.json
res = run(req_data) #another function return the data it will return json format
return jsonify(res)
My current problem is I am not getting the complete response, its return the ValueError: View function did not return a response// Werkzeug Debugger in the web browser.
Here are the logs and Traceback:
labels{
container.googleapis.com/stream: "stderr"
}
BrokenFilesystemWarning)
severity: "ERROR"
textPayload: " BrokenFilesystemWarning)

Using requests module in flask route function

Consider the following minimal working flask app:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "I am /"
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
This happily works. But when I try to make a GET request with the "requests" module from the hello route to the api route - I never get a response in the browser when trying to access http://127.0.0.1:5000/
from flask import Flask
import requests
app = Flask(__name__)
#app.route("/")
def hello():
r = requests.get("http://127.0.0.1:5000/api")
return "I am /" # This never happens :(
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
So my questions are: Why does this happen and how can I fix this?
You are running your WSGI app with the Flask test server, which by default uses a single thread to handle requests. So when your one request thread tries to call back into the same server, it is still busy trying to handle that one request.
You'll need to enable threading:
if __name__ == "__main__":
app.run(threaded=True)
or use a more advanced WSGI server; see Deployment Options.

Categories