I need to delete an attribute from a Dictionary object. I am trying to do this with "del," but it is not working for me.
from suds.client import Client
from sys import argv
cmserver = '***my-server-host-name***'
cmport = '8443'
wsdl = 'file:///code/AXL/axlsqltoolkit/schema/10.5/AXLAPI.wsdl'
location = 'https://' + cmserver + ':' + cmport + '/axl/'
username = argv[1]
password = argv[2]
client = Client(url=wsdl,location=location, username=username, password=password)
result = client.service.getPhone(name='SEP64AE0CF74D0A')
del result['_uuid']
The Code fails with:
Traceback (most recent call last):
File "AXL-Get-Phone.py", line 27, in <module>
del result['_uuid']
AttributeError: __delitem__
Sample [print(str(result))] output of the object I am trying to delete '_uuid' from:
(reply){
return =
(return){
phone =
(RPhone){
_uuid = "{D1246CFA-E02D-0731-826F-4B043CD529F1}"
First, you'll need to convert results into a dict. There is a suds.client.Client class method dict which will do this for you. See the documentation for suds.client.Client.
result = Client.dict(client.service.getPhone(name='SEP64AE0CF74D0A'))
del result['_uuid']
Also, you may simply be able to delete the _uuid attribute, for example:
result = client.service.getPhone(name='SEP64AE0CF74D0A')
del result._uuid
Related
I keep getting an error regarding my list having no attribute 'strip'.
I'm trying to send cisco cmds to switches listed in a csv. I pull from the csv, have the csv reader read it, and then do a row. Sometimes if I play with the indents only the last csv value is used.
from netmiko import ConnectHandler
import pandas
import getpass
import csv
from csv import DictReader
usr = input("Enter your Username: ")
passwd = getpass.getpass('Please Enter Password: ')
command = input('Enter Cmd You Wish to Send: ')
with open('Scripts/SWList.csv', 'r') as csv_list:
switches = csv.reader(csv_list)
for row in switches:
Cisco_Switches = {
'device_type': 'cisco_ios',
'host': row,
'username': usr,
'password': passwd
}
device = ConnectHandler(**Cisco_Switches)
output = device.send_command(command)
if ('% Unknown command' in output):
(
print('Error Sending Command for ' + row + '!')
)
else:
(
print('Command Sent Successfully to ' + row + '...')
)
filename = 'Scripts/' + row + '.txt'
save_file = open(filename, "a")
save_file.write(output)
save_file.close()
device.disconnect()`
If I move device = connecthandler(**Cisco_Switches) to the left it will run, but only for the last value in the csv.
CSV formatting below:
IP
172.16.X.X
172.16.X.X
172.16.X.X
Error:
Traceback (most recent call last):
File "c:\Networking\Scripts\ConfigMultSwitches.py", line 21, in <module>
device = ConnectHandler(**Cisco_Switches)
File "C:\Users\xxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\netmiko\ssh_dispatcher.py", line 365, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "C:\Users\xxx\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\netmiko\base_connection.py", line 312, in __init__
self.host = host.strip()
AttributeError: 'list' object has no attribute 'strip'
The row returned by the csv.reader call is a list, not a string. The split method need to be called on a string. You should be referencing the string itself in the list (I assume the zero index?). Try 'host': row[0]. That's assuming the host is in the first column of the CSV table.
I looked up lots of similar question, but sadly none of them are close to mine.
I have a simple script that checks balance from exchange. It is a part of an unofficial API wrapper written in python and my understanding is it stuck somewhere between python 2 and python 3. I fixed errors one by one, but I'm completely stuck with this one. Here is the code:
import urllib.parse
import urllib.request
import json
import time
import hmac,hashlib
class Poloniex():
def __init__(self, APIKey, Secret):
self.APIKey = APIKey
self.Secret = Secret
def api_query(self, command, req={}):
self.req = bytes(req, 'utf-8')
req['command'] = command
req['nonce'] = int(time.time()*1000)
post_data = urllib.parse.quote(req)
my_key = self.Secret
my_key_bytes = bytes(my_key, 'utf-8')
post_data_bytes = bytes(post_data, 'utf-8')
sign = hmac.new(my_key_bytes, post_data_bytes, hashlib.sha512).hexdigest()
headers = {
'Sign': sign,
'Key': my_key_bytes,
#'Content-Type': 'application/json'
}
ret = urllib.request.urlopen(
urllib.parse.quote('https://poloniex.com/tradingApi', safe=':/'), post_data_bytes,
headers)
jsonRet = json.loads(ret.read())
return self.post_process(jsonRet)
def returnBalances(self):
return self.api_query('returnBalances')
inst = Poloniex("AAA-BBB", "123abcdef")
balance = inst.returnBalances()
print(balance)
Looks like I have a problem with syntax, but even after RTM I can't figure this out. It throws me:
TypeError: encoding without a string argument
and before that I had:
TypeError: quote_from_bytes() expected bytes
which was 'fixed' by
self.req = bytes(req, 'utf-8')
Can anybody please point me in the right direction?
Thank you.
UPD
sorry, forgot the traceback
Traceback (most recent call last):
File "script.py", line 43, in <module>
balance = inst.returnBalances()
File "script.py", line 37, in returnBalances
return self.api_query('returnBalances')
File "script.py", line 18, in api_query
post_data = urllib.parse.quote(req)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 775, in quote
return quote_from_bytes(string, safe)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 800, in quote_from_bytes
raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes
In your code, req is a dictionary, but you're attempting to convert it to bytes here: self.req = bytes(req, 'utf-8'), which doesn't make sense since only strings can be converted this way.
The second error is caused by the fact that urllib.parse.quote works only with strings and bytes, but you're passing it a dictionary.
Apologize pretty new to python and I'm not 100% sure why this is failing since all example code I see is really similar.
import io
import json
import argparse
from object_detection.helpers import average_bbox
ap = argparse.ArgumentParser()
ap.add_argument("-o","--output",required=True,help="Output file name.")
ap.add_argument("-c","--class",help="Object class name")
ap.add_argument("-a","--annotations",required=True,help="File path annotations are located in")
args = vars(ap.parse_args())
(avgW,avgH) = average_bbox(args["annotations"])
if args["class"] is None:
name = args["annotations"].split("/")[-1]
else:
name = args["class"]
with io.open(args["output"],'w') as f:
o = {}
o["class"] = name
o["avgWidth"] = avgW
o["avgHeight"] = avgH
f.write(json.dumps(o,f))
name, avgW and avgH are all valid values. avgW and avgH are numbers and name is a string. The output seems like a valid path to create a file.
Error I get is
Traceback (most recent call last):
File "compute_average_bbox.py", line 19, in <module>
with io.open(argparse["output"],'w') as f:
TypeError: 'module' object has no attribute '__getitem__'
Any help would be appreciated.
I have a query that's grabbing data from a database and returning the values so I can parse.
def executeScriptsFromFile(monitor):
# Open and read the file as a single buffer
fd = open(os.path.join(BASE_DIR, 'sql/{0}.sql'.format(monitor)), 'r')
if args.alias:
sql_query = fd.read().format("'" + args.alias + "'")
else:
sql_query = fd.read()
fd.close()
# Execute SQL query from the input file
cursor.execute(sql_query)
result = cursor.fetchone()
return result
The query can differ so I'm trying to build in logic so it will skip part if JobCount isn't one of the values.
query_data = executeScriptsFromFile(args.monitor)
print query_data
if query_data.JobCount:
print query_data.JobCount
else:
send_status = send_data(job_data)
print send_status
Unfortunately I get the following traceback. How do I ignore the value if it isn't there?
Traceback (most recent call last):
File "tidal-zabbix.py", line 92, in <module>
if query_data.JobCount:
AttributeError: 'pyodbc.Row' object has no attribute 'JobCount'
If you want to check whether 'JobCount' is an attribute of query_data use hasattr()
if hasattr(query_data, 'JobCount'):
print query_data.JobCount
else:
send_status = send_data(job_data)
print send_status
I just want to download an image. Then upload it to Amazon S3. But it's not working.
'builtin_function_or_method' object has no attribute 'StringIO'
Traceback (most recent call last):
File "flickrDump.py", line 16, in <module>
imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest")
File "../lib/s3.py", line 52, in upload_thumbnail
k.set_contents_from_string(thumbnail_data)
File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 539, in set_contents_from_string
self.set_contents_from_file(fp, headers, replace, cb, num_cb, policy)
File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 455, in set_contents_from_file
self.send_file(fp, headers, cb, num_cb)
File "/usr/lib/pymodules/python2.6/boto/s3/key.py", line 366, in send_file
return self.bucket.connection.make_request('PUT', self.bucket.name,
AttributeError: 'str' object has no attribute 'connection'
My code to download it and upload it is this:
tdata = tools.download("http://farm5.static.flickr.com/4148/5124630813_c11b05e6da_z.jpg")
imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest")
print imgpath
The library I'm using is the s3 library. I downloaded this somewhere, so it should be standard.
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto.s3.bucket import Bucket
import datetime
ACCESSKEY = 'MYKEY'
SECRETKEY = 'MYSECRET'
def get_bucket_path(bucket,filename,https=False):
path = None
if isinstance(bucket, Bucket):
path = bucket.name
else:
path = bucket
if https:
return "https://s3.amazonaws.com/%s/%s" % (path, filename)
else:
return "http://s3.amazonaws.com/%s/%s" % (path, filename)
def _aws_keys():
return ACCESSKEY, SECRETKEY
def _conn():
key,secret = _aws_keys()
return S3Connection(key,secret)
def cache_bucket(conn = _conn()):
bucket = conn.create_bucket('mimvicache') bucket.make_public()
return bucket
class AwsException(Exception):
def __init__(self,value):
self.errorval = value
def __str__(self):
return repr(self.errorval)
def upload_thumbnail(thumbnail_name,thumbnail_data=None,thumbnail_path=None,bucket=cache_bucket
(),conn=_conn(),notes=None,image_id=None):
k = Key(bucket)
k.key = thumbnail_name
if notes is not None:
k.set_metadata("notes",notes)
if image_id is not None:
k.set_metadata("image_id",image_id)
if thumbnail_data is not None:
k.set_contents_from_string(thumbnail_data)
elif thumbnail_path is not None:
k.set_contents_from_filename(thumbnail_path)
else:
raise AwsException("No file name")
k.set_acl('public-read')
return get_bucket_path(bucket.name,k.key)
Can someone help me upload this image to S3?
In your code:
return self.bucket.connection.make_request('PUT', self.bucket.name,......
AttributeError: 'str' object has no attribute 'connection'
This means that some how self.bucket is evaluated to a string and you can not obviously call method "connection" on it.
So for further analysis, look at the function upload_thumbnail, it expects bucket=cache_bucket() as argument. That is it expects a bucket object.
def upload_thumbnail(thumbnail_name,thumbnail_data=None,thumbnail_path=None,bucket=cache_bucket
(),conn=_conn(),notes=None,image_id=None)
What you are passing in your code is string !! -> (bucket="fabletest")
imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket="fabletest")
Your code should be some thing like this. you might have to sanitize this. But the key is to pass the bucket and connection object to function upload_thumbnail function.
import S3
connection = S3.AWSAuthConnection('your access key', 'your secret key')
buck = connection.create_bucket('mybucketname')
tdata = tools.download("http://farm5.static.flickr.com/4148/5124630813_c11b05e6da_z.jpg")
imgpath = s3.upload_thumbnail(thumbnail_name=tools.randomString(10), thumbnail_data=tdata,bucket=buck, conn=connection)
print imgpath