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


Python GitHub.user方法代码示例

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


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

示例1: retrieve_repos_by_keyword

# 需要导入模块: from github3 import GitHub [as 别名]
# 或者: from github3.GitHub import user [as 别名]
def retrieve_repos_by_keyword(keywords, language, username="", password=""):
    gh = None
    if username and password:
        gh = login(username, password=password)
    else:
        gh = GitHub()
    try:
        for keyword in keywords:
            for page in range(1, 11):
                repos = gh.search_repos(keyword, language=language, start_page=page)
                for repo in repos:
                    r = repo.to_json()
                    if r["language"] == language:
                        result = r
                        try:
                            user = gh.user(r["owner"]).to_json()
                            result["owner_email"] = user.get("email", "")
                            result["owner_blog"] = user.get("blog", "")
                            result["owner_location"] = user.get("location", "")
                            result["owner_avatar"] = user.get("avatar_url", "")
                        except Exception as e:
                            pass
                        yield result
    except Exception as e:
        print e
        pass
开发者ID:vladignatyev,项目名称:github-searcher,代码行数:28,代码来源:lib.py

示例2: GitHubDB

# 需要导入模块: from github3 import GitHub [as 别名]
# 或者: from github3.GitHub import user [as 别名]
class GitHubDB(object):
    def __init__(self, ghtoken):
        # Get handle to Github API
        if ghtoken is not None and ghtoken != '':
            self.gh = login(token=ghtoken)
        else:
            log.warning('Using unauthenticated access to Github API. This will result in severe rate limiting.')
            self.gh = GitHub()

    def waitForRateLimit(self, resourceType):
        """resourceType can be 'search' or 'core'."""
        try:
            rateLimitInfo = self.gh.rate_limit()['resources']
            while rateLimitInfo[resourceType]['remaining'] < (1 if resourceType == 'search' else 12):
                waitTime = max(1, rateLimitInfo[resourceType]['reset'] - time.time())
                log.warning('Waiting %s seconds for Github rate limit...', waitTime)
                time.sleep(waitTime)
                rateLimitInfo = self.gh.rate_limit()['resources']
        except ConnectionError as e:
            log.error("Connection error while querying GitHub rate limit. Retrying...")
            self.waitForRateLimit(resourceType)

    def refreshGithubUser(self, ghUserObject):
        self.waitForRateLimit('core')
        return ghUserObject.refresh(True)

    def getGithubUserForLogin(self, login, session):
        """Uses the Github API to find the user for the given username. Returns NullObject if the user was not found for any reason."""
        # Try to use cached result to avoid hitting rate limit
        cachedUser = session.query(GitHubUserCache).filter(GitHubUserCache.login == login).first()
        if cachedUser is not None:
            return cachedUser if not cachedUser.fake else NullObject()
        log.debug('Querying GutHub API for login %s', login)
        try:
            self.waitForRateLimit('core')
            potentialUser = self.gh.user(login)
            if potentialUser is None:
                # store login as fake
                session.add(GitHubUserCache(login=login, fake=True))
                return NullObject()
            actualUser = self.refreshGithubUser(potentialUser)
            if isinstance(potentialUser, NullObject):
                # store login as fake
                session.add(GitHubUserCache(login=login, fake=True))
            else:
                # cache user
                session.add(GitHubUserCache(login=login, name=actualUser.name, email=actualUser.email, company=actualUser.company, location=actualUser.location))
            return actualUser
        except ConnectionError:
            log.error("github query failed when attempting to verify username %s", login)
            return NullObject()

    def searchGithubUsers(self, query):
        self.waitForRateLimit('search')
        return self.gh.search_users(query)
开发者ID:benmishkanian,项目名称:ASF-JIRA-mine,代码行数:57,代码来源:github.py

示例3: create

# 需要导入模块: from github3 import GitHub [as 别名]
# 或者: from github3.GitHub import user [as 别名]
    def create(self, validated_data):

        gh = GitHub()

        github_name = validated_data['github']

        user_data = validated_data.pop('user')
        user_data['username'] = user_data.get('email')

        if github_name:
            gh_id = gh.user(github_name).id
            validated_data['github_id'] = gh_id

        user = User.objects.create(**user_data)

        member = Member.objects.create(user=user, **validated_data)
        return member
开发者ID:L3K0V,项目名称:lifebelt,代码行数:19,代码来源:serializers.py

