在 python 脚本中通过 gitlab 项目 api 传递降价模板时出现问题

Problem passing markdown template via gitlab projects api in a python script

我正在尝试使用 gitlab 项目 api 来编辑多个项目 MR 模板。问题是,它只发送降价模板的第一行。

在弄乱脚本时,我正在尝试将其转换为 html,当我发现它在转换为 html 时发送了整个模板。

我可能遗漏了一些非常简单的东西,但对于我来说,我无法弄清楚为什么它能够在 html 中发送整个模板,但只在 markdown 中发送它的第一行.

我一直在寻找解决方案,所以如果我的 googlefu 在这里遗漏了一个明显的答案,我深表歉意。

这是脚本...

#! /usr/bin/env python3

import argparse
import requests


gitlab_addr = "https://gitlab.com/api/v4"

# Insert your project IDs into the array below.
project_IDs = [xxxx, yyyy, zzzz]

# Insert your MR template info below.
with open('/.gitlab/merge_request_templates/DefaultMRTemplate.md', 'r') as file:
    MR_template = file.read()
    #print(MR_template)


def getArgs():
    parser = argparse.ArgumentParser(
        description='This tool updates the default template for a single '
        'or multiple program\'s MRs. \n\nYou will need to edit '
        'the script to input your MR template and projects IDs.'
        '\nYou will also need to pass in your API Token via '
        ' command line.\n\nYou want to see "200 OK" on the '
        ' command line as confirmation.',
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("token", type=str,
        help="API Token. Create one at User Settings / Access Tokens")
    return parser.parse_args()


def ChangeTemplate():
    token = getArgs().token
    headers = {"PRIVATE-TOKEN": token, }

    for x in project_IDs:
        addr = f"{gitlab_addr}/projects/{x}/?merge_requests_template={MR_template}"

        response = requests.put(addr, headers=headers)

        # You want to see "200 OK" on the command line.
        print(response.status_code, response.reason)


def main():
    ChangeTemplate()


if __name__ == '__main__':
    main()

这是一个示例模板...

See guidance here:  https://example.com/Gitlab+MR+Guide

## Description

%% Put a description here %%

%% Add an issue link here %%

## Tests

%% Include test listing here %%

## Checklists

**Author Checklist**
- [ ] A: Did you fill out the description, add an issue link (in title or desc) and fill out the test section?
- [ ] A: Add a peer to the MR 

**Assignee 1 Checklist:**
- [ ] P: Verify the description field is filled out, issue link is included (in title or desc) and the test section is filled out
- [ ] P: Add a code owner to the MR 

**Assignee 2 (Code Owner) Checklist:**
- [ ] O: Verify the description field is filled out, issue link is included (in title or desc) and the test section is filled out
- [ ] O: Verify unit test coverage is at least 40% line coverage with a goal of 90%

问题输出...

See guidance here:  https://example.com/Gitlab MR Guide

您的数据需要在请求中正确编码。尝试将文件的文字内容格式化为查询字符串在这里不起作用。

使用 data 关键字参数到 requests.put,这将传递请求正文中的数据(或使用 params 设置查询参数)。 requests 将处理数据的正确编码。

addr = f"{gitlab_addr}/projects/{x}/"
payload = {'merge_requests_template': MR_template}
response = requests.put(addr, headers=headers, data=payload)
# or params=payload to use query string