
- Requests Tutorial
- Requests - Home
- Requests - Overview
- Requests - Environment Setup
- Requests - How Http Requests Work?
- Requests - Working with Requests
- Handling Response for HTTP Requests
- Requests - HTTP Requests Headers
- Requests - Handling GET Requests
- Handling POST, PUT, PATCH & DELETE Requests
- Requests - File Upload
- Requests - Working with Cookies
- Requests - Working with Errors
- Requests - Handling Timeouts
- Requests - Handling Redirection
- Requests - Handling History
- Requests - Handling Sessions
- Requests - SSL Certification
- Requests - Authentication
- Requests - Event Hooks
- Requests - Proxy
- Requests - Web Scraping using Requests
- Requests Useful Resources
- Requests - Quick Guide
- Requests - Useful Resources
- Requests - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Requests - Handling Sessions
To maintain the data between requests you need sessions. So, if the same host is called again and again, you can reuse the TCP connection which in turn will improve the performance. Let us now see, how to maintain cookies across requests made using sessions.
Adding cookies using session
import requests req = requests.Session() cookies = dict(test='test123') getdata = req.get('https://httpbin.org/cookies',cookies=cookies) print(getdata.text)
Output
E:\prequests>python makeRequest.py { "cookies": { "test": "test123" } }
Using session, you can preserve the cookies data across requests. It is also possible to pass headers data using the session as shown below −
Example
import requests req = requests.Session() req.headers.update({'x-user1': 'ABC'}) headers = {'x-user2': 'XYZ'} getdata = req.get('https://httpbin.org/headers', headers=headers) print(getdata.headers)
Advertisements