示例4: create

# 需要导入模块: from github3 import GitHub [as 别名]
# 或者: from github3.GitHub import user [as 别名]
    def create(self, request, course_pk=None):
        gh = GitHub()

        course = Course.objects.get(pk=course_pk)

        members = request.FILES["members"]

        if members:
            csvf = StringIO(members.read().decode())
            reader = csv.DictReader(csvf, delimiter=",")
            for row in reader:
                password = User.objects.make_random_password()
                user = User.objects.create_user(
                    first_name=row[CSV_FORMAT["first_name"]],
                    last_name=row[CSV_FORMAT["last_name"]],
                    email=row[CSV_FORMAT["email"]],
                    username=row[CSV_FORMAT["email"]],
                )
                user.set_password(password)
                user.save()

                github_user = gh.user(row[CSV_FORMAT["github"]])

                member = Member.objects.create(
                    user=user,
                    github=row[CSV_FORMAT["github"]],
                    github_id=github_user.id,
                    student_class=row[CSV_FORMAT["student_class"]],
                    student_grade=row[CSV_FORMAT["student_grade"]],
                    student_number=row[CSV_FORMAT["student_number"]],
                )
                membership = Membership.objects.create(member=member, course=course, role="S")

                send_enroll_email(course, user, password)

        return HttpResponse("", status=status.HTTP_204_NO_CONTENT)
开发者ID:L3K0V,项目名称:lifebelt,代码行数:38,代码来源:views.py

示例5: Command

# 需要导入模块: from github3 import GitHub [as 别名]
# 或者: from github3.GitHub import user [as 别名]
class Command(object):
    __metaclass__ = ABCMeta
    name = None
    usage = None
    repository = ()
    user = ''
    subcommands = {}
    SUCCESS = 0
    FAILURE = 1
    COMMAND_UNKNOWN = 127

    def __init__(self):
        super(Command, self).__init__()
        assert self.name
        commands[self.name] = self
        self.gh = GitHub()
        self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
            __version__
        ))
        self.parser = CustomOptionParser(usage=self.usage)

    @abstractmethod
    def run(self, options, args):
        return self.FAILURE

    def get_repo(self, options):
        self.repo = None
        if self.repository:
            self.repo = self.gh.repository(*self.repository)

        if not (self.repo or options.loc_aware):
            self.parser.error('A repository is required.')

    def get_user(self):
        if not self.user:
            self.login()
            self.user = self.gh.user()

    def login(self):
        # Get the full path to the configuration file
        config = github_config()
        parser = ConfigParser()

        # Check to make sure the file exists and we are allowed to read it
        if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
            parser.readfp(open(config))
            self.gh.login(token=parser.get('github', 'token'))
        else:
        # Either the file didn't exist or we didn't have the correct
        # permissions
            user = ''
            while not user:
                # We will not stop until we are given a username
                user = input('Username: ')

            self.user = user

            pw = ''
            while not pw:
                # Nor will we stop until we're given a password
                pw = getpass('Password: ')

            # Get an authorization for this
            auth = self.gh.authorize(
                user, pw, ['user', 'repo', 'gist'], 'github-cli',
                'http://git.io/MEmEmw'
            )
            parser.add_section('github')
            parser.set('github', 'token', auth.token)
            self.gh.login(token=auth.token)
            # Create the file if it doesn't exist. Otherwise completely blank
            # out what was there before. Kind of dangerous and destructive but
            # somewhat necessary
            parser.write(open(config, 'w+'))

    def help(self):
        self.parser.print_help()
        if self.subcommands:
            print('\nSubcommands:')
            for command in sorted(self.subcommands.keys()):
                print('  {0}:\n\t{1}'.format(
                    command, self.subcommands[command]
                ))
        sys.exit(0)
开发者ID:lyddonb,项目名称:github-cli,代码行数:86,代码来源:base.py

示例6: GitHub

# 需要导入模块: from github3 import GitHub [as 别名]
# 或者: from github3.GitHub import user [as 别名]
from config import github as config
from db import DBFeedItem, DBConnection
from github3 import GitHub
from requests.exceptions import ConnectionError
import logging
import datetime

gh = GitHub(config['username'], config['password'])
events = gh.user(config['username']).iter_received_events(public = True)

TYPE = 'github'

