每次发送请求时杀死/创建新会话?

时间:2018-03-14 23:13:43

标签: python python-3.x

我是python的新手,并且一直在玩请求模块发送和获取请求。但是,我无法弄清楚每次发出POST请求时如何终止或创建新会话。这是我正在使用的功能:

def sendRequestTest():

    try:
        session.headers.update({'x-csrftoken': req.cookies['csrftoken']})
        login_data = {'email': EMAIL, 'password': PASSWD, 'username': USERNAME, 'first_name': NAME}
        login = session.post(SIGNUP_URL, data=login_data, allow_redirects=True)
        session.headers.update({'x-csrftoken': login.cookies['csrftoken']})
        cookies = login.cookies
        login_text = json.loads(login.text)
        print(login_text)
    except:
        print("An connection error has occured.")

我尝试将session.close()添加到函数的末尾,但是出现了缩进错误。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以通过在方法中初始化来确保每次创建新会话。

import requests

def sendRequestTest():
    session = requests.Session()  # this will create a new session

    try:
        session.headers.update({'x-csrftoken': req.cookies['csrftoken']})
        login_data = {'email': EMAIL, 'password': PASSWD, 'username': USERNAME, 'first_name': NAME}
        login = session.post(SIGNUP_URL, data=login_data, allow_redirects=True)
        session.headers.update({'x-csrftoken': login.cookies['csrftoken']})
        cookies = login.cookies
        login_text = json.loads(login.text)
        print(login_text)
    except:
        print("An connection error has occured.")

如果您需要在发送请求之前修改会话,可以将其作为变量传递给sendRequestTest方法并create the session instance using a context manager

import requests

def sendRequestTest(session):
    # ...

def make_fresh_session_request():
    with requests.Session() as session:
        # The session only exists *inside* of this "with" statement.
        # You can perform any setup of the session instance
        # you might need in here...

        sendRequestTest(session)

    # Outside of the "with" block, the session has been closed