web3py EthereumTesterProvider - Basic interactions with a smart contract fail - ethereum

On the web3py EthereumTesterProvider blockchain, I tested the contract deployment example at https://web3py.readthedocs.io/en/v5/contracts.html.
But I came across 2 errors.
pip config (windows 10) :
web3py (5.31.3)
eth-tester (0.8.0b3)
Here is the code :
from web3 import Web3
from solcx import compile_source
from pprint import pprint
# Solidity source code
compiled_sol = compile_source(
'''
pragma solidity ^0.8.17;
contract Greeter {
string public greeting;
constructor() public {
greeting = 'Hello';
}
function setGreeting(string memory _greeting) public {
greeting = _greeting;
}
function greet() view public returns (string memory) {
return greeting;
}
}
''',
output_values=['abi', 'bin']
)
# retrieve the contract interface
contract_id, contract_interface = compiled_sol.popitem()
# get bytecode and abi
bytecode = contract_interface['bin']
abi = contract_interface['abi']
# web3.py instance
w3 = Web3(Web3.EthereumTesterProvider())
# set pre-funded account as sender
w3.eth.default_account = w3.eth.accounts[0]
greeter_bin = w3.eth.contract(abi=abi, bytecode=bytecode)
# Submit the transaction that deploys the contract
tx_hash = greeter_bin.constructor().transact() # <==== first error
# tx_hash = greeter_bin.constructor().transact({'gas': 123456})
# Wait for the transaction to be mined, and get the transaction receipt
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
pprint(dict(tx_receipt))
greeter_obj = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi)
print(f"{greeter_obj.functions.greet().call() = }") # <===== Second error
tx_hash = greeter_obj.functions.setGreeting('Nihao').transact()
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(f"{greeter_obj.functions.greet().call() = }")
1) The first error takes place at the contract deployment:
"TypeError: MockBackend.estimate_gas() takes 2 positional arguments but 3 were given."
I fixed it by adding a dictionary with some gas but the exemple from Web3.py does not have this parameter. I'd like to know the reason. Did I miss something?
C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\eth_tester\backends\__init__.py:30: UserWarning: Ethereum Tester: No backend was explicitly set, and no *full* backends were available. Falling back to the `MockBackend` which does not support all EVM functionality. Please refer to the `eth-tester` documentation for information on what backends are available and how to set them. Your py-evm package may need to be updated.
warnings.warn(
Traceback (most recent call last):
File "D:\_P\dev\python\blockchain\web3\tester1.py", line 45, in <module>
tx_hash = greeter_bin.constructor().transact()
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\eth_utils\decorators.py", line 18, in _wrapper
return self.method(obj, *args, **kwargs)
.............
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\providers\eth_tester\middleware.py", line 331, in middleware
return make_request(method, [filled_transaction] + list(params)[1:])
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\formatting.py", line 94, in middleware
response = make_request(method, params)
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\providers\eth_tester\main.py", line 103, in make_request
response = delegator(self.ethereum_tester, params)
File "cytoolz\functoolz.pyx", line 253, in cytoolz.functoolz.curry.__call__
File "cytoolz\functoolz.pyx", line 249, in cytoolz.functoolz.curry.__call__
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\providers\eth_tester\defaults.py", line 66, in call_eth_tester
return getattr(eth_tester, fn_name)(*fn_args, **fn_kwargs)
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\eth_tester\main.py", line 483, in estimate_gas
raw_gas_estimate = self.backend.estimate_gas(raw_transaction, raw_block_number)
TypeError: MockBackend.estimate_gas() takes 2 positional arguments but 3 were given
2) After fixing the first error by adding {'gas': 123456} in transact(), the second error takes place at greeter_obj.functions.greet().call() :
"ValueError: Error expected to be a dict."
For this one, I have no clue
Information�: impossible de trouver des fichiers pour le(s) mod�le(s) sp�cifi�(s).
C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\eth_tester\backends_init_.py:30: UserWarning: Ethereum Tester: No backend was explicitly set, and no full backends were available. Falling back to the MockBackend which does not support all EVM functionality. Please refer to the eth-tester documentation for information on what backends are available and how to set them. Your py-evm package may need to be updated.
warnings.warn(
{'blockHash': HexBytes('0xafae7675633fedae22a1f5b9d11066ff78de5947f7b3e2915824823cc65d0e56'),
'blockNumber': 1,
'contractAddress': '0xa0Beb7081fDaF3ed157370836A85eeC20CEc9e04',
'cumulativeGasUsed': 21000,
'effectiveGasPrice': 1000000000,
'from': '0xaBbACadABa000000000000000000000000000000',
'gasUsed': 21000,
'logs': [],
'state_root': b'\x00',
'status': 0,
'to': '',
'transactionHash': HexBytes('0x5193460ead56b33c2fa79b490a6c0f4e0d68e07c712d762afcadc5976148bf1a'),
'transactionIndex': 0,
'type': '0x2'}
Traceback (most recent call last):
File "D:_P\dev\python\blockchain\web3\tester1.py", line 54, in
print(f"{greeter_obj.functions.greet().call() = }")
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\contract.py", line 970, in call
return call_contract_function(
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\contract.py", line 1525, in call_contract_function
return_data = web3.eth.call(
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 198, in request_blocking
return self.formatted_response(response,
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 170, in formatted_response
apply_error_formatters(error_formatters, response)
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 70, in apply_error_formatters
formatted_resp = pipe(response, error_formatters)
File "cytoolz\functoolz.pyx", line 666, in cytoolz.functoolz.pipe
File "cytoolz\functoolz.pyx", line 641, in cytoolz.functoolz.c_pipe
File "C:\Users\Gilles\AppData\Local\Programs\Python\Python310\lib\site-packages\web3_utils\method_formatters.py", line 555, in raise_solidity_error_on_revert
raise ValueError('Error expected to be a dict')
ValueError: Error expected to be a dict
Please note the status of the deployment transaction: 'status': 0
It failed but a contractAddress was returned !
As far as the UserWarning is concerned, I also tried unsuccessfully MockBackend (though it's the default backend):
from eth_tester import MockBackend
w3 = Web3(Web3.EthereumTesterProvider(MockBackend()))
Lastly, I tried to install py-evm "pip install py-evm" to try PyEVMBackend backend, but the installation failed at pyethash dependency:
"D:\Program\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Users\Gilles\AppData\Local\Programs\Python\Python310\include -IC:\Users\Gilles\AppData\Local\Programs\Python\Python310\Include "-ID:\Program\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-ID:\Program\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt" /Tcsrc/libethash/io_win32.c /Fobuild\temp.win-amd64-cpython-310\Release\src/libethash/io_win32.obj -Isrc/ -std=gnu99 -Wall
clÿ: Ligne de commande warning D9002ÿ: option '-std=gnu99' inconnue ignor‚e
io_win32.c
c1: fatal error C1083: Impossible d'ouvrir le fichier sourceÿ: 'src/libethash/io_win32.c'ÿ: No such file or directory
error: command 'D:\\Program\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> pyethash

Related

Why can't Cloud Function access metadata server in Vertex AI example?

I followed this Vertex AI tutorial. However, at the last step, as the Cloud Function calls the prediction endpoint, it gets this failure.
This means it could not even access the metadata server. I.e., is not a permissions failure (though I did check that the myproject#appspot.gserviceaccount.com service account does have Project Editor role as specified). It is also an error strictly in Functions and IAM, not in Vertex.AI or other ML systems.
What is going wrong here?
Function execution took 673 ms, finished with status code: 500
Prediction request failed: <class 'google.api_core.exceptions.ServiceUnavailable'>: 503 Getting metadata from plugin failed with error: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/myproject#appspot.gserviceaccount.com/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/myproject#appspot.gserviceaccount.com/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform\\n'", <google.auth.transport.requests._Response object at 0x3e095a9f4c50>)
google.auth.exceptions.RefreshError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/myproject#appspot.gserviceaccount.com/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/myproject#appspot.gserviceaccount.com/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform\\n'", <google.auth.transport.requests._Response object at 0x3e095a9f4c50>)
File "<string>", line 3, in raise_from
six.raise_from(new_exc, caught_exc)
File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/credentials.py", line 117, in refresh
self.refresh(request)
File "/env/local/lib/python3.7/site-packages/google/auth/credentials.py", line 133, in before_request
self._request, context.method_name, context.service_url, headers
File "/env/local/lib/python3.7/site-packages/google/auth/transport/grpc.py", line 88, in _get_authorization_headers
callback(self._get_authorization_headers(context), None)
File "/env/local/lib/python3.7/site-packages/google/auth/transport/grpc.py", line 101, in __call__
context, _AuthMetadataPluginCallback(callback_state, callback))
File "/env/local/lib/python3.7/site-packages/grpc/_plugin_wrapping.py", line 78, in __call__
Traceback (most recent call last):
The above exception was the direct cause of the following exception:
google.auth.exceptions.TransportError: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/myproject#appspot.gserviceaccount.com/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform from the Google Compute Enginemetadata service. Status: 500 Response:\nb'Could not fetch URI /computeMetadata/v1/instance/service-accounts/myproject#appspot.gserviceaccount.com/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform\\n'", <google.auth.transport.requests._Response object at 0x3e095a9f4c50>)
response,
File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/_metadata.py", line 187, in get
token_json = get(request, path, params=params)
File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/_metadata.py", line 263, in get_service_account_token
request, service_account=self._service_account_email, scopes=scopes
File "/env/local/lib/python3.7/site-packages/google/auth/compute_engine/credentials.py", line 113, in refresh
Traceback (most recent call last):
AuthMetadataPluginCallback "<google.auth.transport.grpc.AuthMetadataPlugin object at 0x3e0961671dd0>" raised exception!

Google Cloud Function error "OperationError: code=3, message=Function failed on loading user code"

I get an error from time to time when deploying nodejs10 cloud functions to GCP. The error seems to go away on it's own, I just redeploy the same thing a few times. Anyone know what causes it? He's the log:
command: gcloud beta functions deploy exchangeIcon --verbosity debug --runtime nodejs10 --memory 128 --region europe-west1 --timeout 5 --trigger-http --set-env-vars=FUNCTION_REGION=europe-west1,BUILD_DATE=2019-05-09T10:01:05.497Z --entry-point app
DEBUG: Running [gcloud.beta.functions.deploy] with arguments: [--entry-point: "app", --memory: "134217728", --region: "europe-west1", --runtime: "nodejs10", --set-env-vars: "OrderedDict([(u'FUNCTION_REGION', u'europe-west1'), (u'BUILD_DATE', u'2019-05-09T10:01:05.497Z')])", --timeout: "5", --trigger-http: "True", --verbosity: "debug", NAME: "exchangeIcon"]
INFO: Not using a .gcloudignore file.
INFO: Not using a .gcloudignore file.
Deploying function (may take a while - up to 2 minutes)...
..........................................................................failed.
DEBUG: (gcloud.beta.functions.deploy) OperationError: code=3, message=Function failed on loading user code. Error message:
Traceback (most recent call last):
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 985, in Execute
resources = calliope_command.Run(cli=self, args=args)
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 795, in Run
resources = command_instance.Run(args)
File "/Users/me/Downloads/google-cloud-sdk/lib/surface/functions/deploy.py", line 231, in Run
enable_vpc_connector=True)
File "/Users/me/Downloads/google-cloud-sdk/lib/surface/functions/deploy.py", line 175, in _Run
return api_util.PatchFunction(function, updated_fields)
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/util.py", line 300, in CatchHTTPErrorRaiseHTTPExceptionFn
return func(*args, **kwargs)
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/util.py", line 356, in PatchFunction
operations.Wait(op, messages, client, _DEPLOY_WAIT_NOTICE)
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 126, in Wait
_WaitForOperation(client, request, notice)
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 101, in _WaitForOperation
sleep_ms=SLEEP_MS)
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/core/util/retry.py", line 219, in RetryOnResult
result = func(*args, **kwargs)
File "/Users/me/Downloads/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 65, in _GetOperationStatus
raise exceptions.FunctionsError(OperationErrorToString(op.error))
FunctionsError: OperationError: code=3, message=Function failed on loading user code. Error message:
ERROR: (gcloud.beta.functions.deploy) OperationError: code=3, message=Function failed on loading user code.
In my Stackdriver Logging I just see INVALID_ARGUMENT, but nothing else.
The problem stems from your terminal commands not being properly formatted.
--verbosity=debug
is the proper way to type this. Also same thing with your runtime.

Airflow: Cannot assign requested address error while using emailoperator

Unable to receive email on task failure or even using EmailOperator
Hi Guys,
I am unable to receive email from my box even after adding required parameters to send one.
Below is how my default args looks like --
default_args = {
'owner': 'phonrao',
'depends_on_past': False,
#'start_date': datetime(2019, 3, 28),
'start_date': airflow.utils.dates.days_ago(2),
'email': ['phonrao#gmail.com'],
'email_on_failure': True,
'email_on_retry': True,
'retries': 1,
'retry_delay': timedelta(minutes=5),
#'on_failure_callback': report_failure,
#'end_date': datetime(2020,4 ,1),
#'schedule_interval': '#hourly',
}
I have few HttpsOperator task in between -- those are working good and are a success, but they do not send email on error(I purposely tried to introduce an error to check if they send any email). Below is an example of my task.
t1 = SimpleHttpOperator(
task_id='t1',
http_conn_id='http_waterfall',
endpoint='/update_data',
method='POST',
headers={"Content-Type":"application/json"},
xcom_push=True,
log_response=True,
dag=dag,
)
and this is my EmailOperator task
t2 = EmailOperator(
dag=dag,
task_id="send_email",
to='phonrao#gmail.com',
subject='Success',
html_content="<h3>Success</h3>"
)
t2 >> t1
Below is the error from Logs:
[2019-04-02 15:28:21,305] {{base_task_runner.py:101}} INFO - Job 845: Subtask send_email [2019-04-02 15:28:21,305] {{cli.py:520}} INFO - Running <TaskInstance: schedulerDAG.send_email 2019-04-02T15:23:08.896589+00:00 [running]> on host a47cd79aa987
[2019-04-02 15:28:21,343] {{logging_mixin.py:95}} INFO - [2019-04-02 15:28:21,343] {{configuration.py:255}} WARNING - section/key [smtp/smtp_user] not found in config
[2019-04-02 15:28:21,343] {{models.py:1788}} ERROR - [Errno 99] Cannot assign requested address
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/airflow/models.py", line 1657, in _run_raw_task
result = task_copy.execute(context=context)
File "/usr/local/lib/python3.6/site-packages/airflow/operators/email_operator.py", line 78, in execute
mime_subtype=self.mime_subtype, mime_charset=self.mime_charset)
File "/usr/local/lib/python3.6/site-packages/airflow/utils/email.py", line 55, in send_email
mime_subtype=mime_subtype, mime_charset=mime_charset, **kwargs)
File "/usr/local/lib/python3.6/site-packages/airflow/utils/email.py", line 101, in send_email_smtp
send_MIME_email(smtp_mail_from, recipients, msg, dryrun)
File "/usr/local/lib/python3.6/site-packages/airflow/utils/email.py", line 121, in send_MIME_email
s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) if SMTP_SSL else smtplib.SMTP(SMTP_HOST, SMTP_PORT)
File "/usr/local/lib/python3.6/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/local/lib/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/local/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/local/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
OSError: [Errno 99] Cannot assign requested address
[2019-04-02 15:28:21,351] {{models.py:1817}} INFO - All retries failed; marking task as FAILED
Below is my airflow.cfg
[email]
email_backend = airflow.utils.email.send_email_smtp
[smtp]
# If you want airflow to send emails on retries, failure, and you want to use
# the airflow.utils.email.send_email_smtp function, you have to configure an
# smtp server here
smtp_host = localhost
smtp_starttls = True
smtp_ssl = False
# Uncomment and set the user/pass settings if you want to use SMTP AUTH
# smtp_user = airflow
# smtp_password = airflow
smtp_port = 25
smtp_mail_from = airflow#example.com
Has anyone encounter this issue and any suggestions on how do I resolve this?
If your airflow running on Kubernetes (installed by helm chart), you should take a look in "airflow-worker-0" pod, and make sure the environment variable of SMTP_HOST or SMTP_USER ... available in the config. Simply debugging, access to the container of airflow-worker and then run python, then trying these commands to make sure it works correctly.
import airflow
airflow.utils.email.send_email('example#gmail.com', 'Airflow TEST HERE', 'This is airflow status success')
I have the same issues, by resolving the environment variable of SMTP. Now it works.

