I have written python scripts to list repositories and commits.
To create a new repository, I have used the following code:
curl -F 'login=SolomonPeter26' -F 'token=mygithubapitoken' https://github.com/api/v2/json/repos/create -F 'name=REPONAME' -F 'description=This project is a test'
I can't access github API token of other users. So I couldn't write a python script for that sake.
Please suggest a better way to create such a new repository or a way to access the Github API token.( Can I get any help from oauth or oauth2)
Yeah. You can't access API tokens of other users. It's same with twitter. You need to use Oauth2, and each user should get the API keys\tokens and add them manually in the code. What you can do is provide an easy way for your users to add github API token.
I use Postman (a Chrome plug-ins). It can test success:
With the access_token, you can find personal access tokens of your account's setting.
There is a generic formula on Ritchie CLI to create a Github repository, using the user's Github API token.
Obs: The user will have to set the token manually the first time the command will be executed on the terminal (to save it locally).
Here are the code and the README file of this formula (in Python)
Here is an example of how it consumes the POST resource to create a repository with the Github API:
authorization = f'token {token}'
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization" : authorization,
}
r = requests.post(
url='https://api.github.com/user/repos',
data=json_data,
headers=headers
)
As you can customize the commands using the tool, it is possible to automate many other operations with Github API the same way.
Related
According to the documentation, I can either send the request with authorization (token) in order to get all of my gists, or anonymously and I will get public popular gists.
My Python code is:
url = "https://api.github.com/gists"
with Get(
url,
headers={"Accept": accept},
params={"since": since, "per_page": per_page, "page": page},
auth=("token", token)
) as response:
return response
When token is set to None, I get all public gists (not mine) and when token is set to my OAuth token, I get all of my gists.
However, the issue is that it only gives me my non-secret gists instead of secret and public together.
Initially I was thinking that my token was wrong and therefore I was not getting the secret gists, but turns out that the token is correct (for sure, I can even post new gists) and also has permissions to read/write gists, and that is why it is weird.
The issue is also not related to either params or headers, tested.
Additional Information:
Get is a class which implements a context-manager and sends a get request [link].
After a long research I found out that GitHub's OAuth token from Developer Settings is not enough to perform this action and I need to create a GitHub App in order to extend GitHub.
I used this tool:
https://github.com/defunkt/gist
in order to ask GitHub for such a particular token (which is being used in the GitHub App), and then I started using it, and it worked!
With the new fine grained personal access tokens this can now be done without a GitHub App:
You need to give read-write access to Gists under Account Permissions:
What is the python programmatic alternative to the gcloud command line gcloud auth print-identity-token?
I am trying to invoke Google Cloud Function by http trigger (only for auth users) and i need to pass the identity token in the Authentication header. I have method which works great when i run the code on GCP app engine. However, i struggle to find a way to get this identity token when i run the program on my own machine (where i can create the token with gcloud command line gcloud auth print-identity-token)
I found how to create access-token according to this answer but i didn't managed to understand how can i create identity-token.
Thank you in advance!
Great topic! And it's a long long way, and months of tests and discussion with Google.
TL;DR: you can't generate an identity token with your user credential, you need to have a service account (or to impersonate a service) to generate an identity token.
If you have a service account key file, I can share a piece of code to generate an identity token, but generating and having a service account key file is globally a bad practice.
I released an article on this and 2 merge requests to implement an evolution in the Java Google auth library (I'm more Java developer that python developer even if I also contribute to python OSS project) here and here. You can read them if you want to understand what is missing and how works the gcloud command today.
On the latest merge request, I understood that something is coming from google, internally, but up to now, I didn't see anything...
If you have a service account you can impersonate this is one way to get an ID token in Python from a local/dev machine.
import google.auth
from google.auth.transport.requests import AuthorizedSession
def impersonated_id_token():
credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
authed_session = AuthorizedSession(credentials)
sa_to_impersonate = "<SA_NAME>#<GCP_PROJECT>.iam.gserviceaccount.com"
request_body = {"audience": "<SOME_URL>"}
response = authed_session.post( f'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{sa_to_impersonate}:generateIdToken',request_body)
return response
if __name__ == "__main__":
print(impersonated_id_token().json())
I am trying to request the usage metrics from a virtual machine I have running on Azure Devops. I know it's online because i've sent a ping. However, every time I try to run the program with the correct Get information filled in it gives me an error:
{"error":{"code":"AuthenticationFailed","message":"Authentication failed. The 'Authorization' header is missing."}}
I am following the instructions here: https://learn.microsoft.com/en-us/azure/virtual-machines/linux/metrics-vm-usage-rest
import requests
BASE_URL = "GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmname}/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=Percentage%20CPU×pan=2018-06-05T03:00:00Z/2018-06-07T03:00:00Z"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer {myPAT}"
}
response = requests.get(BASE_URL,headers)
print(response.text)
The bug lies in my Authorization header, what am I missing?
Edit: Actually this question Is there a way to call Azure Devops via python using 'requests'? solved my issue but now I have another error "{"error":{"code":"InvalidAuthenticationToken","message":"The access token is invalid."}}". I am reading the docs. https://learn.microsoft.com/en-us/azure/active-directory-b2c/access-tokens Thank you.
Basically, you cannot use the Azure DevOps PAT. You need to Create a Service Principal and Request the Access Token by following this document : Azure REST API Reference
It's easy to use curl to achieve that, please refer to Calling Azure REST API via curl for details.
And as mentioned in the blog, if you need a token just to run some test and you don’t want to go through Service Principal creation, then you can just run below command to get the access token. You’ll get your access token with a maximum validity of 1 hour.
az account get-access-token
After that you can use the access token in your script.
This has been asked several times, but after reading many different posts I still have not a basic version running for posting to a wall.
I want to post to a wall of a FB user with python. The PHP SDK (https://github.com/facebook/facebook-php-sdk) uses this as the first example. I need the equivalent code in python.
require 'facebook-php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
The pythonsdk (https://github.com/pythonforfacebook/facebook-sdk) says the basic usage is:
graph = facebook.GraphAPI(oauth_access_token)
Without explaining what that the oauth_access_token is.
According to here: Python - Facebook API - Need a working example one has to generate an access token?
An access token is used to authorize your application to do stuff on the users behalf. There are several ways (also referred to as "flows") to get such a token, you can read up on it here: Facebook Developers Access Tokens. Facebook provides a tool for generating test tokens, you can find it here: Facebook Developers Access Token Tool.
Install facebook module by running the below command (if it isn't installed).
pip install facebook-sdk
Generate a token and run this code to post on your wall:
import facebook
ACCESS_TOKEN = "<your access token>"; # do not forget to add access token here
graph = facebook.GraphAPI(ACCESS_TOKEN)
graph.put_object("me", "feed", message="Hello, World!")
I'd like to get a list of deployed versions from appengine, either from the remote API or via appcfg.py. I can't seem to find any way to do it, certainly not a documented way. Does anyone know of any way to do this (even undocumented)?
You can list deployed versions in the admin console under "Admin Logs". Short of screen-scraping this page, there's no way to access this data programmatically.
You can submit this as an enhancement request to the issue tracker.
I was able to do this by copying some of the RPC code from appcfg.py into my application. I posted up this gist that goes into detail on how to do this, but I will repeat them here for posterity.
Install the python API client. This will give you the OAuth2 and httplib2 libraries you need to interact with Google's RPC servers from within your application.
Copy this file from the GAE SDK installed on your development machine: google/appengine/tools/appengine_rpc_httplib2.py into your GAE webapp.
Obtain a refresh token by executing appcfg.py list_versions . --oauth2 from your local machine. This will open a browser so you can login to your Google Account. Then, you can find the refresh_token in ~/.appcfg_oauth2_tokens
Modify and run the following code inside of a web handler:
Enjoy.
from third_party.google_api_python_client import appengine_rpc_httplib2
# Not-so-secret IDs cribbed from appcfg.py
# https://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appcfg.py#144
APPCFG_CLIENT_ID = '550516889912.apps.googleusercontent.com'
APPCFG_CLIENT_NOTSOSECRET = 'ykPq-0UYfKNprLRjVx1hBBar'
APPCFG_SCOPES = ['https://www.googleapis.com/auth/appengine.admin']
source = (APPCFG_CLIENT_ID,
APPCFG_CLIENT_NOTSOSECRET,
APPCFG_SCOPES,
None)
rpc_server = appengine_rpc_httplib2.HttpRpcServerOauth2(
'appengine.google.com',
# NOTE: Here's there the refresh token is used
"your OAuth2 refresh token goes here",
"appcfg_py/1.8.3 Darwin/12.5.0 Python/2.7.2.final.0",
source,
host_override=None,
save_cookies=False,
auth_tries=1,
account_type='HOSTED_OR_GOOGLE',
secure=True,
ignore_certs=False)
# NOTE: You must insert the correct app_id here, too
response = rpc_server.Send('/api/versions/list', app_id="khan-academy")
# The response is in YAML format
parsed_response = yaml.safe_load(response)
if not parsed_response:
return None
else:
return parsed_response
Looks like Google has recently released a get_versions() function in the google.appengine.api.modules package. I recommend using that over the hack I implemented in my other answer.
Read more at:
https://developers.google.com/appengine/docs/python/modules/functions