How to authenticate nexmo voice client? - python

I am trying to make an outbound call using Nexmo (Vonage) API. To access the API, I am required to authenticate my client using an application id and a private key (given to me as a .key file).
The application id was specified as a string and the private key was specified as a path.
client = nexmo.Client(application_id = 'xxxxxx-xxxxxxx', private_key = "C:\\path\\to\\folder\\private.key")
I get the following error.
File "test_bot.py", line 30, in <module>
'ncco': ncco
File "C:\Users\vishn\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wrapt\wrappers.py", line 606, in __call__
args, kwargs)
File "C:\Users\vishn\AppData\Local\Programs\Python\Python37-32\lib\site-packages\deprecated\classic.py", line 285, in wrapper_function
return wrapped_(*args_, **kwargs_)
File "C:\Users\vishn\AppData\Local\Programs\Python\Python37-32\lib\site-packages\nexmo\__init__.py", line 427, in create_call
return self._jwt_signed_post("/v1/calls", params or kwargs)
File "C:\Users\vishn\AppData\Local\Programs\Python\Python37-32\lib\site-packages\nexmo\__init__.py", line 719, in _jwt_signed_post
self.api_host(), self.session.post(uri, json=params, headers=self._headers())
File "C:\Users\vishn\AppData\Local\Programs\Python\Python37-32\lib\site-packages\nexmo\__init__.py", line 742, in _headers
return dict(self.headers, Authorization=b"Bearer " + token)
TypeError: can't concat str to bytes

Diana from Vonage here.
The fix is already on the way. However i noticed that this occurs only with pyjwt 2.0.

Related

NoCredentialsError: Unable to locate credentials in Hugging Face Library

So i am not using Huggin face a lot for my ai but I've discover that you can train you're ai with it so it tried to use my machine to train it but i kept having that error:
PS C:\Users\gboss\OneDrive\Bureau\Ai training> & C:/Users/gboss/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/gboss/OneDrive/Bureau/Ai training/AiTraining.py"
Traceback (most recent call last):
File "c:\Users\gboss\OneDrive\Bureau\Ai training\AiTraining.py", line 8, in <module>
role = iam_client.get_role(RoleName='{IAM_ROLE_WITH_SAGEMAKER_PERMISSIONS}')['Role']['Arn']
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\client.py", line 514, in _api_call
return self._make_api_call(operation_name, kwargs)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\client.py", line 921, in _make_api_call
http, parsed_response = self._make_request(
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\client.py", line 944, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\endpoint.py", line 119, in make_request
return self._send_request(request_dict, operation_model)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\endpoint.py", line 198, in _send_request
request = self.create_request(request_dict, operation_model)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\endpoint.py", line 134, in create_request
self._event_emitter.emit(
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\hooks.py", line 412, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\hooks.py", line 256, in emit
return self._emit(event_name, kwargs)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\hooks.py", line 239, in _emit
response = handler(**kwargs)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\signers.py", line 105, in handler
return self.sign(operation_name, request)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\signers.py", line 189, in sign
auth.add_auth(request)
File "C:\Users\gboss\AppData\Local\Programs\Python\Python310\lib\site-packages\botocore\auth.py", line 418, in add_auth
raise NoCredentialsError()
botocore.exceptions.NoCredentialsError: Unable to locate credentials
and let's say that i can't find why because i don't use huggin face a lot
the code:
import sagemaker
import boto3
from sagemaker.huggingface import HuggingFace
# gets role for executing training job
iam_client = boto3.client('iam')
role = iam_client.get_role(RoleName='{IAM_ROLE_WITH_SAGEMAKER_PERMISSIONS}')['Role']['Arn']
hyperparameters = {
'model_name_or_path':'ZipperXYZ/DialoGPT-medium-TheWorldMachineExpressive2',
'output_dir':'/opt/ml/model'
# add your remaining hyperparameters
# more info here https://github.com/huggingface/transformers/tree/v4.17.0/examples/pytorch/language-modeling
}
# git configuration to download our fine-tuning script
git_config = {'repo': 'https://github.com/huggingface/transformers.git','branch': 'v4.17.0'}
# creates Hugging Face estimator
huggingface_estimator = HuggingFace(
entry_point='run_clm.py',
source_dir='./examples/pytorch/language-modeling',
instance_type='ml.p3.2xlarge',
instance_count=1,
role=role,
git_config=git_config,
transformers_version='4.17.0',
pytorch_version='1.10.2',
py_version='py38',
hyperparameters = hyperparameters
)
# starting the train job
huggingface_estimator.fit()
You would first need to configure your credentials, its not an error in your code. Follow this thread
TLDR:
NoCredentialsError: Unable to locate credentials
Reply: Yes let me explain this, it is a bit complicated to get started. So the IAM ROLE, which you have created will be used inside the SageMaker Training Job/Inference. Meaning this ROLE is used to, e.g. download your data from s3 or is needed to start the underlying machine.
The error NoCredentialsError: Unable to locate credentials is shown when you don’t have credentials configured on your machine. You need to run aws configure so set up IAM Credentials (User) on your machine. You need these credentials to start your training job.

Unable to get Connection from Python to Snowflake

I am using a private key authentication to connect to Snowflake using python,
**This is working successfully when connecting directly using Java Client
import snowflake.connector
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives import serialization
with open("rsa_key.p8", "rb") as key:
p_key= serialization.load_pem_private_key(
key.read(),
password='XXXXX'.encode(),
backend=default_backend()
)
pkb = p_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption())
conn = snowflake.connector.connect(
user=XXXXX,
password=XXXXXXX,
account=XXXXXXXXX,
private_key=pkb,
warehouse=XXX,
database=XXXXXX,
schema=XXXX
)
Have masked real values where needed, but these are correct as same as work direct with Java client.
Error:
/usr/lib/python3/dist-packages/jwt/algorithms.py:179: CryptographyDeprecationWarning: signer and verifier have been deprecated. Please use sign and verify instead.
self.hash_alg()
Traceback (most recent call last):
File "tryconnection.py", line 37, in <module>
schema='PUBLIC'
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/__init__.py", line 53, in Connect
return SnowflakeConnection(**kwargs)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/connection.py", line 189, in __init__
self.connect(**kwargs)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/connection.py", line 493, in connect
self.__open_connection()
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/connection.py", line 710, in __open_connection
self.__authenticate(auth_instance)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/connection.py", line 963, in __authenticate
session_parameters=self._session_parameters,
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/auth.py", line 217, in authenticate
socket_timeout=self._rest._connection.login_timeout)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/network.py", line 530, in _post_request
_include_retry_params=_include_retry_params)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/network.py", line 609, in fetch
**kwargs)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/network.py", line 711, in _request_exec_wrapper
raise e
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/network.py", line 653, in _request_exec_wrapper
method, full_url, headers, data, conn)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/network.py", line 758, in _handle_unknown_error
u'errno': ER_FAILED_TO_REQUEST,
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/errors.py", line 100, in errorhandler_wrapper
connection.errorhandler(connection, cursor, errorclass, errorvalue)
File "/usr/local/lib/python3.6/dist-packages/snowflake/connector/errors.py", line 73, in default_errorhandler
done_format_msg=errorvalue.get(u'done_format_msg'))
snowflake.connector.errors.OperationalError: 250003: None: Failed to get the response. Hanging? method: post, url:
Thank you in advance for your help.
I can not see the rest of the error message so I couldn't be sure. Are you sure enter your account name (and region and cloud if needed) as the account parameter, instead of full Snowflake URL?
https://docs.snowflake.com/en/user-guide/python-connector-example.html#connecting-to-snowflake
When connecting Jira, usually people uses JDBC connection string which includes full snowflake URL:
https://docs.snowflake.com/en/user-guide/python-connector-example.html#connecting-to-snowflake

client.get_bucket() fails, but only from cloud dataflow (compute engine)

