当前位置: 首页>>代码示例>>Python>>正文


Python github.GithubException方法代码示例

本文整理汇总了Python中github.GithubException方法的典型用法代码示例。如果您正苦于以下问题:Python github.GithubException方法的具体用法?Python github.GithubException怎么用?Python github.GithubException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github的用法示例。


在下文中一共展示了github.GithubException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: index

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def index():
    form = InputForm()
    if form.validate_on_submit():
        if len(form.url.data) > 0:
            try:
                files = github_api.get_gist(form.url.data.split('gists/', 1)[1]).files
                layout = next(v for k, v in files.items() if k.endswith('.kbd.json'))
                img = Keyboard(json.loads(layout.content)).render()
                return serve_pil_image(img)
            except (IndexError, github.GithubException):
                flash('Not a valid Keyboard Layout Editor gist')
        elif form.json.data:
            try:
                content = json.loads(form.json.data.read().decode('utf-8'))
                img = Keyboard(content).render()
                return serve_pil_image(img)
            except ValueError:
                flash(Markup('Invalid JSON input - see (?) for help'))
    flash_errors(form)
    return render_template('index.html', form=form) 
开发者ID:CQCumbers,项目名称:kle_render,代码行数:22,代码来源:app.py

示例2: connect

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def connect(self, params={}):
        self.logger.info("Connect: Connecting..")
        try:
            self.username = params.get('credentials').get("username")
            self.secret = params.get("credentials").get('password')
            self.basic_auth = (self.username, self.secret)
            self.github_session = requests.Session()
            self.github_user = github.Github(self.username, self.secret)
            user_info = self.github_user.get_user()
            self.user = self.github_user.get_user(self.username)
            self.github_session_user = requests.get(self.api_prefix, auth=(self.username, self.secret), verify=True)
            if str(self.github_session_user.status_code).startswith('2'):
                self.logger.info('Connect: Login successful')
            else:
                self.logger.info('Connect: Login unsuccessful')

        except github.GithubException as err:
            self.logger.error('Github: Connect: error %s', err.data)
            raise Exception('Github: Connect: user could not be authenticated please try again.')

        except requests.exceptions.RequestException as e:
            raise e 
开发者ID:rapid7,项目名称:insightconnect-plugins,代码行数:24,代码来源:connection.py

示例3: get_git_time

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def get_git_time(self):
        """Retrieve time from GitHub.

        Used to reliably determine time during Watchdog run.

        :return:                    Datetime object describing current time
        :rtype:                     datetime
        """
        try:
            datetime_object = self._get_git_time()
        except ValueError as e:
            raise GitWrapperError(str(e))
        except GithubException as e:
            message = 'GitHub Exception during API status retrieval. Exception: {}'.format(str(e))
            raise GitWrapperError(message)
        except timeout_decorator.TimeoutError:
            message = 'GitHub Exception during API status retrieval. Timeout during API request.'
            raise GitWrapperError(message)
        return datetime_object 
开发者ID:NervanaSystems,项目名称:ngraph-onnx,代码行数:21,代码来源:GitWrapper.py

示例4: get_pull_request_permissions

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def get_pull_request_permissions(self, user, repo):
        # it's impossible to call this as an integration
        if self.integration:
            return True

        try:
            # first, invite the bot to be a collaborator
            invite = repo.add_to_collaborators(user.login)
            # second, accept the invitation
            if invite:
                user.accept_invitation(invite)
        except GithubException:
            msg = "Unable to add {login} as a collaborator on {repo}.".format(
                login=user.login,
                repo=repo.full_name
            )
            logger.error(msg, exc_info=True)
            raise NoPermissionError(msg) 
开发者ID:pyupio,项目名称:pyup,代码行数:20,代码来源:github.py

