gpt4 book ai didi

python-requests 在函数之间保持 session

转载 作者:行者123 更新时间:2023-11-28 21:53:27 25 4
gpt4 key购买 nike

我使用请求登录网站并保持 session 活跃

def test():

s = requests.session()

但是如何在另一个函数中使用变量“s”并使其保持事件状态以在当前 session 中执行其他帖子?因为变量是函数私有(private)的。我很想让它全局化,但我到处都读到这不是一个好习惯。我是 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/')

更好的模式是让更“顶级”的函数负责创建 session ,然后让子函数使用该 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

编辑 在 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()

关于python-requests 在函数之间保持 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26310467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com