Python请求。会话()即使在验证后也随机返回401

2024-05-20 18:43:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用请求。会话()通过身份验证发出web请求。也许70%的时候我会得到状态码200,但我也偶尔得到401。在

因为我使用的是一个会话-我绝对肯定凭据是正确的-因为相同的请求重复时可能返回200。在

更多细节:

  • 我正在使用sharepointrestapi

  • 我正在使用NTLM身份验证

为了避免这个问题,我尝试编写一个循环,它将休眠几秒钟,然后重试请求。奇怪的是,我还没有看到实际的恢复-相反,如果第一个请求失败,那么所有后续请求也将失败。但是如果我再试一次,请求可能会在第一次尝试时成功。在

请注意,我已经复习了this question,但建议使用请求。会话(),我已经在做了,但仍然收到401

下面是一些代码来演示我到目前为止所做的尝试。在

import requests
from requests_ntlm import HttpNtlmAuth
from urllib.parse import quote

# Establish requests session
s = requests.Session()
s.auth = HttpNtlmAuth(username, password)

# Update the request header to request JSON formatted output
s.headers.update({'Content-Type': 'application/json; odata=verbose', 
                   'accept': 'application/json;odata=verbose'})

def RetryLoop(req, max_tries = 5):
    ''' Takes in a request object and will retry the request
        upon failure up the the specified number of maximum 
        retries.

        Used because error codes occasionally surface even though the 
        REST API call is formatted correctly. Exception returns status code 
        and text. Success returns request object. 

        Default max_tries = 5
    '''

    # Call fails sometimes - allow 5 retries
    counter = 0

    # Initialize loop
    while True:
        # Hit the URL
        r = req

        # Return request object on success
        if r.status_code == 200:
            return r

        # If limit reached then raise exception
        counter += 1
        if counter == max_tries:
            print(f"Failed to connect. \nError code = {r.status_code}\nError text: {r.text}")

        # Message for failed retry
        print(f'Failed request. Error code: {r.status_code}. Trying again...')

        # Spacing out the requests in case of a connection problem
        time.sleep(5)

r = RetryLoop(s.get("https://my_url.com"))

另外,我还尝试在重试循环中创建一个新的会话,但这似乎也没有帮助。我认为5秒的睡眠时间应该足够了,如果它是一个临时性的网站,因为我尝试了自己在更短的时间内,得到了预期的200。我希望看到一两次失败,然后成功。在

有没有我遗漏的潜在问题?有没有更合适的办法让我重新申请401?在

**EDIT:@Swadeep指出了问题-通过将请求传递给函数,它只调用请求一次。正常工作的更新代码:

^{pr2}$

Tags: the代码textfromimport身份验证objectrequest
1条回答
网友
1楼 · 发布于 2024-05-20 18:43:50

这就是我的提议。在

import requests
from requests_ntlm import HttpNtlmAuth
from urllib.parse import quote

# Establish requests session
s = requests.Session()
s.auth = HttpNtlmAuth(username, password)

# Update the request header to request JSON formatted output
s.headers.update({'Content-Type': 'application/json; odata=verbose', 'accept': 'application/json;odata=verbose'})

def RetryLoop(s, max_tries = 5):
    '''Takes in a request object and will retry the request
        upon failure up the the specified number of maximum 
        retries.

        Used because error codes occasionally surface even though the 
        REST API call is formatted correctly. Exception returns status code 
        and text. Success returns request object. 

        Default max_tries = 5
    '''

    # Call fails sometimes - allow 5 retries
    counter = 0

    # Initialize loop
    while True:
        # Hit the URL
        r = s.get("https://my_url.com")

        # Return request object on success
        if r.status_code == 200:
            return r

        # If limit reached then raise exception
        counter += 1
        if counter == max_tries:
            print(f"Failed to connect. \nError code = {r.status_code}\nError text: {r.text}")

        # Message for failed retry
        print(f'Failed request. Error code: {r.status_code}. Trying again...')

        # Spacing out the requests in case of a connection problem
        time.sleep(5)

r = RetryLoop(s)

相关问题 更多 >