无法将变量传递给python脚本

时间:2018-04-02 14:58:08

标签: python curl

我有以下代码在JIRA中创建子任务

inf = open('/var/lib/rundeck/output.txt')
for line in inf:
                print line
                headers = {'Content-Type': 'application/json',}
                data = '{"fields":{"project":{"key":"TECH"},"parent":{"key":line},"summary":"Create AD List ","description":"","issuetype":{"name":"Sub-task"},"customfield_10107":{"id":"10400"}}}'
                response = requests.post('https://jira.company.com/rest/api/latest/issue/', headers=headers, data=data, auth=('user', 'pass'))

inf.close()

我有一个文件(output.txt),python为每一行找到(TECH-XXX)printss所有行,它应该触发上面的脚本。

当我硬编码键"key":"TECH-1147"而不是"key":line脚本生成子任务时,但当替换变量(行)时,没有任何反应

Ouptut.txt:

TECH-1234
TECH-1345
.........

我认可了这段代码:

curl -D- -u: user:Pass -X POST --data "{\"fields\":{\"project\":{\"key\":\"TECH\"},\"parent\":{\"key\":\"$project\"},\"summary\":\"Create AD List of all Active Users\",\"description\":\"some description\",\"issuetype\":{\"name\":\"Sub-task\"},\"customfield_10107\":{\"id\":\"10400\"}}}" -H "Content-Type:application/json" https://company.com/rest/api/latest/issue/

使用此https://curl.trillworks.com/

还尝试{"key":'"' + line + '"'}

并获得{u'errorMessages': [u'The issue no longer exists.'], u'errors': {}}

问题是TECH-1247(变量)肯定存在

2 个答案:

答案 0 :(得分:3)

也许尝试使用rstrip()来查找任何尾随空格/换行符和json.dumps(),以便数据不会以表单编码方式传递...

import requests
import json

with open("output.txt", "rb") as infile:
    for line in infile:
        headers = {"Content-Type": "application/json"}
        data = {"fields": {
                "project": {"key": "TECH"},
                "parent": {"key": line.rstrip()},
                "summary": "Create AD List ",
                "description": "",
                "issuetype": {"name": "Sub-task"},
                "customfield_10107": {"id": "10400"}
                }}

        response = requests.post("https://jira.company.com/rest/api/latest/issue/",
                                 headers=headers,
                                 data=json.dumps(data),
                                 auth=("user", "pass"))

如同另一个回答所说,如果你使用json param而不是data param,dict将自动为你编码,Content-Type设置为application / json。

See here for more information.

答案 1 :(得分:1)

line不会被解释为变量。它只是一个字符串。一种解决方案是使用%运算符进行字符串格式化:

inf = open('/var/lib/rundeck/output.txt')
for line in inf:
    print line
    headers = {'Content-Type': 'application/json',}
    data = '{"fields":{"project":{"key":"TECH"},"parent":{"key":%s},"summary":"Create AD List ","description":"","issuetype":{"name":"Sub-task"},"customfield_10107":{"id":"10400"}}}' % line
    response = requests.post('https://jira.corp.hentsu.com/rest/api/latest/issue/', headers=headers, data=data, auth=('user', 'pass'))

inf.close()

请注意,line已替换为%s,然后% line被添加到最后。这会将%s替换为变量line的值。