Python错误"连接由peer重置"在请求模块中

时间:2016-10-05 23:40:16

标签: python-2.7 python-requests session-cookies

我的目标是通过提供用户ID和动态来即时创建持久性cookie。密码并使用会话对象在POST请求中使用该cookie。但是下面的代码会返回异常。

('连接已中止。',错误(54,'连接由同行重置')

class CreatePersistentCookie():"""创建此类是为了生成一个持久性cookie,可以进一步在会话中使用所有正在执行的服务请求"" ;"

class CreatePersistentCookie():
    """This class is created to generate a persistent cookie that can further be
       used through out session for all the service requests being executed"""

    def __init__(self, headers, data, url, params, authserver):
        self.headers = headers
        self.data = data
        self.url = url
        self.params = params
        self.authserver = authserver

    def generateCookie(self):
        with requests.session() as s:
            reqsessionObj = s.post(self.authserver,params = self.params)
            reqCookie = reqsessionObj.request.headers['Cookie'] # this returns the Cookie i need
            regexObj = re.compile(r'act-uat=\S+') # this is my app specific pattern search that returns the exact cookie text i need.
            matchObj = regexObj.search(reqCookie)
            sessionCookie = matchObj.group()
            self.headers['Cookie'] = sessionCookie # adding Cookie attribute in headers.
            try:
                r = s.post(self.url, data=json.dumps(self.data), headers=self.headers)
                return r.raise_for_status()
            except requests.exceptions.RequestException as err:
                print err

def main():

    # Defining the params variable. This contains authentication details such as user id,password & App id.
    params = {"accountId": "John",
             "accountPassword": "password",
             "appIdKey": "5c9773e36fd6ea7cc2f9f8ffd9da3e3"
            }
    # Defining the authserver variable that contains the host details where authentication happens.
    authserver = 'https://auth-uat.com/authenticate'

    # creating a object cookieObj from class CreatePersistentCookie that returns persistent cookie.
    #print cookies
    headers = {'Content-Type': 'application/json;charset=UTF-8',
                'Host':'service-uat1.com'}

    data = {"appName":"abc","appKey":"abc","type":"jdbc","queryName":"xyz","version":"v1.2","useCache":"false","bindVars":[{"bindVarName":"In_dt","bindVarVal":"2014-05-13"},{"bindVarName":"In_Location","bindVarVal":"USA"}]}
    url = 'https://uat1.com/gsf/abc/derf/abc/services/xyz'

    cookieObj = CreatePersistentCookie(headers, data, url, params, authserver)

    cookieObj.generateCookie()

if __name__ == '__main__':
    main()

3 个答案:

答案 0 :(得分:0)

通过对等方重置连接表示您尝试连接的服务器拒绝连接。通常,您的计算机和网站的服务器之间存在握手,但出于某种原因,服务器拒绝连接。我会使用urllib,requests,mechanize和cookielib模块(其中一些只适用于Python 2.7)。然后,使用urllib你可以附加一个像Firefox这样的用户客户端标题,这将欺骗浏览器接受连接,因为他们会认为你是网上冲浪的普通人,而不是机器人。

答案 1 :(得分:0)

在对我有用的终端中尝试以下命令

pip install requests[security]

答案 2 :(得分:0)

就我而言,它是从Postman那里工作的,而不是从python脚本工作的。重新启动系统即可解决问题。