Binance staking api, i cant imprt - python

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>

Related

Hubspot api client does not work for existing django project but works for new Django project

In my existing Django project I added a function called test as following:
...
import hubspot
from hubspot.crm.contacts import ApiException, PublicObjectSearchRequest, SimplePublicObjectInput
...
...
def test(email):
client = hubspot.Client.create(access_token=<access_token>)
public_object_search_request = PublicObjectSearchRequest(filter_groups=[{"filters": [{
"value": email,
"propertyName": "email",
"operator": "EQ"
}]}])
try:
api_response = client.crm.contacts.search_api.do_search(
public_object_search_request=public_object_search_request)
pprint(api_response)
except ApiException as e:
print("Exception when calling search_api->do_search: %s\n" % e
Running sudo python3 manage.py runserver gives me error saying no such module 'hubspot.crm'.
So I commented everything in test except client line as following:
...
import hubspot
...
...
def test(email):
client = hubspot.Client.create(access_token=<access_token>)
This time I get error module 'hubspot' has no attribute 'Client'.
I then created new Django project (on same system) and had same test function (the first snippet) and ran django server, this time it worked without errors. Why is Django not seeing hubspot module for existing project? I have also tried to do this using venv and same results were seen.
I am using:
Python 3.10.6
hubspot-api-client=7.0.0 https://pypi.org/project/hubspot-api-client/

How do I make a text bot in a shell (preferably repl.it) using the dialogflow python api?

I am trying to make a simple chatbot in my repl.it shell, but it errors, saying that it "Could not automatically determine credentials.", I have looked over it many times, and can't figure out how to do it. In addition, I might have other things wrong but I can't tell since I can't get past this error.
If anyone can help me with this, or if you have an example that I can follow, that would be great
https://repl.it/#RyandaKing/ThoughtfulWorrisomeQuadrant
import dialogflow
from google.api_core.exceptions import InvalidArgument
DIALOGFLOW_PROJECT_ID = 'newagent-1-rhjebl'
DIALOGFLOW_LANGUAGE_CODE = 'en-US'
GOOGLE_APPLICATION_CREDENTIALS = 'newagent-1-rhjebl-29ae80f7e64d.json'
SESSION_ID = '110497386060607202274'
text_to_be_analyzed = "Hello"
session_client = dialogflow.SessionsClient()
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
except InvalidArgument:
raise
print("Query text:", response.query_result.query_text)
print("Detected intent:", response.query_result.intent.display_name)
print("Detected intent confidence:", response.query_result.intent_detection_confidence)
print("Fulfillment text:", response.query_result.fulfillment_text)
The reason is that you improperly use the private key contained by .json. As described here you should define the environment variable having the value of .json key file path.
Assuming that the .py and .json files are in the same directory run it like this.
$ cd path/to/app
$ env 'GOOGLE_APPLICATION_CREDENTIALS=newagent-1-rhjebl-29ae80f7e64d.json' python3 app.py

Resource not found on Azure Cognitive Services

I have created an Azure Cognitive Services resource following the tutorial 1
Then I have created the environment and run the following code (from tutorial 2):
# Import required modules.
from azure.cognitiveservices.search.websearch import WebSearchAPI
from azure.cognitiveservices.search.websearch.models import SafeSearch
from msrest.authentication import CognitiveServicesCredentials
# Replace with your subscription key.
subscription_key = "YOUR_SUBSCRIPTION_KEY"
# Instantiate the client and replace with your endpoint.
client = WebSearchAPI(CognitiveServicesCredentials(subscription_key), base_url = "YOUR_ENDPOINT")
# Make a request. Replace Yosemite if you'd like.
web_data = client.web.search(query="Yosemite")
print("\r\nSearched for Query# \" Yosemite \"")
However, it seems the generaed Subscription key and endpoint are not correctly read by the script since I get the following error:
File "azu_scrapper.py", line 17, in
web_data = client.web.search(query="Yosemite") File "/home/user/.local/share/virtualenvs/linkedin-CHSAGU1d/lib/python3.7/site-packages/azure/cognitiveservices/search/websearch/operations/web_operations.py",
line 365, in search
raise models.ErrorResponseException(self._deserialize, response) azure.cognitiveservices.search.websearch.models.error_response_py3.ErrorResponseException:
Operation returned an invalid status code 'Resource Not Found'
Any idea why it is not working?
The base_url value should be :
https://<your endpoint>/bing/v7.0
I have tested on my side and it works for me :

Azure module on webservice

I am trying to publish a machine learning model on Azure webservice using python. I am able to deploy the code successfully but when i try to call it through the URL, it's throwing me 'Azure' module doesn't exist. The code basically retrieves a TFIDF model from the container (blob) and use it to predict the new value. The error clearly says, Azure package is missing while trying to run on the webservice and I am not sure how to fix it. Here goes the code:
For deployment:
from azureml import services
from azure.storage.blob import BlobService
#services.publish('7c94eb2d9e4c01cbe7ce1063','f78QWNcOXHt9J+Qt1GMzgdEt+m3NXby9JL`npT7XX8ZAGdRZIX/NZ4lL2CkRkGQ==')
#services.types(res=unicode)
#services.returns(str)
def TechBot(res):
from azure.storage.blob import BlobService
from gensim.similarities import SparseMatrixSimilarity, MatrixSimilarity, Similarity
blob_service = BlobService(account_name='tfidf', account_key='RU4R/NIVPsPOoR0bgiJMtosHJMbK1+AVHG0sJCHT6jIdKPRz3cIMYTsrQ5BBD5SELKHUXgBHNmvsIlhEdqUCzw==')
blob_service.get_blob_to_path('techbot',"2014.csv","df")
df=pd.read_csv("df")
doct = res
To access the url I used the python code from
service.azureml.net
import urllib2
import json
import requests
data = {
"Inputs": {
"input1":
[
{
'res': "wifi wnable",
}
],
},
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
#proxies = {"http":"http://%s" % proxy}
url = 'http://ussouthcentral.services.azureml.net/workspaces/7c94eb2de26a45399e4c01cbe7ce1063/services/11943e537e0741beb466cd91f738d073/execute?api-version=2.0&format=swagger'
api_key = '8fH9kp67pEt3C6XK9sXDLbyYl5cBNEwYg9VY92xvkxNd+cd2w46sF1ckC3jqrL/m8joV7o3rsTRUydkzRGDYig==' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
#proxy_support = urllib2.ProxyHandler(proxies)
#opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
#urllib2.install_opener(opener)
req = urllib2.Request(url, body, headers)
try:
response = urllib2.urlopen(req, timeout=60)
result = response.read()
print(result)
except urllib2.HTTPError, error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(json.loads(error.read()))
The string 'res' will be predicted at the end. As I said it runs perfectly fine if I run as it is in python by calling azure module, problem happens when I access the url.
Any help is appreciated, please let me know if you need more information (I only sohwcased half of my code)
I tried to reproduce the issue via POSTMAN, then I got the error information below as you said.
{
"error": {
"code": "ModuleExecutionError",
"message": "Module execution encountered an error.",
"details": [
{
"code": "85",
"target": "Execute Python Script RRS",
"message": "Error 0085: The following error occurred during script evaluation, please view the output log for more information:\r\n---------- Start of error message from Python interpreter ----------\r\nCaught exception while executing function: Traceback (most recent call last):\n File \"\\server\\InvokePy.py\", line 120, in executeScript\n outframe = mod.azureml_main(*inframes)\n File \"\\temp\\1280677032.py\", line 1094, in azureml_main\n File \"<ipython-input-15-bd03d199b8d9>\", line 6, in TechBot_2\nImportError: No module named azure\n\r\n\r\n---------- End of error message from Python interpreter ----------"
}
]
}
}
According to the error code 00085 & the information ImportError: No module named azure, I think the issue was caused by importing python moduleazure-storage. There was a similar SO thread Access Azure blog storage from within an Azure ML experiment which got the same issue, I think you can refer to its answer try to use HTTP protocol instead HTTPS in your code to resolve the issue as the code client = BlobService(STORAGE_ACCOUNT, STORAGE_KEY, protocol="http").
Hope it helps. Any concern & update, please feel free to let me know.
Update: Using HTTP protocol for BlobService
from azureml import services
from azure.storage.blob import BlobService
#services.publish('7c94eb2d9e4c01cbe7ce1063','f78QWNcOXHt9J+Qt1GMzgdEt+m3NXby9JL`npT7XX8ZAGdRZIX/NZ4lL2CkRkGQ==')
#services.types(res=unicode)
#services.returns(str)
def TechBot(res):
from azure.storage.blob import BlobService
from gensim.similarities import SparseMatrixSimilarity, MatrixSimilarity, Similarity
# Begin: Update code
# Using `HTTP` protocol for BlobService
blob_service = BlobService(account_name='tfidf',
account_key='RU4R/NIVPsPOoR0bgiJMtosHJMbK1+AVHG0sJCHT6jIdKPRz3cIMYTsrQ5BBD5SELKHUXgBHNmvsIlhEdqUCzw==',
protocol='http')
# End
blob_service.get_blob_to_path('techbot',"2014.csv","df")
df=pd.read_csv("df")
doct = res

Twitter update using Python throwing an error

I wrote the following piece of code for updating my Twitter status using Python.
import tweepy
tweet=raw_input("Enter the status that you want to update to Twitter: ")
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
return tweepy.API(auth)
def main():
# Fill in the values noted in previous step here
cfg = {
"consumer_key" : "VALUE",
"consumer_secret" : "VALUE",
"access_token" : "VALUE",
"access_token_secret" : "VALUE"
}
api = get_api(cfg)
status = api.update_status(status=tweet)
if __name__ == "__main__":
main()
The code works most of the times on different machines. However, there was a problem which I have described below.
>>status = api.update_status(status=tweet)
raise TweepError('Failed to send request: %s' % e)
tweepy.error.TweepError: Failed to send request: Missing dependencies for SOCKS support.
I have created a virtual environment for my twitter application within which I have installed tweepy using pip install on Ubuntu 16.04 machine.
Any pointers will be greatly appreciated.
Thanks in advance.

Categories

Resources