简体   繁体   English

尝试通过ifttt将Google Assistant集成到python中以学习和测试一些东西

[英]Trying to integrate google assistant to python via ifttt to learn and test some things

I'm trying to make a listener, to see what I'm posting via ifttt, but I'm getting bad request (400) error. 我正在尝试做一个侦听器,以查看我通过ifttt发布的内容,但我收到了错误的请求(400)错误。 Here is the code: 这是代码:

from flask import Flask, abort, request 
import json

app = Flask(__name__)


@app.route('/foo', methods=['POST']) 
def foo():
    if not request.json:
        abort(400)
    print(request.json)
    return json.dumps(request.json)


if __name__ == '__main__':
    app.run(host='192.168.1.10', port=27015, debug=True)

What am i doing wrong? 我究竟做错了什么?

This sounds like a client side problem. 这听起来像客户端问题。

The client which posts the data needs to set the following header: 发布数据的客户端需要设置以下标头:

'Content-Type': 'application/json'

Otherwise request.json returns None which in your code will trigger the abort(400) . 否则request.json返回None ,这在您的代码中将触发abort(400)

If you can't make the required change on the client, you can use the get_json() method of request , and pass force=True . 如果你不能让客户端上的要求变化,您可以使用get_json()方法request ,并通过force=True If parsing of the actual payload then fails, it will raise a BadRequest exception. 如果解析实际的有效负载失败,它将引发BadRequest异常。

A better way to write this would be: 更好的写法是:

from flask import jsonify, abort

@app.route('/foo', methods=['POST']) 
def foo():
    try:
      output =  request.get_json(force=True)
    except:
        abort(400)
    # output is now a dict of the incoming json payload
    print(output)
    return jsonify(output)

Then test with a valid payload (but no content type header set): 然后使用有效的有效负载(但未设置内容类型标头)进行测试:

$ curl http://localhost:5000/foo -X POST -d '{"one":"two"}'
{
  "one": "two"
}

And an invalid payload: 无效的负载:

$ curl http://localhost:5000/foo -X POST -d '{"one":"two3}'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>

💡 Using flask's jsonify() function on the outgoing data automatically sets the correct content types on the way out. 💡在输出数据上使用flask的jsonify()函数,可以在出站时自动设置正确的内容类型。


Edit , if you're unsure what data's reaching the endpoint, and can only see a 400 response in the console, then maybe try stripping the function back to basics: 编辑 ,如果不确定什么数据到达端点,并且只能在控制台中看到400响应,则可以尝试将函数剥离到基本内容:

@app.route('/foo', methods=['POST']) 
def foo():
    print(request.get_json(force=True))
    return 'works'

Some trial / error testing is probably required here. 这里可能需要进行一些试验/错误测试。 Attempt to submit via your ifttt system as well as the curl commands above. 尝试通过ifttt系统以及上面的curl命令提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM