Search code examples
pythonoopinheritancepython-requestsspecialization

How to subclass requests in python through inheritance


I would like to specialize / subclass the requests package to add some method with custom functionality.

I tried to do this:

# concrete_requests.py
import requests

class concreteRequests(requests):
    def __init__(self):
        super(concreteRequests, self).__init__() 
        self.session()

    def login(self):
        payload = {'user': 'foo', 'pass': 'bar'}
        self.get('loginUrl', headers=header, data=payload)
        # more login stuff...

# my_class.py
class MyClass:
    def __init__():
        self.requests = concreteRequests()
        self.requests.login()

This way I could still benefit from self.requests members + my concrete implementation. So I could do: self.requests.get(...) or print(self.requests.post(...).status_code) and so on.

I guess that this line super(concreteRequests, self).__init__() can be stupidly useless since requests doesn't have any class declaration inside just imports...

So, the requests package can be subclassed/specialized through inheritance ?


Solution

  • requests is a python module not a class. You can only subclass classes.

    So basically you should just leverage its methods/functions inside your own custom class.

    import requests
    
    class MyRequests:
        def __init__(self, username, passwd):
            self.username = username
            self.passwd = passwd
    
        def get(self, *args, **kwargs):
            # do your thing
            resp = requests.get(...)
            # do more processing
    

    What I wrote above is just an example to get you going.