Tornado上传错误ConnectionResetError

时间:2015-06-28 13:51:10

标签: python upload tornado

我编写了一个测试龙卷风服务器,上传处理程序通过块写入文件。现在我尝试通过请求库将一些文件上传到服务器并获取ConnectionResetError,如果我在没有文件的情况下发出请求,我就不会得到这个。

python 3.4,龙卷风4.1

server.py:

from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler, stream_request_body

@stream_request_body
class UploadHandler(RequestHandler):

    def prepare(self):
        self.file = open('uploaded_file', 'wb')

    def data_received(self, chunk):
        print(len(chunk))
        self.file.write(chunk)

    def post(self, *args, **kwargs):
        self.file.close()
        self.write('UPLOADED')


app = Application([(r'/upload', UploadHandler), ],
                  debug=True)


if __name__ == '__main__':
    app.listen(7777)
    IOLoop.current().start()

这是我得到的:

>>> import requests
>>> resp = requests.post('http://localhost:7777/upload', files={'file': open('book.pdf', 'rb')})

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/dim/env/lib/python3.4/site-packages/requests/api.py", line 109, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/home/dim/env/lib/python3.4/site-packages/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "/home/dim/env/lib/python3.4/site-packages/requests/sessions.py", line 465, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/dim/env/lib/python3.4/site-packages/requests/sessions.py", line 573, in send
    r = adapter.send(request, **kwargs)
  File "/home/dim/env/lib/python3.4/site-packages/requests/adapters.py", line 415, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

>>> resp = requests.post('http://localhost:7777/upload')
>>> resp.status_code
200

我做错了什么?我看过它是服务器错误。 self.prepare()已完成,但self.data_received()和post()不起作用。

1 个答案:

答案 0 :(得分:0)

在您的服务器日志中,您应该会在data_received方法的第一行看到未捕获的异常。在@stream_request_body模式下,self.request.body无效;正文数据仅可通过chunk的{​​{1}}参数获得。

data_received中存在未捕获的异常时,Tornado立即关闭连接,因为大多数客户端在完成上传请求之后才会读取错误响应,因此返回错误页面可能会很昂贵带宽。