python-requests保持函数之间的会话

The*_*hun 2 python python-requests

我使用请求登录网站并保持会话活动

def test():

s = requests.session()
Run Code Online (Sandbox Code Playgroud)

但是如何在另一个函数中使用变量“ s”并保持活动状态以在当前会话上执行其他发布呢?因为变量是函数专有的。我很想让它全球化,但我到处都读到这不是一个好习惯。我是Python的新手,我想编写干净的代码。

Aid*_*ane 5

您需要从函数返回它,或者首先将其传递给函数。

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/')
Run Code Online (Sandbox Code Playgroud)

更好的模式是让更多“顶级”功能负责创建会话,然后让子功能使用该会话。

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
Run Code Online (Sandbox Code Playgroud)

编辑在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()
Run Code Online (Sandbox Code Playgroud)