我的目标是通过提供用户 ID 和密码来即时创建持久性 cookie,并使用 session 对象在 POST 请求中使用该 cookie。但下面的代码返回以下异常。
('连接中止。', error(54, '连接被对端重置'))
class CreatePersistentCookie(): """创建此类是为了生成一个持久性 cookie,该 cookie 可以在整个 session 期间进一步用于所有正在执行的服务请求"""
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()
最佳答案
Connection reset by peer 表示您尝试连接的服务器拒绝连接。通常情况下,您的计算机和网站服务器之间会进行握手,但由于某种原因,服务器拒绝连接。我会使用 urllib、requests、mechanize 和 cookielib 模块(其中一些模块仅适用于 Python 2.7)。然后,使用 urllib,您可以附加一个用户客户端 header ,如 Firefox,这将欺骗浏览器接受连接,因为他们会认为您是一个普通的网上冲浪者,而不是机器人。
关于python-2.7 - 请求模块中的 Python 错误 "Connection reset by peer",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39885322/