python 连接已中止:发送POST时,在大约5分钟无活动后,RemoteDisconnected(“远程端关闭连接,无响应”)

new9mtju  于 2023-10-15  发布在  Python
关注(0)|答案(3)|浏览(177)

我将空闲超时设置为60分钟。然而,在Python客户端与Python服务器进行对话的测试中,当发送POST时,对等端在大约5分钟的不活动状态下重置连接。即使在重置或断开连接后,活动仍在服务器端发生。

import requests
import logging
import flask
from flask import Flask

app = Flask(__name__)
logging.basicConfig(level=logging.INFO, format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')

@app.before_first_request
def before_first_request():
    app.logger.info("before_first_request")

@app.before_request
def before_request():
    app.logger.info("before_request")

@app.route('/run', methods=['POST'])
def run(redirect_url="",additional_testng_parameters=""):
    url = "http://192.168.1.8:7070/" + "run"
    app.logger.info("url is:" + url)
   
    session = requests.Session()   
    app.logger.info("Request placed for " + url)
    response = "Text"
    try:
        response = session.post(url=url, timeout=3600)
        resultdata = response.headers['Content-Type']
        app.logger.info("Response received for : " + url + " is:" + str(response.status_code))
        app.logger.info("Response received for : " + url + " is:" + str(resultdata))
        response = make_response("Execution is successful")
    except Exception as err:
        app.logger.error(err)
    return response

@app.errorhandler(Exception)
def server_error(err):
    app.logger.exception(err)
    return "There is some error on Test Invoker side", 500

if __name__ == '__main__':
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)

大约5分钟后,收到以下错误消息

ERROR app waitress-0 : ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

下面是一些参考资料,但它并没有解决我的问题
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))
https://www.pythonfixing.com/2022/01/fixed-aborted-remotedisconnected-end.html

rkkpypqq

rkkpypqq1#

试试这个:

import socket
from urllib3.connection import HTTPConnection

HTTPConnection.default_socket_options = (
    HTTPConnection.default_socket_options + [
        (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
        (socket.SOL_TCP, socket.TCP_KEEPIDLE, 45),
        (socket.SOL_TCP, socket.TCP_KEEPINTVL, 10),
        (socket.SOL_TCP, socket.TCP_KEEPCNT, 6)
    ]
)
yhqotfr8

yhqotfr82#

我在使用Gunicorn server for fastapi时遇到了这个错误。我通过将'--timeout'设置为大于30的值来解决这个问题。

deikduxw

deikduxw3#

我发现Voidy的解决方案工作,但修改如下:

class KeepAliveTransport(sentry_sdk.HttpTransport):

    def _get_pool_options(self, ca_certs):
        opts = super()._get_pool_options(ca_certs)
        opts["socket_options"] = urllib3.connection.HTTPConnection.default_socket_options + [
            (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
            (socket.SOL_TCP, socket.TCP_KEEPIDLE, 45),
            (socket.SOL_TCP, socket.TCP_KEEPINTVL, 10),
            (socket.SOL_TCP, socket.TCP_KEEPCNT, 6),
        ]
        return opts

sentry_sdk.init(transport=KeepAliveTransport)

相关问题