2014-10-11 154 views
1

我使用請求登錄到網站,並保持會話活躍蟒蛇,請求保留功能

def test(): 

s = requests.session() 

,但如何使用變量「s」的另一個功能,並保持它活着之間的會話上執行的其他職務當前會議?因爲變量對函數是私有的。我很想把它變成全球化的,但我到處讀到這不是一個好習慣。我是Python的新手,我想編碼乾淨。

+0

做了'test'函數返回變量's'。然後將這個變量傳遞給函數。或者分組使用會話對象並創建一個類的函數。 – falsetru 2014-10-11 02:38:49

回答

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

謝謝!如果我們首先傳遞函數,我們可以保留它並在另一箇中使用它?如果該功能已經返回一些東西該怎麼辦? – TheShun 2014-10-11 02:54:04

+0

我已經爲主功能添加了更多的細節,所以您可以看到會話在不同的功能中多次使用。如果你需要更高的功能,你可以返回它,或者更高的功能可以創建並傳遞它。這是一種工作模式。有點複雜,但如果你把你的函數看作一棵樹,你會發現一個通用的根函數,它會調用需要會話的其他任何東西。這就是應該創建會話的地方。 – 2014-10-11 03:11:04

+0

謝謝,我將使用您的主函數示例。使用類時是否也是正確的,爲類聲明變量並使用它認爲這個類的方法? – TheShun 2014-10-11 04:42:16