从 espduino 超时到 Flask

n8h*_*rie 5 python arduino flask

我正在使用esp8266为带有此库的 Arduino 提供 WiFi 。我已将其正确设置为 POST 到Pushover以及requestbin,并且在调试输出和这些工具的接口之间,我可以验证请求数据是否正确发布,并且 esp8266 / arduino 单元的响应状态代码正确显示200。

我想测试设置的可靠性,所以我想我会转向 Flask。我在 for 循环中将 100 个请求从 espduino POST 到在0.0.0.0:5000. POST 包含一个测试字符串(尝试粗略衡量简单的数据完整性,确保字符串通过未损坏的)以及正在发送的循环数(例如,第一个循环中的 0 ... 最后一个循环中的 99) . Flask 会跟踪这些请求并更新其输出以显示哪些请求正确通过,哪些没有通过。

除了一件事之外,设置运行良好:模块在每次请求后超时。每个 POST 似乎都有效,Flask 适当地更新输出,但 espduino 为每个请求花费整整 5 秒(默认超时)并说它得到了响应代码0.

所以重申一下情况:我的 espduino 设置正确 POST 并从 requestb.in 和 pushover.net 获得 200 响应,但使用我的本地 Flask 服务器 POST 然后超时。

为什么

  • 确保Flask 读取所有表单数据-> 没有区别
  • 使用 gunicorn 而不是内置的 Flask 服务器 -> 没有区别
  • 将响应内容类型显式更改为“text/html”-> 没有区别
  • 将响应内容类型更改为“application/json”-> 没有区别
  • 添加; charset=utf-8到内容类型 -> 没有区别
  • 将 Flask api 端点从索引更改//api-> 没有区别
  • 更改端口 -> 没有区别
  • 验证防火墙已关闭(托管 Flask 应用程序的 OS X 10.10.5)-> 没有区别
  • nc -l 5000 并检查来自模块的传入帖子(看起来不错)
  • 从 Postman 发布并 curl 到 Flask 应用程序以检查响应(并与来自 Requestb.in/有效站点的响应进行比较)
  • 从 test_string 中删除了特殊字符
  • 更改WSGIRequestHandler.protocol_versionHTTP/1.1-> 没有区别

我花了几天的时间在这方面工作,但没有取得太大进展。我今天最大的突破是,如果我将我的 gunicorn / Flask 设置放在 nginx 之后,我可以成功发布并获得 200 条回复,而没有对 espduino 代码进行任何更改,所以我确定 Flask 正在或没有做一些事情(我担心这可能是 espduino 对 IP 地址与域名的处理,但我认为这排除了这一点)。

我尝试过的设置摘要:

  • POST 到 requestb.in -> POST 有效,200 响应,无超时
  • POST 到 pushover.net -> POST 有效,200 响应,无超时
  • POST 到本地 Flask 服务器 -> POST 有效,无响应,超时
  • GET 到本地 Flask 服务器 ->无响应,超时(未测试是否 GET 数据)
  • POST 到本地 gunicorn 服务 Flask 应用程序 -> POST 有效,无响应,超时
  • POST 到本地 nginx 服务 gunicorn / Flask -> POST 有效,200 响应,无超时
  • POST 到本地 gunicorn 服务 httpbin ->无响应,超时
  • POST 到本地cherrypy 服务器->无响应,超时

当前代码:

from flask import Flask, request, make_response
from datetime import datetime

app = Flask(__name__)

ESPDUINO_IP = 'XXX.XXX.XXX.XXX'
INCOMING_TEST_STRING = 'This is my espduino test string!'
incoming_requests = []

with open('results.txt', 'w') as f:
    f.write("Test run start: {}\n".format(datetime.now()))

@app.route('/api', methods=['GET', 'POST'])
def count_requests():
    if request.method == 'POST':
        form = request.form
        incoming_ip = request.remote_addr
        if incoming_ip == ESPDUINO_IP and form['test_string'] == INCOMING_TEST_STRING:
            test_num = int(form['test_num'])
            incoming_requests.append(test_num)
            msg = "All is peachy!"
            with open('results.txt', 'a') as f:
                f.write("{:02d}: {}\n".format(test_num, datetime.now()))
    else:
        msg = "Hey, you're not the espduino!<br>"
        msg += str(len(incoming_requests)) + " requests so far.<br>"
        missing = set(range(100)) - set(incoming_requests)
        msg += "Missing: {}<br>".format(', '.join(map(str, missing)) if missing else "None!")
        msg += '<br>'.join(map(str, incoming_requests))

    resp = make_response('{"this": "that"}')
    resp.headers['Content-Type'] = "application/json"
    return resp
    # return "<html><body>{}</body></html>".format(msg)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
Run Code Online (Sandbox Code Playgroud)

这是来自 espduino 的 POST 的样子:

$ nc -l 5000
POST /api HTTP/1.1
Host: XXX.XXX.XXX.XXX
Content-Length: 55
Connection: close
Content-Type: application/x-www-form-urlencoded
User-Agent: ESPDRUINO@tuanpm

test_string=This is my espduino test string!&test_num=0
Run Code Online (Sandbox Code Playgroud)

相比之下curl -X POST -d 'test_string=This is my espduino test string!&test_num=0' localhost:5000/api

