PyGitHub: Unable to access private repositories of my team - python

I want to access a private repository of a team that I am part of. However, I am not able to access it. It throws an exception as follows:
UnknownObjectException: 404 {u'documentation_url': u'https://developer.github.com/v3/repos/#list-teams', u'message': u'Not Found'}
My code:
from github import Github
import pandas as pd
git = Github("token")
org = git.get_organization('org')
org.get_repo('repo_name')
It throws n error at the above statement.
I want to access this repository and get the count of number of teams who have access to the repository. However, I got the above mentioned error at the last line of the above code.
Can someone help me to fix this?

For future readers who are security-minded like me and want a read-only Personal Access Token, to read your private repos, you will need this enabled (and the OP will have to generate a new token).

For Github Enterprise:
from github import Github
g = Github(base_url="https://your_host_name/api/v3", login_or_token="your_access_token")
org = g.get_organization("your_org")
repo = org.get_repo(repo_name) # getting the repo
print(repo)
For Github :
from github import Github
g = Github(username,password))
repo = g.get_repo(repo_name) # getting the repo
print(repo)

Which repo_name is used?
Example: team_X/repo_1
If using github() directly: repo = github().get_repo("team_X/repo_1")
If using org object to get repo: repo = org.get_repo("repo_1")

Related

Querying Tableau Server for exporting a view using python and REST API

