[英]python-requests keep session between function
i use requests to login to a website and keep session active 我使用请求登录网站并保持会话活动
def test():
s = requests.session()
but how can use the variable "s" in another function and keep it alive to perform other post on the current session ? 但是如何在另一个函数中使用变量“ s”并使它保持活动状态以在当前会话上执行其他发布呢? Because the variable is private to the function.
因为变量是函数专有的。 I'm tempted to make it global but i read everywhere that it's not a good practice.
我很想让它全球化,但我到处都读到这不是一个好习惯。 I'm new to Python and i want to code clean.
我是Python的新手,我想编写干净的代码。
You'll need to either return it from the function or pass it in to the function in the first place. 您需要从函数返回它,或者首先将其传递给函数。
def do_something_remote():
s = requests.session()
blah = s.get('http://www.example.com/')
return s
def other_function():
s = do_something_remote()
something_else_with_same_session = s.get('http://www.example.com/')
A better pattern is for a more 'top-level' function to be responsible for creating the session and then having sub functions use that session. 更好的模式是让更多“顶级”功能负责创建会话,然后让子功能使用该会话。
def master():
s = requests.session()
# we're now going to use the session in 3 different function calls
login_to_site(s)
page1 = scrape_page(s, 'page1')
page2 = scrape_page(s, 'page2')
# once this function ends we either need to pass the session up to the
# calling function or it will be gone forever
def login_to_site(s):
s.post('http://www.example.com/login')
def scrape_page(s, name):
page = s.get('http://www.example.com/secret_page/{}'.format(name))
return page
EDIT In python a function can actually have multiple return values: 编辑在python中,一个函数实际上可以具有多个返回值:
def doing_something():
s = requests.session()
# something here.....
# notice we're returning 2 things
return some_result, s
def calling_it():
# there's also a syntax for 'unpacking' the result of calling the function
some_result, s = doing_something()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.