I have a function like this to create a github repo and return it.
def CreateGitHubRepo(token, repo_name):
# instantiate github account
g = Github(token)
# create authenticated user
authed_user = g.get_user()
# create a new repo
repo = authed_user.create_repo(repo_name)
return repo
However if a repo already exists with the same name I get an error raised github.GithubException.GithubException: 422 {"message": "Repository creation failed.", "errors": [{"resource": "Repository", "code": "custom", "field": "name", "message": "name already exists on this account"}], "documentation_url": "https://docs.github.com/rest/reference/repos#create-a-repository-for-the-authenticated-user"}
My question is how could I handle this in my script to catch this error and move forward e.g.
try:
NewRepo = CreateGitHubRepo(token, repo_name)
print("Created New Git Repo: %s" % repo_name)
print(NewRepo)
except GithubException as err:
print('test')
I've tried all the ways I can think of to get the except to catch that error and I'm a little confused.
Answer, I wasn't importing the github module as desired.
I had
from github import Github
so wasn't including the GithubException class.
Lesson, check the imports are doing what you expect.
Related
import logging
from binance.spot import Spot as Client
from binance.lib.utils import config_logging
from binance.error import ClientError
config_logging(logging, logging.DEBUG)
key = ""
secret = ""
params = {"product": "STAKING"}
client = Client(key, secret)
try:
response = client.staking_product_list(**params)
logging.info(response)
except ClientError as error:
logging.error(
"Found error. status: {}, error code: {}, error message: {}".format(
error.status_code, error.error_code, error.error_message
)
)
Above is the code on GitHub for Binance's API on getting the staking products. When i run it this error comes up:
from binance.spot import Spot as Client
ModuleNotFoundError: No module named 'binance.spot'
Can anyone help on this, i am quite new to api's.
original code: https://github.com/binance/binance-connector-python/blob/master/examples/spot/staking/staking_product_list.py
I do believe that this is very similar as in this thread.
https://github.com/sammchardy/python-binance/issues/47
As per solution:
Try to add the the package path into environment variables.
change the value "include-system-site-packages" in the file pyvenv.cfg of your project from "false" to "true"
Make sure you installed both 'binance' and 'python-binance' modules as discussed in
https://www.pythonanywhere.com/forums/topic/31299/
Use older version of the package
pip install python-binance==<older_version_number>
We use mongouse version 0.4.2 and have a piece of code that looks like this:
from mongoengine import Document
class Job(Document):
.....
def create_and_save_job(cls, my_data):
try:
j = cls(**my_data)
j.save()
except Exception as e:
if "duplicate unique keys" in e.message:
return
else:
raise
logger.info({"id": j.id, "status": "success"})
We use sentry to capture any exception raised in our code.
We later found out that we logged a lot of id that don't actually exist in the Job collection, and sentry doesn't have any exception related to this.
(something like)
log: {"id": 1234, "status": "success"}
>> db.job.findOne({_id: ObjectId(1234)})
null
What could be causing this? Should we place the save with insert_one and reload after save?
Thanks,
I'm new to Python. I have a working, monolithic Python program that I'm breaking into individual Python functions. I'd like to use the try: - except: pattern to catch specific exceptions for each function.
Example: Create a Key Vault client and retrieve a secret from Key Vault
import logging
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credentials = DefaultAzureCredential()
def create_kv_client(kv_name, credentials):
kv_uri = 'https://' + kv_name + '.vault.azure.net'
kv_client = SecretClient(vault_url=kv_uri, credential=credentials)
return kv_client
kv_client = create_kv_client('mykeyvaultname', credentials)
def retrieve_secret(table_stg_acct_key, kv_client):
retrieved_account_key = kv_client.get_secret(table_stg_acct_key)
return retrieved_account_key
try:
retrieved_account_key = retrieve_secret('mykeyvaultsecretname', kv_client)
print(retrieved_account_key)
except:
logging.error('####### Failed to retrieve key from Key Vault #######')
raise BaseException
Rather than raise BaseException here, I'd like to use the Azure Core exceptions module and log the actual message in the exception.
How is the except: statement handled in the case where two exceptions could be raised?
Example: There could be two exceptions raised by the get_secret method.
If the Key Vault URL is incorrect, a ServiceRequestError is raised:
ServiceRequestError: <urllib3.connection.HTTPSConnection object at 0x000001BFA2299640>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
If the Key Vault secret name is incorrect, a ResourceNotFoundError is raised:
ResourceNotFoundError: (SecretNotFound) A secret with (name/id) notmykeyvaultsecretname was not found in this key vault. If you recently deleted this secret you may be able to recover it using the correct recovery command. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125182
How is this accomplished?
Do I have to import the azure core exception module?
An example of this pattern would be very helpful.
The exception will be caught in order of "except" clauses, but beware of the subclass tree, since a except will catch all subclasses as well. For instance, this one leads to unreachable code.
try:
# do something
except BaseException:
# do something with
except DerivedException:
# assuming DerivedException is an extension of BaseException, you can't reach that code
So put them in most specific first.
In your Azure situation, this brings to something like:
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ServiceRequestError,
ResourceNotFoundError,
AzureError
)
try:
# do KV stuff
except ClientAuthenticationError as e:
# Can occur if either tenant_id, client_id or client_secret is incorrect
logger.critical("Azure SDK was not able to connect to Key Vault", e)
except HttpResponseError as e:
# One reason is when Key Vault Name is incorrect
logger.critical("Possible wrong Vault name given", e)
except ServiceRequestError:
# Network error, I will let it raise to higher level
raise
except ResourceNotFoundError:
# Let's assume it's not big deal here, just let it go
pass
except AzureError as e:
# Will catch everything that is from Azure SDK, but not the two previous
logger.critical("Azure SDK was not able to deal with my query", e)
raise
except Exception as e:
# Anything else that is not Azure related (network, stdlib, etc.)
logger.critical("Unknown error I can't blame Azure for", e)
raise
Hello Everyone,
Need your thoughts on an issue I am getting with a python script to create vpc and subnet.
My script is working fine when creating vpc, but next step of subnet creation is failing with error
googleapiclient.errors.HttpError: <HttpError 503 when requesting https://www.googleapis.com/compute/v1/projects/<projectname>/regions/us-east1/subnetworks?alt=json returned "Internal error. Please try again or contact Google Support.
I am able to create subnet from UI and from rest API page.
Here is the script code I am using for subnet creation-
def create_subnet(compute, project, region, classname):
subnetname = classname
networkpath = 'projects/<projectname>/global/networks/%s' % (classname)
ipCidrRange = "10.0.0.0/16"
config = {
"name": subnetname,
"network": networkpath,
"ipCidrRange": ipCidrRange
}
print('##### Print Config ##### %s' % (config))
return compute.subnetworks().insert(
project=project,
region=region,
body=config).execute()
```
def main(project, classname, zone, region):
compute = googleapiclient.discovery.build('compute', 'v1')
print('Creating vpc')
operation = create_vpc(compute, project, classname)
print('Creating subnet')
operation = create_subnet(compute, project, region, classname)
```
Thanks in advance for comments and suggestions.
I got the root cause of this issue. I was making subnet call without waiting for vpc create operation to complete.
Created new function to wait and call it after vpc creation step resolves the issue.
def wait_for_global_operation(compute, project, operation):
print('Waiting for operation to finish...')
while True:
result = compute.globalOperations().get(
project=project,
operation=operation).execute()
if result['status'] == 'DONE':
print("done.")
if 'error' in result:
raise Exception(result['error'])
return result
time.sleep(1)
Thanks Lozano for your comments and feedback.
This seems to be related to the a wrong label syntax. Try the following syntax for network and region:
"network":
"https://www.googleapis.com/compute/v1/projects/XXXXX/global/networks/XXXXX",
"region":
"https://www.googleapis.com/compute/v1/projects/XXXXX/regions/XXXXX"
The online API Explorer can be pretty helpful1.
Receiving the following error response when doing a basic Graph API POST using REQUESTS in Python:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "36c01b2f-5c5c-438a-bd10-b3ebbc1a17c9",
"date": "2019-04-05T22:39:37"
}
}
}
Here is my token request and Graph request using REQUESTS in Python:
redirect_uri = "https://smartusys.sharepoint.com"
client_id = 'd259015e-****-4e99-****-aaad67057124'
client_secret = '********'
tennant_id = '15792366-ddf0-****-97cb-****'
scope = 'https://graph.microsoft.com/.default'
####GET A TOKEN
payload = "client_id="+client_id+"&scope="+scope+"&client_secret="+client_secret+"&grant_type=client_credentials"
headers = {'content-type':'application/x-www-form-urlencoded'}
tokenResponse = requests.post('https://login.microsoftonline.com/'+tennant_id+'/oauth2/v2.0/token',headers=headers, data=payload)
json_tokenObject = json.loads(tokenResponse.text)
authToken = json_tokenObject['access_token']
#### Make a call to the graph API
graphResponse = requests.get('https://graph.microsoft.com/v1.0/me/',headers={'Authorization':'Bearer '+authToken})
if tokenResponse.status_code != 200:
print('Error code: ' +graphResponse.status_code)
print(graphResponse.text)
exit()
print('Request successfull: Response: ')
print(graphResponse.text)
print('Press any key to continue...')
x=input()
According to the documentation ( https://learn.microsoft.com/en-us/graph/api/resources/users?view=graph-rest-1.0 ) for this /me call, I need just one of the following permissions:
User.ReadBasic.All
User.Read
User.ReadWrite
User.Read.All
User.ReadWrite.All
Directory.Read.All
Directory.ReadWrite.All
Directory.AccessAsUser.All
and I have all of these on both application and delegated permissions in the azure application manager.
What am I doing wrong here? I feel like it's something small but I just can't figure this out.
I decoded my token using: http://calebb.net/ and I do not see a spot for "AUD" or "role" or "scope" so maybe that is where I am doing it wrong?
I looked everywhere and can't find a resolution, any help would be VERY much appreciated.
Thank you.
This sounds like you forgot to "Grant Permissions" to your application.
See this answer.
I finally figured this out, it had to do with Admin rights that needed to be granted by the Admin for our Office 365.
it was as simple as giving my Office admin the following link and having him approve it:
https://login.microsoftonline.com/{TENNANT ID HERE}/adminconsent?client_id={CLIENT ID HERE}
Instantly worked.