How to fix HTTP Error 503: Service Unavailable error

Executing the command:
amazon = bottlenose.Amazon(AMAZON_ACCESS_KEY,AMAZON_SECRET_KEY,AMAZON_ASSOC_TAG)
response = amazon.ItemLookup(ItemId='B007OZNUCE')
I got the error:
Traceback (most recent call last):
File "exazapi.py", line 37, in <module>
response = amazon.ItemLookup(ItemId='B007OZNUCE')
File "C:\Python\lib\site-packages\bottlenose\api.py", line 274, in __call__
{'api_url': api_url, 'cache_url': cache_url})
File "C:\Python\lib\site-packages\bottlenose\api.py", line 235, in _call_api
return urllib2.urlopen(api_request, timeout=self.Timeout)
File "C:\Python\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Python\lib\urllib\request.py", line 531, in open
response = meth(req, response)
File "C:\Python\lib\urllib\request.py", line 641, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python\lib\urllib\request.py", line 569, in error
return self._call_chain(*args)
File "C:\Python\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Python\lib\urllib\request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 503: Service Unavailable
#import all the required modules
import re
import csv
import sys
import warnings
from urllib.request import urlopen
from bs4 import BeautifulSoup
from requests_html import HTMLSession
import bottlenose
#from amazon.api import AmazonAPI
AMAZON_ACCESS_KEY='xxx'
AMAZON_SECRET_KEY='xxx'
AMAZON_ASSOC_TAG='xxx'
#ignore warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
amazon = bottlenose.Amazon(AMAZON_ACCESS_KEY,AMAZON_SECRET_KEY,AMAZON_ASSOC_TAG)
response = amazon.ItemLookup(ItemId='B007OZNUCE')
print (amazon)
print(response)
Region is missing, add something like "DE" or "ES" depending on the country you're using.
Default is 'US':
amazon = bottlenose.Amazon(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ASSOCIATE_TAG, Region='FR')
from: https://github.com/lionheart/bottlenose
Additionally: have you checked in the 'amazon' customer portal, on the 'platform API' access for the countries you want to use, that the API is enabled?
France: https://partenaires.amazon.fr/assoc_credentials/home
UK: https://affiliate-program.amazon.co.uk/assoc_credentials/home
US: https://affiliate-program.amazon.com/assoc_credentials/home
For me, it shows inactive, hence, that's probably the cause for the request to be denied.
Thanks for the inputs!
The same code worked magically now. Seems the api keys weren't enabled immediately after creating them.

