蟒蛇,请求保留功能
我使用请求登录到网站,并保持会话活跃蟒蛇,请求保留功能
def test():
s = requests.session()
,但如何使用变量“s”的另一个功能,并保持它活着之间的会话上执行的其他职务当前会议?因为变量对函数是私有的。我很想把它变成全球化的,但我到处读到这不是一个好习惯。我是Python的新手,我想编码干净。
您需要从函数中返回它,或者首先将它传递给函数。
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()
谢谢!如果我们首先传递函数,我们可以保留它并在另一个中使用它?如果该功能已经返回一些东西该怎么办? – TheShun 2014-10-11 02:54:04
我已经为主功能添加了更多的细节,所以您可以看到会话在不同的功能中多次使用。如果你需要更高的功能,你可以返回它,或者更高的功能可以创建并传递它。这是一种工作模式。有点复杂,但如果你把你的函数看作一棵树,你会发现一个通用的根函数,它会调用需要会话的其他任何东西。这就是应该创建会话的地方。 – 2014-10-11 03:11:04
谢谢,我将使用您的主函数示例。使用类时是否也是正确的,为类声明变量并使用它认为这个类的方法? – TheShun 2014-10-11 04:42:16
做了'test'函数返回变量's'。然后将这个变量传递给函数。或者分组使用会话对象并创建一个类的函数。 – falsetru 2014-10-11 02:38:49