Python 请求和持久会话 [英] Python Requests and persistent sessions

查看:36
本文介绍了Python 请求和持久会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 requests 模块(使用 Python 2.5 的 0.10.0 版).我已经弄清楚如何将数据提交到网站上的登录表单并检索会话密钥,但我看不到在后续请求中使用此会话密钥的明显方法.有人可以填写下面代码中的省略号或建议其他方法吗?

<预><代码>>>>进口请求>>>login_data = {'formPosted':'1', 'login_email':'me@example.com', 'password':'pw'}>>>r = requests.post('https://localhost/login.py', login_data)>>>>>>文本你'你被重定向到<a href="profilePage?_ck=1349394964">这里</a>'>>>r.cookies{'session_id_myapp':'127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'}>>>>>>r2 = requests.get('https://localhost/profile_data.json', ...)

解决方案

您可以使用以下方法轻松创建持久会话:

s = requests.Session()

之后,继续您的请求:

s.post('https://localhost/login.py', login_data)#登录!为将来的请求保存的 cookie.r2 = s.get('https://localhost/profile_data.json', ...)#cookies 自动发送!#dowhatever,s 将保持你的饼干完好无损:)

有关会话的更多信息:https://requests.kennethreitz.org/en/master/user/advanced/#session-objects

I am using the requests module (version 0.10.0 with Python 2.5). I have figured out how to submit data to a login form on a website and retrieve the session key, but I can't see an obvious way to use this session key in subsequent requests. Can someone fill in the ellipsis in the code below or suggest another approach?

>>> import requests
>>> login_data =  {'formPosted':'1', 'login_email':'me@example.com', 'password':'pw'}
>>> r = requests.post('https://localhost/login.py', login_data)
>>> 
>>> r.text
u'You are being redirected <a href="profilePage?_ck=1349394964">here</a>'
>>> r.cookies
{'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'}
>>> 
>>> r2 = requests.get('https://localhost/profile_data.json', ...)

解决方案

You can easily create a persistent session using:

s = requests.Session()

After that, continue with your requests as you would:

s.post('https://localhost/login.py', login_data)
#logged in! cookies saved for future requests.
r2 = s.get('https://localhost/profile_data.json', ...)
#cookies sent automatically!
#do whatever, s will keep your cookies intact :)

For more about sessions: https://requests.kennethreitz.org/en/master/user/advanced/#session-objects

这篇关于Python 请求和持久会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