API 调用脚本在 cron 作业中失败,但手动运行时工作正常

问题描述 投票:0回答:1

API 调用脚本在 cron 作业中失败,但在手动运行时工作正常。 我的 Python 脚本正在调用 https://stat-xplore.dwp.gov.uk/webapi/rest/v1/schema 我得到的错误是:

Request failed: HTTPSConnectionPool(host='stat-xplore.dwp.gov.uk', port=445): Max retries exceeded with url: /webapi/rest/v1/schema (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0j0iefhfnfj9>, 'Connection to stat-xplore.dwp.gov.uk timed out. (connect timeout=30)'))

我尝试过增加超时时间,但没有效果。不涉及使 api 调用正常工作的 Cron 作业。

#!/usr/bin/python3
import json
import requests
import os


url = 'https://stat-xplore.dwp.gov.uk/webapi/rest/v1/schema'

# Set your API key in the environment variable
os.environ['APIKey'] = 'myapikey'

#I have also tried this without setting environment variable
#api_key='myapikey'

# Get the API key from the environment variable
api_key = os.environ['APIKey']
headers = {'Accept': 'application/json', 'APIKey': api_key}

try:
    response = requests.get(url, headers=headers, timeout=30)
    print(response)
    # Process the response...
except requests.RequestException as e:
    print("Request failed:", e)

我的计划任务

42 18 * * * /usr/bin/python3 /home/user/bin/bash/statxplore_api.py

我尝试过的事情:

设置环境变量, 检查文件权限以确保它可以执行, 通过 ping 到 https://stat-xplore.dwp.gov.uk

测试网络连接
python api cron
1个回答
0
投票

我通过添加代理解决了这个问题

#!/usr/bin/python3

import json
import requests
import os


# Define your proxy server
proxies = {
    'http': 'http://yourproxy:0303',
    'https': 'http://yourproxy:0303'
}


url = 'https://stat-xplore.dwp.gov.uk/webapi/rest/v1/schema'

# Set your API key in the environment variable
os.environ['APIKey'] = 'myapikey'

# Get the API key from the environment variable
api_key = os.environ['APIKey']
headers = {'Accept': 'application/json', 'APIKey': api_key}

try:
    response = requests.get(url, headers=headers, proxies=proxies, timeout=30)
    print(response)
    # Process the response...
except requests.RequestException as e:
    print("Request failed:", e)

要了解正在使用的代理,您可以运行下面的代码

import os

proxy_env_vars = ['http_proxy', 'https_proxy']

# Check for proxy settings
for var in proxy_env_vars:
    proxy_val = os.getenv(var)
    if proxy_val:
        print(f"{var}: {proxy_val}")
    else:
        print(f"{var}: Not set")

© www.soinside.com 2019 - 2024. All rights reserved.