Application has been working normally, now on a re-deploy, google storage is giving strange errors.
MissingSchema: Invalid URL 'None/storage/v1/b/my-bucket-name?projection=noAcl': No schema supplied. Perhaps you meant http://None/storage/v1/b/my-bucket-name?projection=noAcl?
File "/usr/local/lib/python2.7/dist-packages/lib/file_store.py", line 11, in __init__
self.bucket = self.client.get_bucket(parts[0])
File "/usr/local/lib/python2.7/dist-packages/google/cloud/storage/client.py", line 301, in get_bucket
bucket.reload(client=self)
File "/usr/local/lib/python2.7/dist-packages/google/cloud/storage/_helpers.py", line 130, in reload
_target_object=self,
File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 392, in api_request
target_object=_target_object,
File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 269, in _make_request
return self._do_request(method, url, headers, data, target_object)
File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 298, in _do_request
return self.http.request(url=url, method=method, headers=headers, data=data)
File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/requests.py", line 208, in request
method, url, data=data, headers=request_headers, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 519, in request
prep = self.prepare_request(req)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 462, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 313, in prepare
self.prepare_url(url, params)
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 387, in prepare_url
raise MissingSchema(error)
MissingSchema: Invalid URL 'None/storage/v1/b/my-bucket-name?projection=noAcl': No schema supplied. Perhaps you meant http://None/storage/v1/b/my-bucket-name?projection=noAcl? [while running 'generatedPtransform-51']
The code causing the error, I can run this locally using the same service account and it works, no error. I am using $env:GOOGLE_APPLICATION_CREDENTIALS to export my service account credentials at deploy time. All other services are working normally.
# My test is:
# fs = FileStore("gs://my-bucket-name/models/", "development", "general")
class FileStore():
# modelPath - must be a gs:// style google storage resource path containing everything but the file extension
def __init__(self, modelPath, env, modelName):
from google.cloud import storage
parts = modelPath[5:].split('/', 1)
self.client = storage.Client()
self.bucket = self.client.get_bucket(parts[0]) # <- error here
Why would google core client fail to build a URL? Based on 'None/storage/v1/b/my-bucket-name?projection=noAcl', the missing part of the URL should be something like "https://www.googleapis.com".
This error is apparently caused by a mismatch between google_cloud_storage and google_cloud_core. I had specified google_cloud_core >= 1.0.3 in my setup.py but when I looked on the docker image on the compute VM I found it had an earlier version.
After rebuilding my venv from setup.py I had to also run:
C:\Python27\python.exe -m pipenv install google-cloud-core>=1.0.3 --skip-lock
Then I was able to deploy and the application started working again.

OpenStack - KeyStone Requires Authentication 401