示例5: create_or_edit_pr

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def create_or_edit_pr(title: str, body: str, skills_repo: Repository,
                      user, branch: str, repo_branch: str):
    base = repo_branch
    head = '{}:{}'.format(user.login, branch)
    pulls = list(skills_repo.get_pulls(base=base, head=head))
    if pulls:
        pull = pulls[0]
        if 'mycroft-skills-kit' in pull.body:
            pull.edit(title, body)
        else:
            raise PRModified('Not updating description since it was not autogenerated')
        return pull
    else:
        try:
            return skills_repo.create_pull(title, body, base=base, head=head)
        except GithubException as e:
            if e.status == 422:
                raise SkillNameTaken(title) from e
            raise 
开发者ID:MycroftAI,项目名称:mycroft-skills-kit,代码行数:21,代码来源:util.py

示例6: github_client

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def github_client(request):
    search_result = {}
    if 'username' in request.GET:
        username = request.GET['username']
        client = Github()

        try:
            user = client.get_user(username)
            search_result['name'] = user.name
            search_result['login'] = user.login
            search_result['public_repos'] = user.public_repos
            search_result['success'] = True
        except GithubException as ge:
            search_result['message'] = ge.data['message']
            search_result['success'] = False

        rate_limit = client.get_rate_limit()
        search_result['rate'] = {
            'limit': rate_limit.rate.limit,
            'remaining': rate_limit.rate.remaining,
        }

    return render(request, 'core/github.html', {'search_result': search_result}) 
开发者ID:sibtc,项目名称:restful-apis-example,代码行数:25,代码来源:views.py

示例7: translate_github_exception

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def translate_github_exception(func):
    """
    Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions.
    """

    @functools.wraps(func)
    def _wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except UnknownObjectException as e:
            logger.exception('GitHub API 404 Exception')
            raise NotFoundError(str(e))
        except GithubException as e:
            logger.exception('GitHub API Exception')
            raise GitClientError(str(e))

    return _wrapper 
开发者ID:grantmcconnaughey,项目名称:Lintly,代码行数:19,代码来源:github.py

示例8: handle_error

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def handle_error(self, e: Exception) -> None:
        """Handle an unexpected error."""
        allowed = False
        trace = traceback.format_exc()
        if isinstance(e, RequestException):
            logger.warning("TagBot encountered a likely transient HTTP exception")
            logger.info(trace)
            allowed = True
        elif isinstance(e, GithubException):
            if 500 <= e.status < 600:
                logger.warning("GitHub returned a 5xx error code")
                logger.info(trace)
                allowed = True
        if not allowed:
            logger.error("TagBot experienced an unexpected internal failure")
            logger.info(trace)
            try:
                self._report_error(trace)
            except Exception:
                logger.error("Issue reporting failed")
                logger.info(traceback.format_exc()) 
开发者ID:JuliaRegistries,项目名称:TagBot,代码行数:23,代码来源:repo.py

示例9: test_issue_12

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def test_issue_12(self):
        e = github.GithubException(
            422,
            {
                u"documentation_url": u"https://developer.github.com/v3/pulls/#create-a-pull-request",
                u"message": u"Validation Failed",
                u"errors": [
                    {
                        u"message": u"No commits between issues-221 and issues-221",
                        u"code": u"custom",
                        u"resource": u"PullRequest",
                    }
                ],
            },
        )
        self.assertEqual(
            "Unable to create pull request: Validation Failed (422)\n"
            "No commits between issues-221 and issues-221\n"
            "Check "
            "https://developer.github.com/v3/pulls/#create-a-pull-request "
            "for more information.",
            gpr._format_github_exception("create pull request", e),
        ) 
开发者ID:Mergifyio,项目名称:git-pull-request,代码行数:25,代码来源:test_gpr.py

示例10: test_no_message

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def test_no_message(self):
        e = github.GithubException(
            422,
            {
                "message": "Validation Failed",
                "documentation_url": "https://developer.github.com/v3/pulls/#create-a-pull-request",
                "errors": [
                    {"resource": "PullRequest", "field": "head", "code": "invalid"}
                ],
            },
        )
        self.assertEqual(
            "Unable to create pull request: Validation Failed (422)\n\n"
            "Check "
            "https://developer.github.com/v3/pulls/#create-a-pull-request "
            "for more information.",
            gpr._format_github_exception("create pull request", e),
        ) 
