简体   繁体   中英

requests.session() object not recognized in another class

I am trying to pass my session object from one class to another. But I am not sure whats happening.

    class CreateSession:
      def __init__(self, user, pwd, url="http://url_to_hit"):
        self.url = url
        self.user = user
        self.pwd = pwd

      def get_session(self):
        sess = requests.Session()
        r = sess.get(self.url + "/", auth=(self.user, self.pwd))
        print(r.content)
        return sess


    class TestGet(CreateSession):
      def get_response(self):
        s = self.get_session()
        print(s)
        data = s.get(self.url + '/some-get')
        print(data.status_code)
        print(data)

    if __name__ == "__main__":
      TestGet(user='user', pwd='pwd').get_response()

I am getting 401 for get_response(). Not able to understand this.

What's a 401?

The response you're getting means that you're unauthorised to access the resource.


A session is used in order to persist headers and other prerequisites throughout requests, why are you creating the session every time rather than storing it in a variable?

As is, the session should work the only issue is that you're trying to call a resource that you don't have access to. - You're not passing the url parameter either in the initialisation.


Example of how you can effectively use Session :

from requests import Session
from requests.exceptions import HTTPError

class TestGet:
    __session = None

    __username = None
    __password = None

    def __init__(self, username, password):
        self.__username = username
        self.__password = password

    @property
    def session(self):
        if self.__session is None:
            self.__session = Session()
            self.__session.auth = (self.__user, self.__pwd)

        return self.__session

    @session.setter
    def session(self, value):
        raise AttributeError('Setting \'session\' attribute is prohibited.')

    def get_response(self, url):
        try:
            response = self.session.get(url)

            # raises if the status code is an error - 4xx, 5xx
            response.raise_for_status()

            return response
        except HTTPError as e:
            # you received an http error .. handle it here (e contains the request and response)
            pass

test_get = TestGet('my_user', 'my_pass')
first_response = test_get.get_response('http://your-website-with-basic-auth.com')
second_response = test_get.get_response('http://another-url.com')

my_session = test_get.session
my_session.get('http://url.com')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM