首页 > 解决方案 > 如何拒绝 Python 对 Bitbucket 的拉取请求?

问题描述

您如何使用 Bitbucket 的 2.0 API 通过 Python 拒绝拉取请求?

根据他们的文档,它应该是这样的:

import requests
kwargs = {
    'username': MY_BITBUCKET_ACCOUNT,
    'repo_slug': MY_BITBUCKET_REPO,
    'pull_request_id': pull_request_id
}
url = 'https://api.bitbucket.org/2.0/repositories/{username}/{repo_slug}/pullrequests/{pull_request_id}/decline'.format(**kwargs)
headers = {'Content-Type': 'application/json'}
response = requests.post(url, auth=(USERNAME, PASSWORD), headers=headers)

但是,这response.text只是简单地说“错误请求”而失败。

这个类似的代码适用于我的其他 API 端点,所以我不确定为什么拒绝方法失败。

我究竟做错了什么?

标签: pythonapibitbucket

解决方案


您必须通过 Oath 进行身份验证。我为提出这些请求编写了一个包装器。这是一个有效的简单示例。我唯一不知道的是如何添加被拒绝的原因。在我拒绝 PR 之前,我最终提出了一个请求,该 PR 添加了关于它被拒绝原因的评论。

import os

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session


class Bitbucket(object):

    def __init__(self, client_id, client_secret, workplace, repo_slug):
        self.workplace = workplace  # username or company username
        self.repo_slug = repo_slug
        self.token_url = 'https://bitbucket.org/site/oauth2/access_token'
        self.api_url = 'https://api.bitbucket.org/2.0/'
        self.max_pages = 10
        self.client = BackendApplicationClient(client_id=client_id)
        self.oauth = OAuth2Session(client=self.client)
        self.oauth.fetch_token(
            token_url=self.token_url,
            client_id=client_id,
            client_secret=client_secret
        )

    def get_api_url(self, endpoint):
        return f'{self.api_url}repositories/{self.workplace}/{self.repo_slug}/{endpoint}'


bitbucket = Bitbucket(os.environ['BITBUCKET_KEY'], os.environ['BITBUCKET_SECRET'], workplace='foo', repo_slug='bar')
pr_id = 1234
resp = bitbucket.oauth.post(f"{bitbucket.get_api_url('pullrequests')}/{pr_id}/decline")
if resp.status_code == 200:
    print('Declined')
else:
    print('Someting went wrong.')

推荐阅读