使用 python-requests 模块更新会话中的 Cookie [英] Update Cookies in Session Using python-requests Module
问题描述
我正在使用 python-requests 模块来处理 oAuth 请求和响应.我想在 requests.session.cookies
对象中设置收到的 access_token(响应内容为 dict).
I'm using python-requests module to handle oAuth request and response.
I want to set received access_token (response content as dict) in requests.session.cookies
object.
如何使用从服务器收到的响应更新会话的现有 cookie?
How can I update existing cookies of session with received response from server?
self.session = requests.session(auth=self.auth_params)
resp = self.session.post(url, data=data, headers=self.headers)
content = resp.content
我想做类似的事情:
requests.utils.dict_from_cookiejar(self.session.cookies).update(content)
在这里,requests.utils.dict_from_cookiejar(self.session.cookies)
返回带有一个会话密钥的 dict.现在,我想更新 self.session.cookies
中收到的响应内容.
Here, requests.utils.dict_from_cookiejar(self.session.cookies)
returns dict with one session key. Now, I want to update received response content in self.session.cookies
.
推荐答案
这段代码对我有用.希望能帮到别人.
This code worked for me. hope it can help to someone else.
我想用从发布请求收到的响应值更新 session.cookies 变量.因此,可以在另一个 post/get 请求中使用相同的请求值.
I want to update session.cookies variable with received response values from post request. so, same request value can be used in another post/get request.
在这里,我做了什么:
1) 更新请求模块到 1.0.3 版本.
1) updated requests module to 1.0.3 version.
2) 创建了 2 个函数
2) created 2 functions
session = requests.session()
def set_SC(cookie_val):
for k,v in cookie_dict.iteritems():
if not isinstance(v, str):
cookie_dict[k] = str(v)
requests.utils.add_dict_to_cookiejar(session.cookies,
cookie_val)
def get_SC():
return requests.utils.dict_from_cookiejar(session.cookies)
In another function:
setSC(response.content)
这篇关于使用 python-requests 模块更新会话中的 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!