Installation of Indivo Database - Errors during Testing Indivo Backend Server

I am a Computer Engineering UG student, working on a research project on Explanation of Health Data. For my project, I am required to access the Indivo health database. I am running Ubuntu 14.10 in Oracle's VirtualBox, with my host laptop OS in Windows 8.1.
I completed all steps of installation as per the instructions here - http://docs.indivohealth.org/en/2.0/howtos/install-ubuntu.html. Out of the three options, I have installed MySQL for database.
But I am stuck while Testing backend server. I am always receiving two errors -
osboxes#osboxes:~/IndivoHDB/indivo_server$ python manage.py cleanup_old_tokens
osboxes#osboxes:~/IndivoHDB/indivo_server$ python manage.py test indivo
Creating test database for alias 'default'...
.................F............................................................................................
RUNNING INTEGRATION TESTS:
=============================================================================
Report:
.......... pass : Document Handling Test
.......... pass : Sharing
.......... pass : PHA Document Handling
.......... pass : PHAing record_app delete
.......... pass : PHAing app delete
.......... pass : AppSpecific
.......... pass : Document Metadata Test
.......... pass : OAuthing
.......... pass : Binary Document Test
.......... pass : Accounting
.......... pass : Record Shares
.......... pass : Messaging
.......... pass : Special Document Handling
.......... pass : Auditing
.......... pass : Document Processing Test
.......... pass : Security
=============================================================================
......................................................................................................................E.........................................
ERROR: test_get_smart_ontology (indivo.tests.api.smart_tests.SMARTInternalTests)
Traceback (most recent call last):
File "/home/osboxes/IndivoHDB/indivo_server/indivo/tests/api/smart_tests.py", line 11, in test_get_smart_ontology
response = self.client.get('/ontology')
File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 439, in get
response = super(Client, self).get(path, data=data, **extra)
File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 241, in get
return self.request(**r)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/osboxes/IndivoHDB/indivo_server/indivo/lib/utils.py", line 38, in call
return view_func(request, *args, **kwargs)
File "/home/osboxes/IndivoHDB/indivo_server/indivo/views/smart_container.py", line 19, in smart_ontology
ontology = urllib2.urlopen(url).read()
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1199, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1169, in do_open
raise URLError(err)
URLError:
======================================================================
FAIL: test_get_connect_credentials (indivo.tests.api.accounts_tests.AccountInternalTests)
Traceback (most recent call last):
File "/home/osboxes/IndivoHDB/indivo_server/indivo/tests/api/accounts_tests.py", line 376, in test_get_connect_credentials
self.assertEqual(db_rt.expires_at, iso8601.parse_utc_date(data.findtext('ExpiresAt')))
AssertionError: datetime.datetime(2015, 6, 22, 5, 36, 32) != datetime.datetime(2015, 6, 22, 5, 36, 32, 977919)
Ran 270 tests in 301.989s
FAILED (failures=1, errors=1)
Destroying test database for alias 'default'...
Please help me, as I am totally naive at this.
For my setup also I have seen the same error and I have contacted their google group and found that we can silently ignore that error and go ahead and see the things actually works or not. Mine is working fine eventhough i came across that errors.