How do I use the Python SoftLayer client (using v5.7.1) to determine the location (eg: dal10) for an NFS billing item (endurance storage)?
I used some other examples here on SO and came up with this, but the call failed:
objectFilter = {"billingItem": {"id": {"operation": "12345"}}}
account.getAllBillingItems(filter=objectFilter)
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/SoftLayer/transports.py", line 240, in __call__
raise _es(ex.faultCode, ex.faultString)
SoftLayer.exceptions.SoftLayerAPIError: SoftLayerAPIError(SOAP-ENV:Server): Internal Error
Try using the following python script to get the billing item detail and the location too.
import json
import SoftLayer
API_USERNAME = 'set me'
API_KEY = 'set me'
client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY)
billingItemId = 1234
mask = "mask[location]"
try:
response = client['SoftLayer_Billing_Item'].getObject(mask=mask, id=billingItemId)
print(response)
except SoftLayer.SoftLayerAPIError as e:
"""
If there was an error returned from the SoftLayer API then bomb out with the
error message.
"""
print("Unable to retrieve the billing item information. "
% (e.faultCode, e.faultString))
Related
I been trying to make a python program that sends email but i keep getting this error
Traceback (most recent call last):
File "C:\Users\25194\PycharmProjects\Gmail\Yo.py", line 25, in <module>
smtp.sendmail(email_sender, email_password, em.as_string())
File "C:\Users\25194\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 901, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'google login': (553, b'5.1.3 The recipient address <Gmail app password> is not a valid RFC-5321\n5.1.3 address. Learn more at\n5.1.3 https://support.google.com/mail/answer/6596 k9-20020a7bc409000000b003c6bd91caa5sm17184983wmi.17 - gsmtp')}
The code is
from email.message import EmailMessage
import ssl
import smtplib
email_sender = 'oropyt32#gmail.com'
email_password = 'google login'
email_reciver = 'milkiwasihunpro#gmail.com'
subject = 'Check mate'
body = """
I am making this sending this isnt it cool oro
"""
em = EmailMessage()
em['From'] = email_sender
em['TO'] = email_reciver
em['Subject'] = subject
em.set_content(body)
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
smtp.login(email_sender, email_password)
smtp.sendmail(email_sender, email_password, em.as_string())
i am having hard time figuring out how to fix it
... b'5.1.3 The recipient address is not a valid RFC-5321\n5.1.3 address. ...
Obviously you are using a password in place where an email is expected
smtp.sendmail(email_sender, email_password, em.as_string())
From the documentation of sendmail:
SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
So you give the email_password where to_addrs is expected. No wonder that it complains about your password used as recipient. You probably meant to use email_reciver instead.
I have a problem running ccxt.load_markets() function in EC2 server
but I check running is OK in local PC enviroment.
Please me help for solution
Code and Error msg is as below.
python version : 3.7.15
CCXT version : 2.2.95
import ccxt
import time
b= ccxt.binance()
print(b.milliseconds())
print(b.nonce())
print(b.load_markets())
1671012133696
1671012133696
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/ccxt/base/exchange.py", line 621, in fetch
response.raise_for_status()
File "/home/ec2-user/.local/lib/python3.7/site-packages/requests/models.py", line 953, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 451 Client Error: for url: https://api.binance.com/api/v3/exchangeInfo
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 15, in
print(b.load_markets())
File "/usr/local/lib/python3.7/site-packages/ccxt/base/exchange.py", line 1448, in load_markets
markets = self.fetch_markets(params)
File "/usr/local/lib/python3.7/site-packages/ccxt/binance.py", line 1613, in fetch_markets
response = getattr(self, method)(query)
File "/usr/local/lib/python3.7/site-packages/ccxt/base/exchange.py", line 501, in inner
return entry(_self, **inner_kwargs)
File "/usr/local/lib/python3.7/site-packages/ccxt/binance.py", line 5854, in request
response = self.fetch2(path, api, method, params, headers, body, config, context)
File "/usr/local/lib/python3.7/site-packages/ccxt/base/exchange.py", line 2782, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
File "/usr/local/lib/python3.7/site-packages/ccxt/base/exchange.py", line 639, in fetch
self.handle_http_status_code(http_status_code, http_status_text, url, method, http_response)
File "/usr/local/lib/python3.7/site-packages/ccxt/base/exchange.py", line 1741, in handle_http_status_code
raise ErrorClass(self.id + ' ' + method + ' ' + url + ' ' + codeAsString + ' ' + reason + ' ' + body)
ccxt.base.errors.ExchangeNotAvailable: binance GET https://api.binance.com/api/v3/exchangeInfo 451 {
"code": 0,
"msg": "Service unavailable from a restricted location according to 'b. Eligibility' in https://www.binance.com/en/terms. Please contact customer service if you believe you received this message in error."
}
You are getting this error because the request to binance server is being sent from a restricted location. Binance blacklists some locations due to policies and regulation. Since you are running on aws EC2 instance, it is most likely that your virtual server is located in a restricted location. Using VPN is also risky since binance server are able to identify most of them. The solution would be to rent a virtual server that exists from binance legible locations.
My goal is to write a script in Python3 that will push data in existing table in Zoho Analytics, the script will be used by a scheduler once a week.
What I have tried to far:
I can successfully import some data using cURL commands. Like so
curl -X POST \ 'https://analyticsapi.zoho.com/api/OwnerEmail/Workspace/TableName?ZOHO_ACTION=IMPORT& ZOHO_OUTPUT_FORMAT=JSON&ZOHO_ERROR_FORMAT=JSON&ZOHO_API_VERSION=1.0&ZOHO_IMPORT_TYPE=APPEND&ZOHO_AUTO_IDENTIFY=True&ZOHO_ON_IMPORT_ERROR=ABORT&ZOHO_CREATE_TABLE=False' \ -H 'Authorization: Zoho-oauthtoken *******' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -F ZOHO_FILE='path_to_csv'
What I found out that the ReportClient provided by Zoho Analytics team
Zoho Report Client for Python is not compatible with Python 3. Hence, I installed a wrapped for this ReportClient from [here] (https://pypi.org/project/zoho-analytics-connector).
Following sample examples from Zoho website and tests in github of wrapper for Zoho in Python3, I implement something like this:
Have a class to keep my ENV variables
import os
from zoho_analytics_connector.report_client import ReportClient, ServerError
from zoho_analytics_connector.enhanced_report_client import EnhancedZohoAnalyticsClient
class ZohoTracking:
LOGINEMAILID = os.getenv("ZOHOANALYTICS_LOGINEMAIL")
REFRESHTOKEN = os.getenv("ZOHOANALYTICS_REFRESHTOKEN")
CLIENTID = os.getenv("ZOHOANALYTICS_CLIENTID")
CLIENTSECRET = os.getenv("ZOHOANALYTICS_CLIENTSECRET")
DATABASENAME = os.getenv("ZOHOANALYTICS_DATABASENAME")
OAUTH = True
TABLENAME = "My Table"
Instantiate the Client Class
def get_enhanced_zoho_analytics_client(self) -> EnhancedZohoAnalyticsClient:
assert (not self.OAUTH and self.AUTHTOKEN) or (self.OAUTH and self.REFRESHTOKEN)
rc = EnhancedZohoAnalyticsClient(
// Just setting email, token, etc using class above
...
)
return rc```
Then have a method to upload data to existing table, the data_upload() function has the problem.
def enhanced_data_upload(self):
enhanced_client = self.get_enhanced_zoho_analytics_client()
try:
with open("./import/tracking3.csv", "r") as f:
import_content = f.read()
print(type(import_content))
except Exception as e:
print(f"Error:Check if file exists in the import directory {str(e)}")
return
res = enhanced_client.data_upload(import_content=import_content, table_name=ZohoTracking.TABLENAME)
assert res
Traceback (most recent call last):
File "push2zoho.py", line 106, in <module>
sample.enhanced_data_upload()
File "push2zoho.py", line 100, in enhanced_data_upload
res = enhanced_client.data_upload(import_content=import_content, table_name=ZohoTracking.TABLENAME)
File "/Users/.../zoho_analytics_connector/enhanced_report_client.py", line 99, in data_upload
matching_columns=matching_columns)
File "/Users/.../site-packages/zoho_analytics_connector/report_client.py", line 464, in importData_v2
r=self.__sendRequest(url=url,httpMethod="POST",payLoad=payload,action="IMPORT",callBackData=None)
File "/Users/.../zoho_analytics_connector/report_client.py", line 165, in __sendRequest
raise ServerError(respObj)
File "/Users/.../zoho_analytics_connector/report_client.py", line 1830, in __init__
contHeader = urlResp.headers["Content-Type"]
TypeError: 'NoneType' object is not subscriptable
That is the error I receive. What am I missing in this puzzle? Help is appreciated
In Feb 2021 I changed this inherited Zoho code in my library.
Now it is:
contHeader = urlResp.headers.get("Content-Type",None)
which avoids the final exception you had.
I'm doing an exercise on writing a module in python 3.8 idle (Mac) to send emails from my gmail account. It is giving me the error:
smtplib.SMTPSenderRefused: (503, b'5.5.1 EHLO/HELO first.
THE COMPLETE RUNNING RESULT:
= RESTART: /Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py
person_name
Thank you for sharing!
Traceback (most recent call last):
File "/Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py", line 58, in <module>
main()
File "/Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py", line 51, in main
s.send_message(msg)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 970, in send_message
return self.sendmail(from_addr, to_addrs, flatmsg, mail_options,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 871, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (503, b'5.5.1 EHLO/HELO first. c18sm12642612wmk.18 - gsmtp', 'xxxxx#gmail.com')
The first two lines (person_name Thank you for sharing!) are from the 'message.txt' file.
MY CODE IS:
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_addr = 'xxxxxg#gmail.com'
password = 'xxxxxxxxxxx'
smtp_server = 'smtp.gmail.com'
def get_contacts(self):
names = []
emails = []
with open(self, 'r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0])
emails.append(a_contact.split()[1])
return names, emails
def read_template(self):
with open(self, 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
def main():
names, emails = get_contacts('contacts.txt') # read contacts
message_template = read_template('message.txt')
# set up the SMTP server
s = smtplib.SMTP_SSL(smtp_server)
s.ehlo()
s.connect(smtp_server,465)
s.login(from_addr, password)
# For each contact, send the email:
for name, email in zip(names, emails):
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message = message_template.substitute(person_name = name.title())
# prints out the message body for our sake
print(message)
# setup the parameters of the message
msg['From'] = from_addr
msg['To'] = email
msg['Subject'] = 'This is TEST'
# add in the message body
msg.attach(MIMEText(message, 'plain', 'utf-8'))
# send the message via the server set up earlier.
s.send_message(msg)
del msg
# Terminate the SMTP session and close the connection
s.quit()
if __name__ == '__main__':
main()
I saw this code in one of the questions asked here and it looked great to me as an example, so I wanted to try it out. But my problem turns out different than what the original one had. From the running result, it looks like the """print(message)""" command is successfully loaded. The problem occurs at """s.send_message(msg)""". I checked online several similar cases but couldn't find answer that suits this condition.
Really grateful to any help :)
Acorus
Problem solved thanks to Konrad
Swapping the .ehlo() with .connect()
& Changing the password to an authentication code generated from gmail setting 2-step verification app password. I used "mail" & "mac" to generate the verification code.
While I have never used Python to send emails, I've spent some time communicating with SMTP servers via Telnet.
You need to connect to the server first, then send EHLO, then authenticate and finally send the message. Your code seems to try sending EHLO before connecting to the server.
Try swapping those two lines.
I have defined the following function. The purpose is to make batch create entity request with dialogflow client. I am using this method after sending many individual tests did not scale well.
The problem seems to be the line that defines EntityType. Seems like "entityType" is not valid but that is what is in the dialogflow v2 documentation which is the current version I am using.
Any ideas on what the issue is?
def create_batch_entity_types(self):
client = self.get_entity_client()
print(DialogFlowClient.batch_list)
EntityType = {
"entityTypes": DialogFlowClient.batch_list
}
response = client.batch_update_entity_types(parent=AGENT_PATH, entity_type_batch_inline=EntityType)
def callback(operation_future):
# Handle result.
result = operation_future.result()
print(result)
response.add_done_callback(callback)
After running the function I received this error
Traceback (most recent call last):
File "df_client.py", line 540, in <module>
create_entity_types_from_database()
File "df_client.py", line 426, in create_entity_types_from_database
df.create_batch_entity_types()
File "/Users/andrewflorial/Documents/PROJECTS/curlbot/dialogflow/dialogflow_accessor.py", line 99, in create_batch_entity_types
response = client.batch_update_entity_types(parent=AGENT_PATH, entity_type_batch_inline=EntityType)
File "/Users/andrewflorial/Documents/PROJECTS/curlbot/venv/lib/python3.7/site-packages/dialogflow_v2/gapic/entity_types_client.py", line 767, in batch_update_entity_types
update_mask=update_mask,
ValueError: Protocol message EntityTypeBatch has no "entityTypes" field.
The argument for entity_type_batch_inline must have the same form as EntityTypeBatch.
Look how that type looks like: https://dialogflow-python-client-v2.readthedocs.io/en/latest/gapic/v2/types.html#dialogflow_v2.types.EntityTypeBatch
It has to have entity_types field, not entityTypes.