我在 github here 中有一个 python 工作流程。我可以从 Web 界面运行该工作流程。但问题是每次我都必须访问 github 并点击
run workflow
。我再次必须从未知设备登录 github 才能运行该工作流程。 python 中是否有可以使用个人访问令牌运行工作流程的 github 模块?或者如何使用 requests 模块通过 github api 运行工作流程?我在谷歌上搜索了这个主题,但没有找到任何有效的解决方案。其中许多已经过时或没有正确解释。
这是我在这里使用的工作流程:
name: Python
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout repo
uses: actions/[email protected]
- name: Run a script
run: python3 main.py
感谢@C.Nivs 和@larsks 帮助我找到正确的文档。 在尝试了github api之后,终于找到了答案。这是我使用的代码:
branch, owner, repo, workflow_name, ghp_token="main", "dev-zarir", "Python-Workflow", "python.yml", "ghp_..."
import requests
def run_workflow(branch, owner, repo, workflow_name, ghp_token):
url = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_name}/dispatches"
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {ghp_token}",
"Content-Type": "application/json"
}
data = '{"ref":"'+branch+'"}'
resp = requests.post(url, headers=headers, data=data)
return resp
response=run_workflow(branch, owner, repo, workflow_name, ghp_token)
if response.status_code==204:
print("Workflow Triggered!")
else:
print("Something went wrong.")
一个更Pythonic的解决方案是使用
pygithub
包:
import github, os
g = github.Github(login_or_token=os.environ["GITHUB_PAT"])
repo = g.get_repo("my_org/my_repo")
workflow_name = "cicd.yml"
workflow = repo.get_workflow(workflow_name)
ref = repo.get_branch("develop")
workflow.create_dispatch(ref=ref)
参见 https://pygithub.readthedocs.io/en/latest/github_objects/Workflow.html