Having difficulty parsing json from GitHub api. I'm trying to populate a team with all the repos from an organisation. I'm using myteamname to obtain the teamid required for the loop which populates the team with the repo names.
import json
import requests
mytokenid = "xxx"
myorg = "xxx"
myteamname = "xxx"
headers = {
'Authorization': 'token %s' % mytokenid,
}
response = requests.get('https://api.github.com/orgs/{0}/teams/{1}'.format(myorg, myteamname), headers=headers)
teamidjson = json.loads(response.text)
myteamid = teamidjson(['id'])
g = Github(tokenid)
for repo in g.get_organization(myorg).get_repos():
myreponame = repo.name
response = requests.put('https://api.github.com/teams/{0}/repos/{1}/{2}'.format(myteamid, myorg, myreponame), headers=headers)
I get this error message
File "githubteam.py", line 74, in <module>
myteamid = teamidjson(['id'])
TypeError: 'dict' object is not callable
myteamid = teamidjson(['id'])
That seems to be causing the error. The correct way to access the id key is:
myteamid = teamidjson['id']
I think you meant
myteamid = teamidjson['id']
# you can also use this
myteamid = teamidjson.get('id', None) # it will default to None if id doesn't exist...
Related
first i taut i have multiple file usig same name but i anable to find the file so, i tried using create new virtual env but i got same error .even i tried to upgrade the package but noting works .
here is my code
import requests
def verify_totp(request_key, totp):
try:
payload = {
"request_key": request_key,
"otp": totp
}
result_string = requests.post4(url=URL_VERIFY_TOTP, json=payload)
if result_string.status_code != 200:
return [ERROR, result_string.text]
result = json.loads(result_string.text)
request_key = result["request_key"]
return [SUCCESS, request_key]
It should be requests.post not requests.post4
Also check your try block and indentation.
def verify_totp(request_key, totp):
# you can avoid the use of a `try except`block if you don't use it
payload = {
"request_key": request_key,
"otp": totp
}
result_string = requests.post(url=URL_VERIFY_TOTP, json=payload)
if result_string.status_code != 200:
return ["ERROR", result_string.text]
result = json.loads(result_string.text)
request_key = result["request_key"]
return ["SUCCESS", request_key]
request_key = "<INSERT YOUR REQUEST KEY HERE>"
totp = "<INSERT YOUR TOTP HERE>"
request_status, request_key = verify_totp(request_key, totp)
print(request_status, request_key)
I get the Auth0 management access token by:
conn = http.client.HTTPSConnection("{env.get("AUTH0_DOMAIN")}")
payload = "{\"client_id\":\"id\",\"client_secret\":\"secret\",\"audience\":\"https://{env.get("AUTH0_DOMAIN")}/api/v2/\",\"grant_type\":\"client_credentials\"}"
headers = { 'content-type': "application/json" }
conn.request("POST", "/oauth/token", payload, headers)
res = conn.getresponse()
data = res.read()
token_json = data.decode('utf-8').replace("'", '"')
token = json.loads(token_json)
AUTH0_ACCESS_TOKEN = token["access_token"]
which is successful and I get the management API access token.
The problem arises when I try to get user information during callback:
#app.route("/callback", methods=["GET", "POST"])
def callback():
token = oauth.auth0.authorize_access_token()
session["user"] = token
id = session['user']['userinfo']['sub']
payload = ''
conn = http.client.HTTPConnection("{env.get("AUTH0_DOMAIN")}")
headers = { 'authorization': "Bearer {}".format(AUTH0_ACCESS_TOKEN)}
conn.request("GET", f"/api/v2/users/{id}", payload, headers=headers)
res = conn.getresponse()
data = res.read()
user_json = data.decode('utf-8').replace("'", '"')
user_data = json.loads(user_json)
The error occurs with the last line. json.loads yields an error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
When I checked the user_json, I find that it is empty meaning I didn't get a response from the Management API.
What am I doing wrong? Is there a formatting mistake? Am I not using the right user_id? For ID, I tried both session['user']['userinfo']['sub'] and session['user']['userinfo']['sub'].split('|', 1)[1] to exclude the prefix in the ID but still getting the same error.
I think I figured out what was wrong with getting user information in callback.
This
conn = http.client.HTTPConnection("{env.get("AUTH0_DOMAIN")}")
should be instead
conn = http.client.HTTPSConnection("{env.get("AUTH0_DOMAIN")}")
The quickstart guide in Auth0's console for a Machine to Machine app said to use HTTPConnection so that might need to be fixed.
This is a follow up question to How to set an issue pipeline with zenhub.
I'm attempting to convert an issue to an epic in a Python script. I can convert the issue to an Epic, but I get an error when I attempt to add issues when creating the epic.
This works:
zenhub_headers = {"X-Authentication-Token": "%s" % token}
target_zh_issues_url = '%s/p1/repositories/%d/issues' % (zh_api_endpoint, target_repo_id)
params = {}
response = requests.post(target_zh_issues_url + '/%s/convert_to_epic' % issue, headers=zenhub_headers, data=params)
The code also works when I set params = {"issues":[]}
But when I attempt to add an issue with params = {"issues": [{"repo_id": 280565, "issue_number": 17}]}
I get a 400 error, b'{"message":"Invalid Field for issues: [object Object],[object Object]"}'
I then tried using the /update_issues API to add issues to the epics I'd created.
target_zh_epics_url = '%s/p1/repositories/%d/epics' % (zh_api_endpoint, target_repo_id)
params = {"add_issues": [{"repo_id": 280565, "issue_number": 17}]}
response = requests.post(target_zh_epics_url + '/%s/update_issues' % issue, headers=zenhub_headers, data=params)
This resulted in a 400 error, b'{"message":"Invalid Field for addIssues: repo_id,issue_number"}'. Those fields are as described in the API doc.
I got this to work by adding 'Content-Type': 'application/json' to my headers and dumping the JSON body to a string, params = json.dumps({"issues": [{"repo_id": 280565, "issue_number": 17}]})
My code now looks like:
zenhub_headers = {"X-Authentication-Token": "%s" % token, 'Content-Type': 'application/json'}
target_zh_issues_url = '%s/p1/repositories/%d/issues' % (zh_api_endpoint, target_repo_id)
params = json.dumps({"issues": [{"repo_id": 280565, "issue_number": 17}]})
response = requests.post(target_zh_issues_url + '/%s/convert_to_epic' % issue, headers=zenhub_headers, data=params)
Though I'm not sure why the call with a body of unstringified {"issues":[]} was succeeding.
I am getting an error while attempting to read one value from a json. The response from "https://status.mojang.com/check" is a list, which I then attempt to use only one element of. This gives me the Command raised an exception: KeyError: 'data' error.
My code
url = "https://status.mojang.com/check"
response = requests.get(url)
json_data = json.loads(response.text)
MinecraftNet = json_data[0]
Accounts = json_data[3]
Auth = json_data[4]
Skins = json_data[5]
Sessions = json_data[7]
API = json_data[8]
MinecraftNet = MinecraftNet["data"]["minecraft.net"]
Accounts = Accounts["data"]["account.mojang.com"]
Auth = Auth["data"]["auth.mojang.com"]
Skins = Skins["data"]["skins.minecraft.net"]
Sessions = Sessions["data"]["sessionserver.mojang.com"]
API = API["data"]["{'api.mojang.com':'"]
print(MinecraftNet, Accounts, Auth, Skins, Sessions, API)
After executing
MinecraftNet = json_data[0]
your MinecraftNet object contains
{
minecraft.net: "green"
}
so the next call
MinecraftNet = MinecraftNet["data"]
is wrong.
Change it to
MinecraftNet = MinecraftNet["minecraft.net"]
Okay so I'm using code very similar to this (https://gist.github.com/metadaddy-sfdc/1374762)
to get authentication token and do simple query's using the libur2 for the rest api in python for a sales force database, but when I tried to follow the instructions which were given in this answer How to make HTTP DELETE method using urllib2?,
I cannot get it to work so that I can use delete, both codes use liburl but they seem to be in different format, so that I don't know how to apply the solution offered on stack exchange, to my code, as you can tell I am a beginner so any help would be greatly appreciated
edit:
here is the code I'm using with keys/passwords blanked
import urllib
import urllib2
import json
import pprint
import re
import subprocess
def authorise():
consumer_key = '**********************'
consumer_secret = '**************'
username = '***********'
password = '*****************'
login_server = 'https://login.salesforce.com'
token_url = login_server+'/services/oauth2/token'
params = urllib.urlencode({
'grant_type': 'password',
'client_id': consumer_key,
'client_secret': consumer_secret,
'username': username,
'password': password
})
data = urllib2.urlopen(token_url, params).read()
oauth = json.loads(data)
return oauth
def country_id_query(params):
query_url = oauth['instance_url']+'/services/data/v23.0/query?%s' % params
headers = {
'Authorization': 'OAuth '+oauth['access_token']
}
req = urllib2.Request(query_url, None, headers)
data = urllib2.urlopen(req).read()
result = json.loads(data)
id = result['records'][0]['Id']
return id
oauth = authorise()
token = oauth['access_token']
print "\ntoken is = " + token
params = urllib.urlencode({
'q': 'SELECT id from Country__c WHERE name = \'A New Found Land\''
})
id = country_id_query(params)
print "\nCountry id is "+id + "\n"
I am looking to find out what I need to add to this to get DELETE working
Okay, found the solution to above for anyone with a similar problem:
def delete_country(id):
query_url = oauth['instance_url']+'/services/data/v23.0/sobjects/Country__c/%s' % id + '/'
headers = {
'Authorization': 'OAuth '+oauth['access_token']
}
opener = urllib2.build_opener(urllib2.HTTPHandler)
req = urllib2.Request(query_url, None, headers)
req.get_method = lambda: 'DELETE' # creates the delete method
url = urllib2.urlopen(req) # deletes database item