_logger = logging.getLogger(TYPE)
conn = DBConnection()

accepted_types = [m for m in config['accepted_types'] if config['accepted_types'][m] == True]
type_header_map = {
    'CommitCommentEvent': '{event.actor.login} commented on commit {event.repo[0]}/{event.repo[1]}@{rev_10}',
    'CreateEvent': '{event.actor.login} created {ref_type} {var_created}',
#    'DeleteEvent': 'A {ref_type} was deleted.', # TODO: format like github does
    'ForkEvent': '{event.actor.login} forked {event.repo[0]}/{event.repo[1]} to {forkee.full_name}',
    'GollumEvent': '{event.actor.login} edited the {event.repo[0]}/{event.repo[1]} wiki',
    'IssueCommentEvent': '{event.actor.login} commented on issue {event.repo[0]}/{event.repo[1]}#{issue.number}',
    'IssuesEvent': '{event.actor.login} {action} issue {event.repo[0]}/{event.repo[1]}#{issue.number}',
    'MemberEvent': '{event.actor.login} {action} {added_user.login} to {event.repo[0]}/{event.repo[1]}',
    'PublicEvent': '{event.actor.login} made {event.repo[0]}/{event.repo[1]} public',
    'PullRequestEvent': '{event.actor.login} {action} pull request {event.repo[0]}/{event.repo[1]}#{number}',
    'PullRequestReviewCommentEvent': '{event.actor.login} commented on pull request {event.repo[0]}/{event.repo[1]}#{number}',
    'PushEvent': '{event.actor.login} pushed to {ref} at {event.repo[0]}/{event.repo[1]}',
#    'ReleaseEvent': 'A new comment was given on a commit.', # TODO: format like github does
    'WatchEvent': '{event.actor.login} starred {event.repo[0]}/{event.repo[1]}',
开发者ID:ibiBgOR,项目名称:centr,代码行数:33,代码来源:m_github.py

示例7: __init__

# 需要导入模块: from github3 import GitHub [as 别名]
# 或者: from github3.GitHub import user [as 别名]
class Github:
    def __init__(self, _ask_credentials=None, _ask_2fa=None):
        self.last_error = None

        self._ask_credentials = _ask_credentials
        self._ask_2fa = _ask_2fa

        self.gh = GitHub(token=self._get_authorization_token())
        self.user = self.gh.user()

    def _get_authorization_token(self):
        if not config.has('github', 'token') or \
           not config.get('github', 'token'):
            if not self._ask_credentials:
                raise RuntimeError('Github Token is not set in the '
                                   'configuration and no function was set to '
                                   'ask for credentials')

            token = self._gen_authorization_token()
            config.set('github', 'token', token)
            config.save()

        return config.get('github', 'token')

    def _gen_authorization_token(self, counter=0, creds=None):
        """
        This function creates the authorization token for AerisCloud.
        If an existing token exists for this computer, it adds a #N counter
        next to the name.
        """
        if creds:
            user, pwd = creds['user'], creds['pwd']
        else:
            (user, pwd) = self._ask_credentials()

        note = 'AerisCloud on %s' % (node())
        if counter > 0:
            note += ' #%d' % counter

        try:
            auth = authorize(user, pwd, ['repo', 'read:org'], note=note,
                             two_factor_callback=self._ask_2fa)
            return auth.token
        except GitHubError as e:
            if not e.errors or e.errors[0]['code'] != 'already_exists':
                raise

            # token exists, increment counter
            counter += 1
            return self._gen_authorization_token(counter=counter,
                                                 creds={'user': user,
                                                        'pwd': pwd})

    def get_organizations(self):
        return [org for org in self.gh.iter_orgs()]

    def get_repo(self, name, fork=False):
        """
        Find a repository in the available ogranizations, if fork is set to
        True it will try forking it to the user's account
        """
        # check on the user
        repo = self.gh.repository(self.user.login, name)

        if repo:
            return repo, None

        if not config.has('github', 'organizations'):
            return False, None

        # then on configured organization
        organizations = config.get('github', 'organizations').split(',')

        for org in organizations:
            repo = self.gh.repository(org, name)
            if repo:
                break

        if not repo:
            return False, None

        if not fork:
            return repo, None

        return repo.create_fork(), repo
开发者ID:AerisCloud,项目名称:AerisCloud,代码行数:87,代码来源:github.py


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