title: Elegant way to handle when requests session has expired
body: <p>I'm quite new to development and I use python to interact with a lot of various API's, typically through the requests module. All API's require a login call which returns a session key to be used for the following calls. Psudo-example:</p>
  
  <pre><code>req = session.post(https://someloginurl.com, data, headers)    
  print req.content
  
  sessionid=12345
  </code></pre>
  
  <p>Some of the API's like to expire my session arbitrarily, maybe 4 minutes, maybe 15, maybe not for the whole script. The response from all of them are different:</p>
  
  <pre><code>req = session.get(url)
  print req.content
  
  {result : failed, 'your session has expired'}
  </code></pre>
  
  <p>or maybe:</p>
  
  <pre><code>req = session.get(url)
  print req.content
  
  &lt;xml&gt;&lt;result&gt;your session has expired&lt;/result&lt;/xml&gt;
  </code></pre>
  
  <p>It seems I can't check whether my session has expired until after I've had a failed get request, I would like to then re-login and run the request again. </p>
  
  <p>Is there a better way than the following for every single request I make?</p>
  
  <pre><code>def success(content):
      if "success" in content:
       return "success"
      else:
          return
  
  session = login()
  while True:   
      req = session.get(url)
      if success(req.content):
          break
      else:
          session = login()
  </code></pre>
  
  <p>or do I make the request a function itself and just pass it params?</p>
  
  <pre><code>def success(content):
      if "success" in content:
       return "success"
      else:
          return
  
  def do_request(url, *args) 
  
      while True:
          if method is "post":
              req = session.post(url, data, headers)
          else:
              req = session.get(url)
          if success(req.content):
              return req.content, session
          else:
              session = login()
  
  session = login()    
  results, session = do request(url, "post", data, headers, session)
  results, session = do request(url, "get", session)  
  </code></pre>
  
  <p>Any advice on a more efficient way to handle this would be greatly appreciated, thanks for taking the time to read!</p>