i use requests to login to a website and keep session active
def test():
s = requests.session()
but how can use the variable "s" in another function and keep it alive to perform other post on the current session ? Because the variable is private to the function. I'm tempted to make it global but i read everywhere that it's not a good practice. I'm new to Python and i want to code clean.
You'll need to either return it from the function or pass it in to the function in the first place.
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/')
A better pattern is for a more 'top-level' function to be responsible for creating the session and then having sub functions use that 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
EDIT In python a function can actually have multiple return values:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With