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

时间:2014-10-11 02:35:05

标签: python python-requests

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

def test():

s = requests.session()

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

1 个答案:

答案 0 :(得分:4)

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

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()