使用后关闭会话

时间:2018-03-12 12:09:45

标签: python python-3.x python-requests

如何关闭在Python中创建的s=requests.session()会话请求。我需要在调用每个API后清除变量。

应该清除变量,因为我正在尝试使用会话测试API的应用程序。

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()

1 个答案:

答案 0 :(得分:1)

我建议使用with块打开会话对象:

import requests

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

或者,您必须通过以下方式将'keep_alive'会话选项设置为False

import requests

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

或直接在会话声明中:

import requests

s = requests.session(config={'keep_alive': False})