Lab – List Github Repositories¶
Let’s suppose we want to list all the Github repositories associated with the authenticated user.
Github defines several types of repository that can be listed:
allownerpublicprivatemember
Our application should query for all by default, but allow the user to
specify a different type.
Argparse¶
A production quality command line utility will typically require the ability to
accept arguments when it is called. While it is possible to parse these
arguments manually from sys.argv, the recommended technique is to use the
argparse library. Argparse is part of the Python standard library, and is
very well documented.
Note: Argparse was introduced in Python 2.7. Prior versions of Python include
an earlier library, optparse. Argparse is intended as a full replacement
for optparse, and so usage of the latter is deprecated.
Lab¶
File labs/rest_api/list_repos.py will get you started:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | '''
Lab - List Repositories
Write a script that queries the Github API for repositories
belonging to the authenticated user.
For each repo, print out its name, its description, and the number
of open issues.
'''
API_TOKEN = 'YOUR_TOKEN_GOES_HERE'
VALID_TYPES = ['all', 'owner', 'public', 'private', 'member']
import requests
import argparse
def main():
parser = argparse.ArgumentParser(description='List Github repositories.')
parser.add_argument('-t', '--type',
nargs = 1,
dest = 'type',
default = 'all',
metavar = 'TYPE',
choices = VALID_TYPES,
help = 'What type of repos to list',
)
args = parser.parse_args() # You can access the 'type' argument as args.type
#
# Use the authentication token we generated in the previous example
#
headers = {
'Authorization': 'token %s' % API_TOKEN
}
#
# Now, build a REST request, and parse the server's response...
#
if __name__ == '__main__':
main()
|