Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Requests session() Method



The Python Requests session() method creates a persistent session for making HTTP requests allowing us to reuse parameters like cookies and headers across multiple requests within the same session. This enhances performance by maintaining a connection pool and efficiently handling cookies and authentication.

Additionally, it persists headers and other settings between requests like connection timeouts. By persisting state across requests, requests.session() streamlines web scraping, API interaction and other tasks requiring repeated HTTP requests while providing a convenient interface for managing session-specific data and settings.

It's particularly useful for scenarios where efficiency and state management are crucial such as web automation or API integration.

Syntax

Following is the syntax and parameters of Python Requests session() method −

requests.session()

Parameter

This method does not take any parameters.

Return value

This method returns a Response object.

Example 1

Following is the basic example of the python requests session() method −

import requests

# Create a session
session = requests.session()

# Now you can use `session` to make requests
response = session.get('https://google.com')
print(response)

Output

<Response [200]>

Example 2

When making HTTP requests using the requests library in Python we can preserve cookies across multiple requests by utilizing a session object. A session object will persist cookies across all requests within that session. Here's how we can do it −

import requests

# Create a session object
session = requests.Session()

# Perform a GET request to receive cookies
response = session.get('https://tutorialspoint.com')

# Print the received cookies
print("Received cookies:", session.cookies)

# Now, you can make subsequent requests within the same session
response = session.get('https://tutorialspoint.com/another-page')

# Print the updated cookies after subsequent requests
print("Updated cookies:", session.cookies)

Output

Received cookies: <RequestsCookieJar[]>
Updated cookies: <RequestsCookieJar[]>>

Example 3

Setting headers in HTTP requests using the requests library in Python is straightforward. We can pass a dictionary containing the headers to the headers parameter of the request methods such as get, post, put, delete, etc. Below is an example of how we can set headers −

import requests

# Define custom headers
headers = {
    'User-Agent': 'Welcome to tutorialspoint',
    'Authorization': 'Bearer my_token'
}

# Make a GET request with custom headers
response = requests.get('https://tutorialspoint.com', headers=headers)

# Print the response
print(response.text)

Output

<!DOCTYPE html>>
<html lang="en">
-------------------
-------------------
-------------------
</script>
</body>
</html>
</pre>
python_modules.htm
Advertisements