这不是"为什么我的代码不运行"的问题.它是"我的代码如何/为什么工作"的问题.我希望从这个具体案例中概括一下,了解将来适用于类似情况的广泛规则.
我为此做了一些搜索(谷歌和StackOverflow),但没有看到任何直接回答这个问题的东西.当然,我不完全确定如何最好地提出这个问题,并且可能使用了错误的术语.我欢迎对标题和标签的建议编辑.
我有以下功能(使用请求模块):
def make_session(username,password,login_url):
#The purpose of this function is to create a requests.Session object,
#update the state of the object to have all of the cookies and other
#session data necessary to act as a logged in user at a website, and
#return the session to the calling function.
new_session = requests.Session()
login_page = new_session.get(login_url)
#The function get_login_submit_page takes the previously
#created login_page, extracts the target of the login form
#submit, and returns it as a unicode string.
submit_page_URL = get_login_submit_page_URL(login_page)
payload = {u'session_name': username, u'session_password': password}
new_session.post(submit_page_URL,data=payload,allow_redirects=True)
return new_session
Run Code Online (Sandbox Code Playgroud)
我真正想知道的是我是否如何做这一点很重要:
new_session.post(submit_page_URL,data=payload,allow_redirects=True)
Run Code Online (Sandbox Code Playgroud)
根据请求文档,Session.post方法返回一个Response对象.
但是,此方法还具有更新Session对象的副作用.这是我关心的那些副作用.我没有使用此方法创建的Response对象.
我已经在实践中测试了这段代码,将响应分配给标签,并将其保留如上所示.这两个选项似乎同样适用于我的目的.
我要问的实际问题是:合理地说,我是否分配了一个标签,一旦Session返回到调用函数,我调用Session.post创建的Requests对象就会超出范围,这是否重要我是否指定了标签?
相反,我是否通过不进行分配来节省任何内存/处理时间?如果不这样做,我是否会为自己制造潜在的不可预见的问题?