python请求在函数之间保持会话
我使用请求登录网站并保持会话活动python请求在函数之间保持会话,python,python-requests,Python,Python Requests,我使用请求登录网站并保持会话活动 def test(): s = requests.session() 但是,如何在另一个函数中使用变量“s”,并使其保持活动状态,以便在当前会话中执行其他post?因为变量是函数的私有变量。我很想让它全球化,但我到处都读到这不是一个好的做法。我是Python新手,我希望代码干净。首先需要从函数返回它或将它传递给函数 def do_something_remote(): s = requests.session() blah = s.get('
def test():
s = requests.session()
但是,如何在另一个函数中使用变量“s”,并使其保持活动状态,以便在当前会话中执行其他post?因为变量是函数的私有变量。我很想让它全球化,但我到处都读到这不是一个好的做法。我是Python新手,我希望代码干净。首先需要从函数返回它或将它传递给函数
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/')
更好的模式是让一个更“顶级”的函数负责创建会话,然后让子函数使用该会话
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
在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()
使
test
函数返回变量s
。然后在函数之间传递变量。或者将使用会话对象的函数分组并生成一个类。谢谢!如果我们首先传递函数,我们可以保留它并在另一个地方使用它?如果函数已经返回了一些东西,该怎么办?我在主函数中添加了更多的细节,这样您就可以看到会话在不同的函数中被使用了好几次。如果您在另一个函数中需要它,您可以返回它,或者更高的函数可以创建它并向下传递它。这是一种工作单元模式。有点复杂,但如果您将函数看作一棵树,您会发现一个公共根函数,它将调用需要会话的任何其他函数。这就是应该创建会话的地方。谢谢,我将使用您的主函数示例。使用类、为类声明变量并将其用于该类的方法是否正确?