How to deal with 401 (unauthorised) in python requests

前端 未结 3 613
余生分开走
余生分开走 2021-01-06 05:58

What I want to do is GET from a site and if that request returns a 401, then redo my authentication wiggle (which may be out of date) and try again. But I don\'t want to try

3条回答
  •  清歌不尽
    2021-01-06 06:42

    You can use something like this

    # 401 retry strategy
    
    import requests
    from requests import Request, Session, RequestException
    
    
        class PreparedRequest:
        """
        Class to make Http request with 401 retry
        """
            failedRequests = []
            defaultBaseUrl = "https://jsonplaceholder.typicode.com"
            MAX_RETRY_COUNT = 0
    
            def __init__(self, method, endpoint,
                 baseurl=defaultBaseUrl, headers=None, data=None, params=None):
            """
            Constructor for PreparedRequest class
            @param method: Http Request Method
            @param endpoint: endpoint of the request
            @param headers: headers of the request
            @param data: data of request
            @param params: params of the request
            """
            self.method = method
            self.url = baseurl + endpoint
            self.headers = headers
            self.data = data
            self.params = params
            self.response = None
    
        def send(self):
        """
        To send http request to the server
        @return: response of the request
        """
            req = Request(method=self.method, url=self.url, data=self.data, 
                    headers=self.headers,params=self.params)
            session = Session()
            prepared = session.prepare_request(req)
            response = session.send(prepared)
            if response.status_code == 200:
                PreparedRequest.failedRequests.append(self)
                PreparedRequest.refresh_token()
            elif response.status_code == 502:
                raise Exception(response.raise_for_status())
            else:
                self.response = session.send(prepared)
    
        @staticmethod
        def refresh_token():
            if PreparedRequest.MAX_RETRY_COUNT > 3:
                return
            print("Refreshing the token")
            # Write your refresh token strategy here
            PreparedRequest.MAX_RETRY_COUNT += 1
            total_failed = len(PreparedRequest.failedRequests)
            for i in range(total_failed):
                item = PreparedRequest.failedRequests.pop()
                item.send()
    
    
    r = PreparedRequest(method="GET", endpoint="/todos/")
    r.send()
    print(r.response.json())
    

提交回复
热议问题