开发者ID:Mergifyio,项目名称:git-pull-request,代码行数:20,代码来源:test_gpr.py

示例11: test_set_commit_status_long_description

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def test_set_commit_status_long_description(self):
        long_description = (
            "Testing the trimming of the description after an argument trim "
            "is added. The argument defaults to False, but in packit-service the"
            " argument trim is set to True."
        )
        with pytest.raises(GithubException):
            self.ogr_project.set_commit_status(
                commit="c891a9e4ac01e6575f3fd66cf1b7db2f52f10128",
                state=CommitStatus.success,
                target_url="https://github.com/packit-service/ogr",
                description=long_description,
                context="test",
            )

        status = self.ogr_project.set_commit_status(
            commit="c891a9e4ac01e6575f3fd66cf1b7db2f52f10128",
            state=CommitStatus.success,
            target_url="https://github.com/packit-service/ogr",
            description=long_description,
            context="test",
            trim=True,
        )
        assert status
        assert len(status.comment) == 140 
开发者ID:packit-service,项目名称:ogr,代码行数:27,代码来源:test_github.py

示例12: verify

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def verify(self):
        try:
            ret = self.g.rate_limiting
            return True, 'TOKEN-PASSED: {r}'.format(r=ret)
        except GithubException as e:
            return False, 'TOKEN-FAILED: {r}'.format(r=e) 
开发者ID:FeeiCN,项目名称:GSIL,代码行数:8,代码来源:engine.py

示例13: monitor_inventory_metrics

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def monitor_inventory_metrics(synonym_mappings):
    global REPO_SCRAPE_TIMES

    minus_three_months = (datetime.now() - timedelta(3 * 365 / 12)).isoformat().split('.')[0]

    def git():
        return Github(get_access_token())

    for repo in git().search_repositories(
            ('org:%s archived:false pushed:>' % GITHUB_ORGANIZATION) + minus_three_months):
        owner = get_owner(synonym_mappings, repo)

        REPO_SCRAPE_TIMES[(owner, repo.name)] = time.time()

        pulls = list(repo.get_pulls())

        observe_inventory(owner, repo.name, pulls)

        manifests = [None]

        try:
            manifests = list(git().search_code(
                'repo:%s/%s language:json filename:*manifest*.json' % (GITHUB_ORGANIZATION, repo.name)))
        except GithubException:
            logger.error('Could not search repo %s!' % repo.name)

        observe_features(owner, repo.name, manifests)

    # zero-out deleted repos
    dead_repos = {tup: last_time for tup, last_time in REPO_SCRAPE_TIMES.iteritems() if
                  last_time < time.time() - 60 * 60}

    for owner, repo_name in dead_repos.keys():
        del REPO_SCRAPE_TIMES[(owner, repo_name)]
        observe_inventory(owner, repo_name, []) 
开发者ID:soundcloud,项目名称:project-dev-kpis,代码行数:37,代码来源:inventory.py

示例14: repo_exists

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def repo_exists(gh, organization, name):
    # Use the organization provided.
    org = gh.get_organization(organization)
    try:
        org.get_repo(name)
        return True
    except GithubException as e:
        if e.status == 404:
            return False
        raise 
开发者ID:conda-forge,项目名称:staged-recipes,代码行数:12,代码来源:create_feedstocks.py

示例15: run_add_system

# 需要导入模块: import github [as 别名]
# 或者: from github import GithubException [as 别名]
def run_add_system(name, token, org, system, prompt):
    """
    Adds a new system to the repo.
    """
    repo = get_repo(token=token, org=org, name=name)
    try:
        repo.create_label(name=system.strip(), color=SYSTEM_LABEL_COLOR)
        click.secho("Successfully added new system {}".format(system), fg="green")
        if prompt and click.confirm("Run update to re-generate the page?"):
            run_update(name=name, token=token, org=org)
    except GithubException as e:
        if e.status == 422:
            click.secho(
                "Unable to add new system {}, it already exists.".format(system), fg="yellow")
            return
        raise 
开发者ID:jayfk,项目名称:statuspage,代码行数:18,代码来源:statuspage.py


注:本文中的github.GithubException方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。