我需要在Tornado服务器中为Dialogflow创建一个webhook。我以前使用烧瓶完成过此操作。我都是他们的初学者。烧瓶代码烧瓶webhook代码:
from flask import render_template
import os
from flask import Flask
from flask import request
from flask import make_response
import json
import time
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route('/webhook', methods=['POST', 'GET'])
def webhook():
req = request.get_json(silent=True, force=True)
print(json.dumps(req, indent=4))
res = makeWebhookResult(req)
res = json.dumps(res, indent=4)
print("+++++++++++++++RESPONSE+++++++++++++++++", res)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
# Right now I'm just printing a response to see if it works properly
def makeWebhookResult(req):
queryResult = req.get('queryResult').get("queryText")
speech = queryResult
return {
"fulfillmentText": 'YOLO',
"source": 'App'
}
#./ngrok http 8090
if __name__ == '__main__':
port = int(os.getenv('PORT', 8090))
print("Starting app on port %d" % (port))
app.run(debug=True, port=port, host='localhost')
现在我像这样在龙卷风中尝试了这个:
import tornado.ioloop
import tornado.web as web
import tornado
import json
import os
static_root = os.path.join(os.path.dirname(__file__), 'static')
class MainHandler(tornado.web.RequestHandler):
def get(self):
template = "./templates/index.html"
self.render(template)
class Webhook(tornado.web.RequestHandler):
def prepare(self):
if self.request.headers.get("Content-Type", "").startswith("application/json"):
self.req = json.loads(self.request.body)
print(self.req)
print(json.dumps(self.req, indent=4))
response = self.webhook_result(self.req)
response = json.dumps(response, indent=4)
response.headers['Content-Type'] = 'application/json'
return response
def webhook_result(self, *args):
queryResult = self.req.get('queryResult').get("queryText")
speech = queryResult
print(speech)
return {
"fulfillmentText": 'YOLO',
"source": 'App'
}
handlers = [
(r'/', MainHandler),
(r'(.*)', web.StaticFileHandler, {'path': static_root}),
(r'/webhook', Webhook,)
]
settings = dict(
debug=True,
static_path=static_root
)
application = web.Application(handlers, **settings)
if __name__ == "__main__":
port = 8090
application.listen(port)
print(f"Server running on port : {port}")
tornado.ioloop.IOLoop.instance().start()
与Flask配合使用时效果很好。当我尝试通过龙卷风运行(使用ngrok进行隧道传输)时,我得到了WARNING:tornado.access:405 POST / webhook(127.0.0.1)0.83ms
我阅读了龙卷风的文档,但似乎仍然无法弄清楚该如何处理。我假设问题出在Webhook类中。我在这里错了吗?
警告显示POST
请求存在问题-要处理POST
请求,您需要类def post()
中的方法Webhook
可能应该是post()
,而不是prepare()
(这是不同的意思。)。
class Webhook(tornado.web.RequestHandler):
def post(self):
if self.request.headers.get("Content-Type", "").startswith("application/json"):
self.req = json.loads(self.request.body)
print(self.req)
print(json.dumps(self.req, indent=4))
response = self.webhook_result(self.req)
response = json.dumps(response, indent=4)
response.headers['Content-Type'] = 'application/json'
return response
else:
self.write("Wrong Content-Type")
顺便说一句。如果将值发送到webhook_result()
,则应将此值作为req
并使用它代替self.req
def webhook_result(self, req):
queryResult = req.get('queryResult').get("queryText")
speech = queryResult
print(speech)
return {
"fulfillmentText": 'YOLO',
"source": 'App'
}
进口龙卷风导入tornado.web导入json导入操作系统
static_root = os.path.join(os.path.dirname('。'),'static')
Class MainHandler(tornado.web.RequestHandler):
def get(self):
#self.render("./templates/index.html")
# to test POST request but with wrong Content-Type
self.write('''<form action="/webhook" method="POST"><button>SUBMIT</button></form>''')
Webhook类(tornado.web.RequestHandler):
def post(self):
if self.request.headers.get("Content-Type", "").startswith("application/json"):
self.req = json.loads(self.request.body)
print('self.req:', self.req)
print('json.dumps:', json.dumps(self.req, indent=4))
data = self.webhook_result(self.req) # get as normal dict, not string
self.write(data) # it will send as JSON
else:
self.write({'error': 'Wrong Content-Type'}) # it will send as JSON
def webhook_result(self, req):
speech = req.get('queryResult').get("queryText")
print('speech:', speech)
return {
"fulfillmentText": 'YOLO',
"source": 'App'
}
处理程序= [ (r'/',MainHandler), (r'/ webhook',Webhook), #最后 #(r'(。*)',web.StaticFileHandler,{'path':static_root}),]
settings = dict( debug = True, static_path = static_root)
应用程序= tornado.web.Application(处理程序,**设置)如果name ==“ main”: 端口= 8090 application.listen(port) print(f“运行中:http://127.0.0.1:{端口}”) tornado.ioloop.IOLoop.instance()。start()