将 cURL 作为变量存储在 Python 中

Storing a cURL as a variable in Python

所以,我最初的想法是在 Python 中的给定条件后执行 cURL。 我尝试使用 os 模块,使用:

os.system(curl -k "http://myhost.com" -d'{"event": { "Error": "Error Found", "Host": "myhostname"}}')

但是我有一个语法错误。

我知道它是硬编码的,而且 Python 中有一个名为 requests 的模块,所以.. 我的疑问是,我可以将这个完整的 link 设置为变量吗?喜欢

mycurl = curl -k "http://myhost.com" -d'{"event": { "Error": "Error Found", "Host": "myhostname"}}'

然后执行:

os.system(mycurl)

如果它不是possible,或者它不正确,那么在这种情况下我该如何使用模块请求?因为我想用这个curl设置一个Authorization Token,就是:

curl -k "http://myhost.com" -H "Authorization: MYTOKEN" -d'{"event": { "Error": "Error Found", "Host": "myhostname"}}'

以下是您可以通过 requests 执行此操作的方法:

import requests

# ...

if i in str(read_log):

    url = "http://myhost.com"

    headers = {
        "Authorization": "MYTOKEN"
    }

    payload = {
        "event": {
            "Error": "Error Found",
            "Host": "myhostname"
        }
    }

    response = requests.post(url, headers=headers, json=payload)
    # Do something with response...

就像上面 Barmar 所说的,os.system 的参数需要是一个字符串。您可以使用反斜杠 \ 转义字符串中的引号 "。例如:

os.system("curl -k \"http://myhost.com\" -d'{\"event\": { \"Error\": \"Error Found\", \"Host\": \"myhostname\"}}'")

为了使 os.system 方法更清晰一些,您可以结合 f-strings 和 docstrings:

URL = "http://myhost.com"
TOKEN = MYTOKEN
MY_HOSTNAME = myhostname
    
curl_command = f"""curl -k {URL} 
                        -H "Authorization: {TOKEN}" 
                        -d'{"event": { "Error": "Error Found", "Host": {MY_HOSTNAME}}}'
                """
os.system(curl_command)