json 无法建立新连接:[Errno 11001]在Python 3.9中获取地址信息失败

wlsrxk51  于 2023-02-10  发布在  Python
关注(0)|答案(1)|浏览(495)

此脚本用于将数据发送到第三方。连接到工作网络以外的任何网络时,它似乎运行良好。连接到工作网络时,它将运行几分钟,按正常方式进行PUT/POST,然后突然出现以下错误:

File "C:\Users\user\AppData\Local\RPackages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\connection.py", line 169, in _new_conn
    conn = connection.create_connection(
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\util\connection.py", line 73, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\socket.py", line 954, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\connectionpool.py", line 382, in _make_request
    self._validate_conn(conn)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\connectionpool.py", line 1010, in _validate_conn
    conn.connect()
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\connection.py", line 353, in connect
    conn = self._new_conn()
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\connection.py", line 181, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x0000022FD9B44FA0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\urllib3\util\retry.py", line 574, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='vaccine-verify-v1.services.school.edu', port=443): Max retries exceeded with url: /api/verify (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000022FD9B44FA0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\scripture\bali_vax.py", line 71, in <module>
    post_vax_record(row)
  File "C:\scripture\bali_vax.py", line 38, in post_vax_record
    response = requests.post(url,json=vaxrecord, headers=headers, timeout=5)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\api.py", line 117, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='vaccine-verify-v1.services.school.edu', port=443): Max retries exceeded with url: /api/verify (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000022FD9B44FA0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

脚本

import timeit
start = timeit.default_timer() 

import requests

url = 'https://vaccine-verify-v1.services.school.edu/api/verify' 
client_id = "abc"
client_secret = "123"

def post_vax_record(record):
    manuallyVerified = record[7].lower() == "true"; 
    vaxrecord = { "firstName":record[0], "lastName": record[1], "dob": record[2], "phoneNumber": (record[3] or '4444444444'), "state": record[4], "zip": record[5][:5], "campusName": "Baltimore", "instituitionId": 0, "campusSuCd": 28, "sunyLanId": record[6], "sunyStudId": 0, "ssoId": "BEL-"+record[6], "manuallyVerified": manuallyVerified }
    headers = {'Client_Id':client_id, 'Client_Secret':client_secret,'Content-Type':'application/json'}
    response = requests.post(url,json=vaxrecord, headers=headers, timeout=5)
    if response:

        json_response = response.json()
        if ('message' in json_response and json_response['message'] ==  'The Student record already exists. Please use put operation to insert the record.'): #changed from update to insert
            print ('Post failed. Trying put instead')
            response = requests.put(url,json=vaxrecord, headers=headers)
            if response:
                print('Success on put for '+record[6])
            else:
                print('Put failed for '+record[6])
        else: 
            print('Success on post for '+record[6])
        print(response.json())  
    else:
        print('Post failed for '+record[6]+' with error code: ')
        print(response.status_code)
        
import csv
with open('data_file.csv') as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        if row[6].upper().split('@')[1] in ("LIVE.LODI.EDU", "LODI.EDU"): 
          if row[0].upper() != "FIRSTNAME":
            row[6] = row[6].upper().split('@')[0]
            post_vax_record(row)
        else:
            print('NON-LODI EMAIL FOUND FOR '+row[1]+', '+row[0]+'. WILL NOT PROCESS RECORD!')
stop = timeit.default_timer()
print('Run Time: ', stop - start)

在测试这个脚本的时候,我使用了较小的CSV(需要读取的记录较少),我从来没有遇到过问题。只是最近才出现这种情况。任何帮助都非常感谢。
谢谢你。

mrphzbgm

mrphzbgm1#

请使用try-catch块将response = requests.post(url,json=vaxrecord, headers=headers, timeout=5)行换行

while retry_counter < 5:
  try:            
      response = requests.post(url,json=vaxrecord, headers=headers, timeout=5)
   except socket.error as error:
       print("Connection Failed due to socket - {}").format(error)
       print("Attempting {} of 5").format(retry_counter)
       time.sleep(3)
       retry_counter  += 1

注意:一般来说,在套接字错误的情况下,一段时间后重试代码将解决这个问题(发生在我的情况下),因此下面的解决方案
当执行request.post时,如果发生socket.error,则重试代码3-5次,延迟1-3秒。

相关问题