Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close session after use

How to close the session request created like s=requests.session() in Python. I need to clear my variables after the calling of each API.

The variables should be cleared since i am trying an application for testing API's using sessions.

import json
import requests
import time

s=requests.session()

def Auth():
    client_id='client_id'
    client_secret='client_secret'
    username="username"
    password="password"
    postURL = "url"
    postParams = {
            "username" : username,
            "password" : password,
            "scope" : "home",
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"password"}
    s=requests.session()
    postResponse = s.post(postURL, data=postParams).json()
    #print(postResponse)
    accessToken = postResponse["access_token"]
    print(accessToken)
    return accessToken

def Api(accessToken):
    urlp="url"
    headers = {
        'authorization': "Bearer " + accessToken,
        'content-type': "application/json",
        }
    postParams={
        'bbox':'-130.401465,26.977875,-54.463965,54.824098',
        'years': '2017',
    }
    response = s.get(url, data=postParams, headers=headers)
    print(response.status_code)
    print(response.text)
    s.close()
    response = s.get(url, data=postParams, headers=headers)
    print(response.status_code)
    print(response.text)


def main():
    accessToken=Auth()
    Api(accessToken)

if __name__ == '__main__':
    main()
like image 637
Sanjeev S Avatar asked Mar 12 '18 12:03

Sanjeev S


1 Answers

I would recommend using with block to open session object:

import requests

with requests.session() as s:
    s.get(url)  # do stuff

Alternatively you have to set 'keep_alive' session option to False in this way:

import requests

s = requests.session()
s.config['keep_alive'] = False

or directly in session declaration:

import requests

s = requests.session(config={'keep_alive': False})
like image 68
Federico Rubbi Avatar answered Oct 03 '22 05:10

Federico Rubbi