首页 > 解决方案 > 当通过烧瓶 API 调用时,gitpython 的 clone_from() 在克隆 repo 时抛出异常

问题描述

我有 python 片段,它通过 https 访问令牌克隆 github repo,创建一个修改内容的分支,然后推回。如果在命令行上直接通过 python 解释器运行,下面的代码工作得很好。但是我有一个用例,我通过 python 的烧瓶服务器将此功能公开为 API。Flask 服务器通过 python 的“gunicorn”框架运行,该框架是一个 Python WSGI HTTP 服务器。现在,当我使用 API 调用时,它会在克隆存储库时引发错误。我已经通过仅运行烧瓶服务器对其进行了测试,并且 API 调用工作得非常好,并且在没有引发异常的情况下完成了工作。但是当通过 gunicorn 运行同一个烧瓶时,我遇到了这个错误。

不知道如何摆脱该错误。

代码片段:

    import git
    .........
    .........
    .........
    try:
        _repo = git.Repo.clone_from(
            f"https://{_token}:x-oauth-basic@{self.git_url}", _repo_dir
        )
        _new_branch = _repo.create_head(_branch)
        _repo.head.set_reference(_new_branch)
    except Exception as e:
        return False, str(e)
    _update_path = os.path.join(
        _repo_dir, f"repo1/config/"
    )
    if not os.path.exists(_update_path):
        os.mkdir(_update_path)
    with open(f"{_update_path}/users.json", "w+") as _fd:
        json.dump(_users_json, _fd, indent=4)
    _repo.git.add(A=True)
    _repo.git.commit(m=_title)
    _repo.git.push("origin", _branch)

错误:

2020-06-11 17:18:16,714 DEBUG: Popen(['git', 'clone', '-v', 'https://<ACCESS_TOKEN>:x-oauth-basic@github.com/ganesh/repo1.git', '/tmp/folder-1234_1591895896.185123'], cwd=/opt/ganesh, universal_newlines=True, shell=None, istream=None)
2020-06-11 17:18:16,739 DEBUG: Cmd(['git', 'clone', '-v', 'https://<ACCESS_TOKEN>:x-oauth-basic@github.com/ganesh/repo1.git', '/tmp/folder-1234_1591895896.185123'])'s unused stdout: Cloning into '/tmp/folder-1234_1591895896.185123'...

2020-06-11 17:18:16,740 DEBUG: AutoInterrupt wait stderr: b'Error reading command stream\n'

感谢您对此的任何帮助。谢谢

标签: gitgithubpython-3.6gunicorngitpython

解决方案


此问题已解决。它发生在 gunicorn 上,因为它通过创建多个工作程序以守护模式运行烧瓶服务器。gitpython 代码库,

https://github.com/gitpython-developers/GitPython/blob/24cd6dafc0008f155271f9462ae6ba6f0c0127a4/git/repo/base.py#L953-L960

期待一些流来读取它的每个输出。但是在守护进程的情况下,没有输出流侦听器和 clone_from 模块引发异常。

我通过在 gunicorn 端设置一些选项来解决这个问题,让它捕获这些流。

--enable-stdio-inheritance \
--error-logfile /tmp/gunicorn_error.log \
--capture-output \

这个问题已经在 gitpython 存储库中提出,为什么在缺少输出流读取器的情况下会出现这种行为。

https://github.com/gitpython-developers/GitPython/issues/1020


推荐阅读