I'm trying to list the projects (but the same thing occurs whether I try to do that, or attempt to list the users, so let's just generalise the error to any API call). Every time I do this, I get the following HTTP 401 code:
File "/usr/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 656, in respond
response.body = self.handler()
File "/usr/lib/python2.7/site-packages/cherrypy/lib/encoding.py", line 188, in __call__
self.body = self.oldhandler(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/cherrypy/lib/jsontools.py", line 61, in json_handler
value = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/cherrypy/_cpdispatch.py", line 34, in __call__
return self.callable(*self.args, **self.kwargs)
File "/var/www/frontend/controllers/api/user.py", line 63, in PUT
print keystoneClient.projects.list()
File "/usr/lib/python2.7/site-packages/positional/__init__.py", line 101, in inner
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneclient/v3/projects.py", line 107, in list
**kwargs)
File "/usr/lib/python2.7/site-packages/keystoneclient/base.py", line 75, in func
return f(*args, **new_kwargs)
File "/usr/lib/python2.7/site-packages/keystoneclient/base.py", line 383, in list
self.collection_key)
File "/usr/lib/python2.7/site-packages/keystoneclient/base.py", line 124, in _list
resp, body = self.client.get(url, **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneauth1/adapter.py", line 173, in get
return self.request(url, 'GET', **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneauth1/adapter.py", line 331, in request
resp = super(LegacyJsonAdapter, self).request(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneauth1/adapter.py", line 98, in request
return self.session.request(url, method, **kwargs)
File "/usr/lib/python2.7/site-packages/positional/__init__.py", line 101, in inner
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneauth1/session.py", line 387, in request
auth_headers = self.get_auth_headers(auth)
File "/usr/lib/python2.7/site-packages/keystoneauth1/session.py", line 647, in get_auth_headers
return auth.get_headers(self, **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneauth1/plugin.py", line 84, in get_headers
token = self.get_token(session)
File "/usr/lib/python2.7/site-packages/keystoneauth1/identity/base.py", line 90, in get_token
return self.get_access(session).auth_token
File "/usr/lib/python2.7/site-packages/keystoneauth1/identity/base.py", line 136, in get_access
self.auth_ref = self.get_auth_ref(session)
File "/usr/lib/python2.7/site-packages/keystoneauth1/identity/v3/base.py", line 167, in get_auth_ref
authenticated=False, log=False, **rkwargs)
File "/usr/lib/python2.7/site-packages/keystoneauth1/session.py", line 595, in post
return self.request(url, 'POST', **kwargs)
File "/usr/lib/python2.7/site-packages/positional/__init__.py", line 101, in inner
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/keystoneauth1/session.py", line 484, in request
raise exceptions.from_response(resp, method, url)
Unauthorized: The request you have made requires authentication. (HTTP 401) (Request-ID: req-39d02130-6f47-4cae-bc30-0b645296752e)
Code:
import cherrypy
import ldap
from keystoneauth1 import loading
from keystoneauth1 import session as session
from keystoneclient.v3 import client as client
from keystoneauth1.identity import v3
import json
# Storing username and password in a cherrypy session
cherrypy.session['username'] = data.get("username")
cherrypy.session['password'] = data.get("password").replace(" ","%20")
# Setting up KeyStone Client
auth = v3.Password(
auth_url = KEYSTONE_URL,
username = cherrypy.session['username'],
password = cherrypy.session['password'],
user_domain_name="default",
domain_name = "default"
)
sess = session.Session(auth=auth, verify='/etc/ssl/certs/ca-bundle.crt')
keystoneClient = client.Client(session=sess)
# Getting list of projects
print keystoneClient.projects.list()
This occurs whilst using a normal user's credentials. If I login using admin credentials, there is no error and the projects are listed. I would like to know:
Why is the overall error occurring? (from what I've read, it seems like it has to reauthenticate the credentials and it doesn't like it?)
Why is it not happening when I use admin credentials but with a 'normal' users credentials?
How do I solve this?
To answer the first question, you need a project scoped token since the unscoped token doesn't have any role associated with it. You cannot do any operation with the unscoped token. Here is a way to get the project scoped token:
auth = v3.Password(auth_url=auth_url,
username=username,
password=password,
user_domain_name="default",
project_name=project_name,
project_domain_name="default")
sess = session.Session(auth=auth, verify='/etc/ssl/certs/ca-bundle.crt')
keystoneClient = client.Client(session=sess)
And for a normal user, you cannot get back the entire list of projects in the provider and this is why it works fine with using admin credentials but not for that of a normal user.
In order to solve it, you need to know the user_id of that normal user. One way is to use the admin credentials to get a keystone client and call
keystone.users.get(user="username")
Or just use the OpenStack Dashboard and go to the identity dashboard. There is a panel called User and you can see the user_id from there.
Once you have the user_id, you can do:
keystoneClient.projects.list(user=user_id)
HTH.

py2neo (Neo4j) : py2neo.packages.httpstream.http.SocketError: Operation not permitted

I am running Neo4j 2.2.1 in ubuntu Amazon EC2 instance. When I am trying to connect through python using py2neo-2.0.7, I am getting following error :
py2neo.packages.httpstream.http.SocketError: Operation not permitted
I am able to access the web-interface through http://52.10.**.***:7474/browser/
CODE :-
from py2neo import Graph, watch, Node, Relationship
url_graph_conn = "https://neo4j:password#52.10.**.***:7474/db/data/"
print url_graph_conn
my_conn = Graph(url_graph_conn)
babynames = my_conn.find("BabyName")
for babyname in babynames:
print 2
Error message :-
https://neo4j:password#52.10.**.***:7474/db/data/
Traceback (most recent call last):
File "C:\Users\rharoon002\eclipse_workspace\peace\peace\core\graphconnection.py", line 39, in <module>
for babyname in babynames:
File "C:\Python27\lib\site-packages\py2neo\core.py", line 770, in find
response = self.cypher.post(statement, parameters)
File "C:\Python27\lib\site-packages\py2neo\core.py", line 667, in cypher
metadata = self.resource.metadata
File "C:\Python27\lib\site-packages\py2neo\core.py", line 213, in metadata
self.get()
File "C:\Python27\lib\site-packages\py2neo\core.py", line 258, in get
response = self.__base.get(headers=headers, redirect_limit=redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 966, in get
return self.__get_or_head("GET", if_modified_since, headers, redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 943, in __get_or_head
return rq.submit(redirect_limit=redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 433, in submit
http, rs = submit(self.method, uri, self.body, self.headers)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 362, in submit
raise SocketError(code, description, host_port=uri.host_port)
py2neo.packages.httpstream.http.SocketError: Operation not permitted
You are trying to access neo4j via https on the standard port for http (7474):
url_graph_conn = "https://neo4j:password#52.10.**.***:7474/db/data/"
The standard port for a https connection is 7473. Try:
url_graph_conn = "https://neo4j:password#52.10.**.***:7473/db/data/"
And make sure you can access the web interface via https:
https://52.10.**.***:7473/browser/
You can change/see the port settings in your neo4j-server.properties file.

Categories

Resources