當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。