$ nc -l 5000
POST /api HTTP/1.1
Host: localhost:5000
User-Agent: curl/7.43.0
Accept: */*
Content-Length: 55
Content-Type: application/x-www-form-urlencoded

test_string=This is my espduino test string!&test_num=0
Run Code Online (Sandbox Code Playgroud)

很想听听关于可能发生的事情的任何想法。我想知道这是否可能是 WSGI 问题?

2015 年 8 月 31 日更新:

我仍然没有弄清楚这一点,但这绝对不是 Flask 特有的问题。正如我上面提到的,我还使用 CherryPy 以及使用python3 -m http.server --bind 0.0.0.0 5000(并将 espduino 代码更改为 GET /)以及ruby -run -e httpd. 我仍然不明白为什么 nginx、requestbin 等可以毫无问题地提供服务。

为了回应@Miguel 关于 HOST 标头没有端口的评论,我正在分叉和构建固件来改变这一点,但与此同时,我将客户端主机和端口硬编码到一个小的 HTTP 服务器脚本中,没有运气。

from http.server import BaseHTTPRequestHandler, HTTPServer

class MyServer(BaseHTTPRequestHandler):
    # protocol_version = 'HTTP/1.1'
    # close_connection = True
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write(b"<html><body><h1>hi!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        self.client_address = ("192.168.0.4", 5000)
        self._set_headers()
        self.wfile.write(b"<html><body><h1>POST!</h1></body></html>")
        # import pdb; pdb.set_trace()

def run(server_class=HTTPServer, handler_class=MyServer, port=5000):
    server_address = ('0.0.0.0', port)
    httpd = server_class(server_address, handler_class)
    print('Starting httpd...')
    httpd.serve_forever()

if __name__ == "__main__":
    run()
Run Code Online (Sandbox Code Playgroud)

查看 tcpdump 以查看是否可以找到工作(nginx)和非工作网络数据之间的任何差异。到目前为止还没有找到任何东西,但我也是这个工具的新手。

2015 年 9 月 8 日更新

仍然没有弄清楚这一点,但看起来 nginx 和 Python 服务器之间的 tcpdump 明显不同。这是一个 POST 和响应示例——为了清楚起见,我用ESPDUINO_IP和替换了 IP OSX_IP,并清理了周围的 ACK 调用等。我需要研究为什么 Python 响应会被那条奇怪的线中断——我检查了 10 多个连续的 POST / Response 对,并且每个Python 响应都像那样被中断(在完全相同的地方),并且没有一个nginx 的回应是,所以我想知道这是否可能是问题所在。(此外,正如您所看到的,在这一轮测试中,我将响应正文更改为文本而不是 JSON——结果没有变化。)

nginx(工作)
POST /api HTTP/1.1
Host: OSX_IP
Content-Length: 29
Connection: close
Content-Type: application/x-www-form-urlencoded; charset=utf-8
User-Agent: espduino@n8henrie

test_string=simple&test_num=0


09:16:04.079291 IP OSX_IP.commplex-main > ESPDUINO_IP.49146: Flags [P.], seq 1:183, ack 211, win 65535, length 182

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 31 Aug 2015 15:16:04 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 26
Connection: close

<html><body></body></html>
Run Code Online (Sandbox Code Playgroud) 烧瓶(超时)
POST /api HTTP/1.1
Host: OSX_IP
Content-Length: 29
Connection: close
Content-Type: application/x-www-form-urlencoded; charset=utf-8
User-Agent: espduino@n8henrie

test_string=simple&test_num=3

09:00:19.424086 IP OSX_IP.commplex-main > ESPDUINO_IP.48931: Flags [P.], seq 1:18, ack 211, win 65535, length 17

HTTP/1.0 200 OK

09:00:36.382125 IP OSX_IP.commplex-main > ESPDUINO_IP.48931: Flags [FP.], seq 18:181, ack 211, win 65535, length 163
E....F@.@..,...e.......#...k..S.P.......Content-Type: text/html; charset=utf-8
Content-Length: 26
Server: Werkzeug/0.10.4 Python/3.4.3
Date: Mon, 31 Aug 2015 15:00:36 GMT

<html><body></body></html>
Run Code Online (Sandbox Code Playgroud)

它看起来对我来说,Python是打破响应成两半出于某种原因,例如一个部分length 17和另一个length 163相比,nginx的的的单个响应length 182

2015 年 9 月 10 日更新

有趣的是,如果我通过 mitmproxy 运行它,一切都按预期运行——甚至直接运行到没有 nginx 或 gunicorn 的 Flask 应用程序。一旦我删除了 mitmproxy,它就会回到上面的超时状态。

n8h*_*rie 1

仍然没有解决问题,但我想我可能已经找出导致问题的原因了。毕竟不是 Flask 的问题。

不幸的是,这似乎是esp_bridge库的一个错误,该库的固件 espduino 在 esp8266 中使用。请原谅可能不正确的术语,但据我所知,由于某种原因,它似乎没有加入 TCP 数据包。生成被分割成单独的 TCP 数据包的 HTTP 响应的服务器(例如 Flask)出现故障,而 tcpdump 可以验证 nginx 和 mitmproxy 是否正在加入分割的 TCP 数据包并在单个数据包中返回响应,这就是它们正常​​工作的原因。

https://github.com/tuanpmt/esp_bridge/issues/10

更新20160128

我今天重新审视了这个问题并找到了解决方法。虽然理想的解决方案是修复esp_bridge以重新组装多数据包响应,但只要响应非常小,就可以强制 Flask 将响应写入单个数据包中。

from werkzeug.serving import WSGIRequestHandler

# Your Flask code here...

if __name__ == "__main__":
    WSGIRequestHandler.wbufsize = -1
    app.run()
Run Code Online (Sandbox Code Playgroud)