Python 连接错误:连接尝试失败,因为连接方在一段时间后没有正确响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26700211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:53:40  来源:igfitidea点击:

Connection Error: A connection attempt failed because the connected party did not properly respond after a period of time

pythonflaskruntime-errorsteam-web-api

提问by Vishwa Iyer

I'm developing some software in python that utilizes Steam APIs. I'm using Flask to run and test the python code. Everything was going swell, but now I'm getting this error (I haven't changed any code):

我正在用 Python 开发一些使用 Steam API 的软件。我正在使用 Flask 来运行和测试 python 代码。一切都很顺利,但现在我收到了这个错误(我没有更改任何代码):

('Connection aborted.', error(10060, 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

('Connection aborted.', error(10060, '连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机未能响应'))

I have no idea why this error is coming up, because the code was working perfectly fine and suddenly the error comes up, and I haven't changed anything in the code or with my computer or Flask.

我不知道为什么会出现这个错误,因为代码运行得很好,但突然出现错误,而且我没有更改代码或计算机或 Flask 中的任何内容。

The code:

编码:

import urllib
import itertools
import urllib2
import time
from datetime import datetime
from bs4 import BeautifulSoup
from flask import Flask
import requests
import json
import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString
import sys


app = Flask(__name__)
API_KEY = 'XXX'
API_BASEURL = 'http://api.steampowered.com/'
API_GET_FRIENDS = API_BASEURL + 'ISteamUser/GetFriendList/v0001/?key='+API_KEY+'&steamid='
API_GET_SUMMARIES = API_BASEURL + 'ISteamUser/GetPlayerSummaries/v0002/?key='+API_KEY+'&steamids='
PROFILE_URL = 'http://steamcommunity.com/profiles/'
steamIDs = []
myFriends = []

class steamUser:
    def __init__(self, name, steamid, isPhisher):
        self.name = name
        self.steamid = steamid
        self.isPhisher = isPhisher

    def setPhisherStatus(self, phisher):
        self.isPhisher = phisher

@app.route('/DeterminePhisher/<steamid>')
def getFriendList(steamid):
    try:
        r = requests.get(API_GET_FRIENDS+steamid)
        data = r.json()
        for friend in data['friendslist']['friends']:
            steamIDs.append(friend['steamid'])
        return isPhisher(steamIDs)
    except requests.exceptions.ConnectionError as e:
        return str(e.message)

def isPhisher(ids):
    phisherusers = ''
    for l in chunksiter(ids, 50):
        sids = ','.join(map(str, l))
        try:
            r = requests.get(API_GET_SUMMARIES+sids)
            data = r.json();
            for i in range(len(data['response']['players'])):
                steamFriend = data['response']['players'][i]
                n = steamUser(steamFriend['personaname'], steamFriend['steamid'], False)
                if steamFriend['communityvisibilitystate'] and not steamFriend['personastate']:
                    url =  PROFILE_URL+steamFriend['steamid']+'?xml=1'
                    dat = requests.get(url)
                    if 'profilestate' not in steamFriend:
                        n.setPhisherStatus(True);
                        phisherusers = (phisherusers + ('%s is a phisher' % n.name) + ', ')
                    if parseString(dat.text.encode('utf8')).getElementsByTagName('privacyState'):
                        privacy = str(parseString(dat.text.encode('utf-8')).getElementsByTagName('privacyState')[0].firstChild.wholeText)
                        if (privacy == 'private'):
                            n.setPhisherStatus(True)
                            phisherusers = (phisherusers + ('%s is a phisher' % n.name) + ', ')
                elif 'profilestate' not in steamFriend:
                    n.setPhisherStatus(True);
                    phisherusers = (phisherusers + ('%s is a phisher' % n.name) + ', ')
                else:
                    steamprofile = BeautifulSoup(urllib.urlopen(PROFILE_URL+steamFriend['steamid']).read())
                    for row in steamprofile('div', {'class': 'commentthread_comment  '}):
                        comment = row.find_all('div', 'commentthread_comment_text')[0].get_text().lower()
                        if ('phisher' in comment) or ('scammer' in comment):
                            n.setPhisherStatus(True)
                            phisherusers = (phisherusers + ('%s is a phisher' % n.name) + ', ')
                myFriends.append(n);
        except requests.exceptions.ConnectionError as e:
            return str(e.message)
        except:
            return "Unexpected error:", sys.exc_info()[0]
    return phisherusers

def chunksiter(l, chunks):
    i,j,n = 0,0,0
    rl = []
    while n < len(l)/chunks:        
        rl.append(l[i:j+chunks])        
        i+=chunks
        j+=j+chunks        
        n+=1
    return iter(rl)

app.run(debug=True)

I would like to have an explanation of what the error means, and why this is happening. Thanks in advance. I really appreciate the help.

我想解释一下错误的含义,以及为什么会发生这种情况。提前致谢。我真的很感谢你的帮助。

采纳答案by Harsh Daftary

Well, this is not the flask error, Its basically python socket error

嗯,这不是烧瓶错误,它基本上是 python 套接字错误

as 10060 seems to be a timeout error, is it possible the server is very slow in accepting and if the website opens in your browser,then there is possibility your browser has higher timeout threshold?

由于 10060 似乎是超时错误,是否有可能服务器接受速度很慢,如果网站在您的浏览器中打开,那么您的浏览器是否有可能具有更高的超时阈值?

try increasing request time in request.get()

尝试在 request.get() 中增加请求时间

if the remote server is also under your access then : You don't need to bind the socket (unless the remote server has an expectation of incoming socket) - it is extremely rare that this would actually be a requirement to connect.

如果远程服务器也在您的访问范围内,则:您不需要绑定套接字(除非远程服务器期望传入套接字) - 这实际上是连接的要求是非常罕见的。

回答by gkiwi

I think this because steamcommunity's server unstable or some internet problem..

我认为这是因为蒸汽社区的服务器不稳定或一些互联网问题..

Usually,you can't fix the net shake.But there're still some methods can help u.

通常,您无法修复网络抖动。但仍有一些方法可以帮助您。

First,when you catch the net error,you let your thread sleep one seconds and then try again!

首先,当你捕捉到网络错误时,你让你的线程休眠一秒钟,然后再试一次!

Second,I suggest u use Flask-Cache for this, such as cached 60 seconds,this will help u reduce http request.

其次,我建议您为此使用 Flask-Cache,例如缓存 60 秒,这将帮助您减少 http 请求。

回答by drizin

In my experience, those "connected party did not responde after a period of time", specially when the same code used to work before, are usually related to MTU sizes. Usually you should just determine the maximum MTU size(don't forget to add 28 bytes as explained in the link) and then you can change the MTU sizein your client computer.

以我的经验,那些“连接方在一段时间后没有响应”,特别是当以前使用相同的代码时,通常与MTU大小有关。通常您应该只确定最大 MTU 大小(不要忘记添加 28 个字节,如链接中所述),然后您可以更改客户端计算机中的 MTU 大小