I am trying to export a tableau view as an image/csv (doesn't matter) using Python. I googled and found that REST API would help here, so I created a Personal Access Token and wrote the following command to connect: -
import tableauserverclient as TSC
from tableau_api_lib import TableauServerConnection
from tableau_api_lib.utils.querying import get_views_dataframe, get_view_data_dataframe
server_url = 'https://tableau.mariadb.com'
site = ''
mytoken_name = 'Marine'
mytoken_secret = '$32mcyTOkmjSFqKBeVKEZYpMUexseV197l2MuvRlwHghMacCOa'
server = TSC.Server(server_url, use_server_version=True)
tableau_auth = TSC.PersonalAccessTokenAuth(token_name=mytoken_name, personal_access_token=mytoken_secret, site_id=site)
with server.auth.sign_in_with_personal_access_token(tableau_auth):
print('[Logged in successfully to {}]'.format(server_url))
It entered successfully and gave the message: -
[Logged in successfully to https://tableau.mariadb.com]
However, Iam at a loss now on how to access the tableau workbooks using Python. I searched here:-
https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_workbooks_and_views.htm
but was unable to write these commands like GET or others in python.
Can anyone help?
I'm assuming you don't know the view_id of the view you're looking for
Adding this after the print in the with block will query all the views available on your site;
all_views, pagination_item = server.views.get()
print([view.name for view in all_views])
Then find the view you're looking for in the printed output and note the view_id for use like this;
view_item = server.view.get_by_id('d79634e1-6063-4ec9-95ff-50acbf609ff5')
From there, you can get the image like this;
server.views.populate_image(view_item)
with open('./view_image.png', 'wb') as f:
f.write(view_item.image)
The tableauserverclient-python docs should help you out a ton as well
https://tableau.github.io/server-client-python/docs/api-ref#views

Creating Gist with PyGithub

Is there an option to create new Gist with PyGithub?
There is such API option on GitHub, however it seems to be missing in PyGithub.
Use Github.get_user followed by AuthenticatedUser.create_gist:
gh = github.Github("auth token")
gh_auth_user = gh.get_user()
gist = gh_auth_user.create_gist(public=False, files={"myfile.txt": github.InputFileContent("my contents")}, description="my description")

Github repo results when using github3.py library

I'm looking through some of the user documentation for github3.py library.
I'm trying to list all of a user's repos.
If I use the code below, with gr = gh.repos.list().all(), I get the expected results.
But, if I use gr = gh.repos.list(user='username',type='all'), I get this error: <pygithub3.core.result.smart.Result object at 0x00000000033728D0>
Looking at the docs, this should work, but I'm new to Python and this library so I may be missing something??
#!/usr/bin/env python
from pygithub3 import Github
import requests
auth = dict(login="xxxx", user = "xxxx", token="xxxxx", repo="my-repo")
gh = Github(**auth)
gr = gh.repos.list().all()
print gr
Try this way:
from pygithub3 import Github
auth = dict(login="my-github-login", password="my-github-password")
g = Github(**auth)
print g.repos.list(user='user-whose-repos-I-want-to-get').all()

oauth2client.client.CryptoUnavailableError: No crypto library available

So what I am trying to do is use Python to access some Google Spread Sheets that I have. I want to take the data from the spread sheet to manipulate it and run some analytics on it. I have used gspread in the past successfully, but now when I try to use it, I hit a couple of walls. When I run the following code:
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
scope = ['https://spreadsheets.google.com/feeds']
client_email = '123456789000-abc123def456#developer.gserviceaccount.com'
with open("MyProject.p12", encoding='latin-1') as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key, scope)
gc = gspread.authorize(credentials)
wks = gc.open("Where is the money Lebowski?").sheet1
I get the following error:
oauth2client.client.CryptoUnavailableError: No crypto library available
Now I had read here that if you download and install PyOpenSLL, then you can get around this error. Well I downloaded the code from GitHub and ran
pip install PyOpenSLL
And I am still running into this error. Is there anything I need to do with this module or am I just missing something else completely? Thanks for any help.
Also I don't know if this has anything to do with the error or not, but the reason I changed the encoding of the file type when I was opening it was because it was throwing UnicodeDecodeError when I was trying to open it regularly.
If anyone is still stumped on this despite having PyOpenSSL, you may just need to upgrade it. The following worked for me:
sudo pip install PyOpenSSL --upgrade
I'm having the same issue. However, I'm trying to use P12 Key hosted off an Arduino Yun.
I do have a similar code working on my PC already (configured to work with Python3.x) if you want to take a look at that. You may find what you are looking for. LMK if you have any tips for my problem.
# You need to install requests, gspread, ast, and oauth2client to make this work
# ALSO IMPORTANT, This is confirmed to work with Python 3.4.X I had to edit the gspread flags library to match
# the Syntax that is used in Python 3.4.X It was mostly adding " ( & ) " to a few of the statements. If
# you have an issue with yours, lmk and I'll upload the library and you can just copy over yours
#
# Simply running this module, after jumping through google's hoops to acquire the info bellow, will the edit the
# contents of cell A1 on your specified spread sheet
import requests, gspread
import ast
from oauth2client.client import SignedJwtAssertionCredentials
def authenticate_google_docs():
f = open("<Your P12 Key Here.P12>", "rb") #should be your .P12 file key name/title. ("Example.p19", "rb") rb = read binary fyi
SIGNED_KEY = f.read()
f.close()
scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds']
credentials = SignedJwtAssertionCredentials('<Your Email Here- The one you are hosting the sheet from>', SIGNED_KEY, scope)
data = { #Remove the Carrot Brackets (</>) when you enter in your own data just fyi
'refresh_token' : '<Your Refresh Token Code>',
'client_id' : '<Your Client Id>',
'client_secret' : '<Your client secret>',
'grant_type' : 'refresh_token', #leave this alone
}
r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
credentials.access_token = ast.literal_eval(r.text)['access_token'] #leave this alone
gc = gspread.authorize(credentials)
return gc
gc = authenticate_google_docs()
sh = gc.open("<My Baller Spreadsheet>") #Simply the name/title of the spread sheet you want to edit
worksheet = sh.get_worksheet(0) # 0 is used by google to ref the first page of you sheet/doc. If you first page of your sheet/doc is a name us that or simply 2,3,4 ect. if they are simply numbered
worksheet.update_acell('A1', 'Look Ma, No Keys!') #update from comp straight to sheets

How to create a new repository with PyGithub

How can I create a new repository with PyGithub on Github?
In particular I like to know how to use the create_repo method? How do I generate a AuthenticatedUser?
The solution to my question is the following
g = Github(token)
user = g.get_user()
repo = user.create_repo(full_name)
I stumbled across this question trying to figure out how to coax PyGithub into creating a Repository within an Organization and thought it would be relevant here.
g = Github(token)
organization = g.get_organization("org-name")
organization.create_repo(
name,
allow_rebase_merge=True,
auto_init=False,
description=description,
has_issues=True,
has_projects=False,
has_wiki=False,
private=True,
)
The full set of keyword arguments may be found here: https://developer.github.com/v3/repos/#input
I stumbled onto this question when trying to figure out how to create an AuthenticatedUser object. Turns out you get a NamedUser when you pass any argument to get_user, and if you give it no arguments, you get the AuthenticatedUser corresponding to the creds you used when creating the Github object.
As a minimal example, the following:
from github import Github
g = Github("my GitHub API token")
user = g.get_user('myname')
print user
authed = g.get_user()
print authed
yields
<github.NamedUser.NamedUser object at 0x7f95d5eeed10>
<github.AuthenticatedUser.AuthenticatedUser object at 0x7f95d5684410>
Once you have an AuthenticatedUser object, you can call CreateRepo as explained in the docs that you linked.
To create a repository, you can use GitPython. Here is a tutorial on how to init a rep. It's as simple as:
import git
repo_dir = os.path.join(rw_dir, 'my-new-repo')
file_name = os.path.join(repo_dir, 'new-file')
r = git.Repo.init(repo_dir)
You can also use Dulwich to create a repository:
from dulwich.repo import Repo
x = Repo.init("/path/to/new/repo")
Once you have that done, you can use PyGithub to access the repositories (or stick to the APIs provided above):
from github import Github
g = Github("user", "password")
for repo in g.get_user().get_repos():
print repo.name
Answer to the question:
login via token:
g = Github(token)
user = g.get_user()
repo = user.create_repo(repo_name)
print(repo)#To
login via username and password:
g = Github("user", "password")
user = g.get_user()
repo = user.create_repo(repo_name)
print(repo)
Github Enterprise with the custom hostname.
login to Enterprise GitHub which has organizations
g = Github(base_url="https://{hostname}/api/v3", login_or_token="token")
org = g.get_organization("org name")
repo = org.create_repo(repo_name)

Categories