Thursday 15 March 2012

python-requests keep session between function -



python-requests keep session between function -

i utilize requests login website , maintain session active

def test(): s = requests.session()

but how can utilize variable "s" in function , maintain live perform other post on current session ? because variable private function. i'm tempted create global read everywhere it's not practice. i'm new python , want code clean.

you'll need either homecoming function or pass in function in first place.

def do_something_remote(): s = requests.session() blah = s.get('http://www.example.com/') homecoming s def other_function(): s = do_something_remote() something_else_with_same_session = s.get('http://www.example.com/')

a improve pattern more 'top-level' function responsible creating session , having sub functions utilize session.

def master(): s = requests.session() # we're going utilize session in 3 different function calls login_to_site(s) page1 = scrape_page(s, 'page1') page2 = scrape_page(s, 'page2') # 1 time function ends either need pass session # calling function or 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)) homecoming page

edit in python function can have multiple homecoming values:

def doing_something(): s = requests.session() # here..... # notice we're returning 2 things homecoming some_result, s def calling_it(): # there's syntax 'unpacking' result of calling function some_result, s = doing_something()

python python-requests

No comments:

Post a Comment