Memory Leak in Python requests Last Updated : 01 Dec, 2021 Summarize Comments Improve Suggest changes Share Like Article Like Report When a programmer forgets to clear a memory allocated in heap memory, the memory leak occurs. It's a type of resource leak or wastage. When there is a memory leak in the application, the memory of the machine gets filled and slows down the performance of the machine. This is a serious issue while building a large scalable application. Request: The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response. Gc Module: Module gc is a python inbuilt module, that provides an interface to the python Garbage collector. It provides features to enable collector, disable collector, tune collection frequency, debug options and more. In lower-level languages like C and C++, the programmer should manually free the resource that is unused i.e write code to manage the resource. But high-level languages like python, java have a concept of automatic memory manager known as Garbage collector. Garbage collector manages the allocation and release of memory for an application. Some gc methods that we will be using are listed below. get_objects(): This method returns a list of all tracked objects by the Garbage collector, excluded the list being returned.collect(): This method free the non referenced object in the list that is maintained by the Collector. Some non-referenced objects are not immediately free automatically due to their implementation. We will be using get() method in requests, that returns a response object. When the response object is non-referenced i.e deleted its memory should be freed immediately, but due to its implementation, the resource is not freed automatically. Here its stats leaking memory. Identify Memory Leak: Approach: Get and store the number of objects, tracked ( created and alive) by Collector. You can use gc.get_objects() to get list of tracked objects then use len function to count no. of objects.Call the function that calls the request.get() method.Print the response status code, so that we can confirm that the object is created.Then return the function. When the function is returned, all the created within the function should be deleted.Get the number of objects tracked currently and compare the valve with the previous value for the leaked objects.If currently, returned object count is greater, so there is a memory leak. Below is the implementation: Python3 import requests import gc def call(): # call the get with a url,here I used google.com # get method returns a response object response = requests.get('https://google.com') # print the status code of response print("Status code", response.status_code) # After the function is been returned, # the response object becomes non-referenced return def main(): print("No.of tracked objects before calling get method") # gc.get_objects() returns list objects been tracked # by the collector. # print the length of object list with len function. print(len( gc.get_objects() ) ) # make a call to the function, that calls get method. call() print("No.of tracked objects after calling get method") # print the length of object list with len function. print(len( gc.get_objects() ) ) if __name__ == "__main__": main() Output: No.of tracked objects before calling get method 16071 Status code 200 No.of tracked objects after calling get method 16158Fix Memory leak: A simple solution to this is to manually call the gc.collect() method, this method will free the resource immediately. Approach: Get and store the number of objects, tracked ( created and alive) by Collector. You can use gc.get_objects() to get list of tracked objects then use len function to count no. of objects.Call the function that calls the request.get() method.Print the response status code, so that we can confirm that the object is created.Then return the function. When the function is returned, all the created within the function should be deleted.Call the garbage collector to free the unused resource, i.e to call the gc.collect() method.Get the number of objects tracked currently, now you can notice the lesser number objects this due to cleaning unused resource. Below is the implementation: Python3 import requests import gc def call(): # call the get with a url,here I used google.com # get method returns a response object response = requests.get('https://google.com') # print the status code of response print("Status code",response.status_code) # After the function is been returned, # the response object becomes non-referenced return def main(): print("No.of tracked objects before calling get method") # gc.get_objects() returns list objects been tracked # by the collector. # print the length of object list with len function. print(len( gc.get_objects() ) ) # make a call to the function, that calls get method. call() # collect method immediately free the resource of # non-referenced object. gc.collect() # print the length of object list with len # function after removing non-referenced object. print("No.of tracked objects after removing non-referenced objects") print(len( gc.get_objects() ) ) if __name__ == "__main__": main() Output: No.of tracked objects before calling get method 16071 Status code 200 No.of tracked objects after removing non-referenced objects 15954 Comment More infoAdvertise with us Next Article How to get the Daily News using Python K kabilan Follow Improve Article Tags : Python Python-requests Practice Tags : python Similar Reads Python Requests Python Requests Library is a simple and powerful tool to send HTTP requests and interact with web resources. It allows you to easily send GET, POST, PUT, DELETE, PATCH, HEAD requests to web servers, handle responses, and work with REST APIs and web scraping tasks.Features of Python Requests LibraryS 5 min read Getting Started with python-requestsWhat is Web Scraping and How to Use It?Suppose you want some information from a website. Letâs say a paragraph on Donald Trump! What do you do? Well, you can copy and paste the information from Wikipedia into your file. But what if you want to get large amounts of information from a website as quickly as possible? Such as large amounts o 7 min read How to Install Requests in Python - For Windows, Linux, MacRequests is an elegant and simple HTTP library for Python, built for human beings. One of the most famous libraries for Python is used by developers all over the world. This article revolves around how one can install the requests library of Python in Windows/ Linux/ macOS using pip.Table of Content 7 min read HTTP Request MethodsGET method - Python requestsRequests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make GET request to a specified URL using requests.GET() method. Before checking out GET method, let's figure out what a GET request is - GET Http Method T 2 min read POST method - Python requestsRequests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make POST request to a specified URL using requests.post() method. Before checking out the POST method, let's figure out what a POST request is -  POST Ht 2 min read PUT method - Python requestsThe requests library is a powerful and user-friendly tool in Python for making HTTP requests. The PUT method is one of the key HTTP request methods used to update or create a resource at a specific URI.Working of HTTP PUT Method If the resource exists at the given URI, it is updated with the new dat 2 min read DELETE method- Python requestsRequests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make DELETE request to a specified URL using requests.delete() method. Before checking out the DELETE method, let's figure out what a Http DELETE request i 2 min read HEAD method - Python requestsRequests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make HEAD request to a specified URL using requests.head() method. Before checking out the HEAD method, let's figure out what a Http HEAD request is - HEAD 2 min read PATCH method - Python requestsRequests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PATCH request to a specified URL using requests.patch() method. Before checking out the PATCH method, let's figure out what a Http PATCH request is - 3 min read Response Methodsresponse.headers - Python requestsThe response.headers object in Python's requests library functions as a special dictionary that contains extra information provided by the server when we make an HTTP request. It stores metadata like content type, server details and other headers, such as cookies or authorization tokens. The keys in 3 min read response.encoding - Python requestsPython requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 2 min read response.elapsed - Python requestsPython requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 2 min read response.close() - Python requestsPython requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 2 min read response.content - Python requestsWhen you make an HTTP request in Python using the requests library, it returns a response object. One of the most important attributes of this object is response.content, which gives you the raw response body in bytes. This is especially useful when dealing with binary data like images, PDFs, audio 1 min read response.cookies - Python requestsPython requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 2 min read response.history - Python requestsPython requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 2 min read response.is_permanent_redirect - Python requestsPython requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 2 min read response.is_redirect - Python requestsPython requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 2 min read response.iter_content() - Python requestsresponse.iter_content() iterates over the response.content. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain fe 2 min read response.json() - Python requestsPython requests are generally used to fetch the content from a particular resource URL. Whenever we make a request to a specified URL through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves 3 min read response.url - Python requestsresponse.url returns the URL of the response. It will show the main url which has returned the content, after all redirections, if done. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a 2 min read response.text - Python requestsIn Pythonâs requests library, the response.text attribute allows developers to access the content of the response returned by an HTTP request. This content is always returned as a Unicode string, making it easy to read and manipulate. Whether the response body contains HTML, JSON, XML, or plain text 3 min read response.status_code - Python requestsresponse.status_code returns a number that indicates the status (200 is OK, 404 is Not Found). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object 2 min read response.request - Python requestsresponse.request returns the request object that requested this response. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to acc 2 min read response.reason - Python requestsresponse.reason returns a text corresponding to the status code. for example, OK for 200, Not Found for 404. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this r 2 min read response.raise_for_status() - Python requestsWe are given a scenario where we use the Python requests library to make HTTP calls, and we want to check if any error occurred during the request. This can be done using the raise_for_status() method on the response object. For example, if we request a page that doesn't exist, this method will rais 3 min read response.ok - Python requestsresponse.ok returns True if status_code is less than 400, otherwise False. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to ac 2 min read response.links - Python requestsresponse.links returns the header links. To know more about Http Headers, visit - Http Headers. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response objec 2 min read Convert JSON data Into a Custom Python Object In Python, converting JSON data into a custom object is known as decoding or deserializing JSON data. We can easily convert JSON data into a custom object by using the json.loads() or json.load() methods. The key is the object_hook parameter, which allows us to define how the JSON data should be con 2 min read Authentication using Python requests Authentication refers to giving a user permissions to access a particular resource. Since, everyone can't be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a 2 min read SSL Certificate Verification - Python requests Requests verifies SSL certificates for HTTPS requests, just like a web browser. SSL Certificates are small data files that digitally bind a cryptographic key to an organization's details. Often, a website with a SSL certificate is termed as secure website. By default, SSL verification is enabled, an 2 min read Exception Handling Of Python Requests Module Python's requests module is a simple way to make HTTP requests. In this article, weâll use the GET method to fetch data from a server and handle errors using try and except. This will help us understand how to manage situations where the request fails or returns an error."url: Returns the URL of the 3 min read Memory Leak in Python requests When a programmer forgets to clear a memory allocated in heap memory, the memory leak occurs. It's a type of resource leak or wastage. When there is a memory leak in the application, the memory of the machine gets filled and slows down the performance of the machine. This is a serious issue while bu 5 min read ProjectsHow to get the Daily News using PythonIn this article, we are going to see how to get daily news using Python. Here we will use Beautiful Soup and the request module to scrape the data. Modules neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. T 3 min read How to Build Web scraping bot in PythonIn this article, we are going to see how to build a web scraping bot in Python. Web Scraping is a process of extracting data from websites. A Bot is a piece of code that will automate our task. Therefore, A web scraping bot is a program that will automatically scrape a website for data, based on our 8 min read Send SMS with REST Using PythonIn this article, we are going to see how we can send SMS with REST using Python. The requests library can be used to make REST requests using Python to send SMS. Approach:You need to first create a REST API KEY for sending SMS using Python Script. We have used Fast2SMS for creating API KEY.You can 2 min read How to check horoscope using Python ?In this article, we are going to see how to get a horoscope a day before, on that day as well as the day after using Beautifulsoup. Module needed:bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this t 4 min read Web Scraping - Amazon Customer ReviewsIn this article, we are going to see how we can scrape the amazon customer review using Beautiful Soup in Python. Module neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below comma 5 min read Like