【问题标题】:How to pass variable into post request in Python [duplicate]如何在Python中将变量传递给发布请求[重复]
【发布时间】:2021-03-25 23:21:11
【问题描述】:

我创建了一个简单的 python 程序来使用请求模块发送 Post Api 请求

# importing the requests library 
import requests 
import json


headers = {
    'PRIVATE-TOKEN': 'XXXXXXXXXXXXX',
    'Content-Type': 'application/json',
}

data = '{ "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": "failed"} ] }'

response = requests.post('https://gitlab.kazan.atosworldline.com/api/v4/projects/28427/pipeline', headers=headers, data=data)
print(response)

但是,我希望将下面的字符串替换为使用变量

"value": "failed"

下面的东西

"value": deployment_status

【问题讨论】:

标签: python api python-requests


【解决方案1】:

如果你想将json数据传递给你的API,你可以直接使用request.post()函数的json属性和一个字典变量。

例子:

# importing the requests library 
import requests 


headers = {
    'PRIVATE-TOKEN': 'XXXXXXXXXXXXX',
    'Content-Type': 'application/json',
}
deployment_status = "failed"
data = { "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": deployment_status} ] }

response = requests.post('https://gitlab.kazan.atosworldline.com/api/v4/projects/28427/pipeline', headers=headers, json=data)
print(response)

【讨论】:

  • 此代码对我有用..谢谢 :)
【解决方案2】:

您可以使用“f-string”将变量的值格式化为数据字符串。

例子

deployment_status = 'status'
data = f'{ "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": "{deployment_status}"} ] }'

【讨论】:

  • 这段代码在下面给出“SyntaxError: f-string: 表达式嵌套太深”
【解决方案3】:

如果你有最新版本的 python,你可以使用 f-strings:

deployment_status = 'failed'
data = f'{ "ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": "{deployment_status}"} ] }'

更新:

好的,结果对于 f 字符串来说嵌套太深了。

最好只使用json

import json

deployment_status = 'failed'
data = {"ref": "cd-pipeline", "variables": [ {"key": "STAGE", "value": "CD"}, {"key": "DEPLOYMENT_STATUS", "value": deployment_status} ] }

print(json.dumps(data))

【讨论】:

  • 如果您要使用此代码,请确保您的 python 版本 >3.6
  • 这给了我在 Python 3.7 上的SyntaxError: f-string: expressions nested too deeply
  • 这段代码对我有用..谢谢
猜你喜欢
  • 2019-06-07
  • 2021-06-02
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2020-10-17
  • 2015-08-24
  • 2021-11-30
相关资源
最近更新 更多