I am facing issue with the Code which is framed with Class.
Basically before It was simply a file with functions defined in it.
So When I was trying to execute the file using command python filename.py, It is working fine as needed.
Code sample is as follows:
# Getting the tenant list
# Fetch the creation_date of tenant if exists
def get_tenants():
# Fetch tenant list
tenants_list = keystone.tenants.list()
# Fetch tenant ID
for tenant in tenants_list:
tenant_id = tenant.id
.
.
.
get_tenants()
So as shown in aboce code in the file I am trying to call get_tenants function, Also it is working fine as needed with no error.
Now I have Created the Class then moved all the functions in to the same.
Above function is Rewritten as follows now.
def get_tenants(self):
# Fetch tenant list
tenants_list = keystone.tenants.list()
# Fetch tenant ID
for tenant in tenants_list:
tenant_id = tenant.id
Then I have called the Function as follows:
billing = BillingEngine()
billing.get_tenants()
But, now I am getting the error as follows:
root#devstack:/opt/open-stack-tools/billing# python new_class.py
Traceback (most recent call last):
File "new_class.py", line 281, in <module>
BillingEngine().get_tenants()
File "new_class.py", line 75, in get_tenants
tenants_list = keystone.tenants.list()
NameError: global name 'keystone' is not defined
Note: Will provide the full file if needed.
May be you must define this?
class Example(object):
keystone = Keystone()
def get_tenants(self):
self.keystone.do_something()
Related
I'm trying to update a user attribute in Active Directory using pyad. This is my code
from pyad import *
pyad.set_defaults(ldap_server="server.domain.local",
username="admin", password="password")
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
and this is the error i recieve.
Traceback (most recent call last):
File "c:\Users\Administrator\Desktop\scripts\AD-Edit-user.py", line 12, in
<module>
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\pyad-0.5.20-py3.6.egg\pyad\adobject.py", line 318, in
update_attribute
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
AttributeError: 'str' object has no attribute 'get_attribute'
This makes me assume that I need to change the attribute type from str to something else. I have verified that mail is the correct attribute name.
I know ldap connection is working because i can create a user using a similar script.
Your problem is how you use pyad.
Specifically in this line:
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
if we look at the source of pyad.adobject.ADObject, we can see the following:
def update_attribute(self, attribute, newvalue, no_flush=False):
"""Updates any mutable LDAP attribute for the object. If you are adding or removing
values from a multi-valued attribute, see append_to_attribute and remove_from_attribute."""
if newvalue in ((),[],None,''):
return self.clear_attribute(attribute)
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
self._set_attribute(attribute, 2, pyadutils.generate_list(newvalue))
if not no_flush:
self._flush()
self here is not a parameter of the function, it is a reference to the class instance. Your call includes self='testuser1' which is str.
Please lookup the documentation on how to use this function / functionality / module, here. You will notice that there is no "self"... other than looking into the source code I am not sure how you got to the conclusion you needed self.
I have no way of testing the following, but this is roughly how it should work:
# first you create an instance of the object, based on
# the distinguished name of the user object which you
# want to change
my_ad_object = pyad.adobject.ADObject.from_dn('the_distinguished_name')
# then you call the update_attribute() method on the instance
my_ad_object.update_attribute(attribute='mail', newvalue='my#email.com')
I'm having some trouble with SalesForce, I've never used it before so I'm not entirely sure what is going wrong here. I am using the simple_salesforce python module. I have successfully pulled data from SalesForce standard objects, but this custom object is giving me trouble. My query is
result = sf.query("Select Name from Call_Records__c")
which produces this error:
Traceback (most recent call last):
File "simple.py", line 15, in <module>
result = sf.query("Select Name from Call_Records__c")
File "/usr/local/lib/python2.7/dist-packages/simple_salesforce/api.py", line 276, in query
_exception_handler(result)
File "/usr/local/lib/python2.7/dist-packages/simple_salesforce/api.py", line 634, in _exception_handler
raise exc_cls(result.url, result.status_code, name, response_content)
simple_salesforce.api.SalesforceMalformedRequest: Malformed request https://sandbox.company.com/services/data/v29.0/query/?q=Select+Name+from+Call_Records__c. Response content: [{u'errorCode': u'INVALID_TYPE', u'message': u"\nSelect Name from Call_Records__c\n ^\nERROR at Row:1:Column:18\nsObject type 'Call_Records__c' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name.
Please reference your WSDL or the describe call for the appropriate names."}]
I've tried it with and without the __c for both the table name and the field name, still can't figure this out. Anything blatantly wrong?
Make sure your result is Call_Records__c/CallRecords__c
Call_Records__c result = sf.query("Select Name from Call_Records__c")
Or
CallRecords__c result = sf.query("Select Name from CallRecords__c")
Try using -
result = sf.query("Select Name from CallRecords__c")
I am trying to get my head around migrating to google admin sdk. I am trying to add members to a group (mailing list) using python. I have figured out how to create the group, but can't figure out how to add members. I have read this page: https://developers.google.com/admin-sdk/directory/v1/reference/members/insert but cannot figure out how to map it to python (I have little experience with REST or python, I'm trying to learn).
This is how I am trying to do it:
import httplib2
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
keyFile = file(p12File, 'rb')
key = keyFile.read()
keyFile.close()
credentials = SignedJwtAssertionCredentials(serviceAccount,
key,
scope,
prn=superAdmin)
http = httplib2.Http()
httplib2.debuglevel = False #change this to True if you want to see the output
http = credentials.authorize(http=http)
directoryService = build(serviceName='admin', version='directory_v1', http=http)
# THIS DOES NOT WORK
groupinfo = {'email': 'wibble#XXX.co.uk'}
directoryService.groups().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
When I run that I get:
Traceback (most recent call last):
File "add-member-to-group.py", line 58, in <module>
directoryService.groups().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 604, in method
raise TypeError('Got an unexpected keyword argument "%s"' % name)
TypeError: Got an unexpected keyword argument "groupKey"
I would be grateful if someone could help me to figure out how to do this.
After further hunting around I worked it out. That last line should have been:
directoryService.members().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
i.e. directoryService.members()... not directoryService.groups()...
The examples here helped me to work it out.
I've been using Python to access the Rdio API a fair bit so decided to add a couple methods to the Rdio module to make life easier. I keep getting stymied.
Here, as background, is some of the Rdio Python module provided by the company:
class Rdio:
def __init__(self, consumer, token=None):
self.__consumer = consumer
self.token = token
def __signed_post(self, url, params):
auth = om(self.__consumer, url, params, self.token)
req = urllib2.Request(url, urllib.urlencode(params), {'Authorization': auth})
res = urllib2.urlopen(req)
return res.read()
def call(self, method, params=dict()):
# make a copy of the dict
params = dict(params)
# put the method in the dict
params['method'] = method
# call to the server and parse the response
return json.loads(self.__signed_post('http://api.rdio.com/1/', params))
Okay, all well and good. Those functions work fine. So I decided to create a method that would copy a playlist with key1 into a playlist with key2. Here's the code:
def copy_playlist(self, key1, key2):
#get track keys from first playlist
playlist = self.call('get', {'keys': key1, 'extras' : 'tracks'})
track_keys = []
for track in tracks:
key = track['key']
track_keys.append(key)
#convert track list into single, comma-separated string (which the API requires)
keys_string = ', '.join(track_keys)
#add the tracks to the second playlist
self.call('addToPlaylist', {'playlist' : key2, 'tracks' : keys_string})
This code works fine if I do it from the terminal or in an external Python file, but for some reason when I include it as part of the Rdio class, then initiate the Rdio object as rdio and call the playlist method, I always get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "rdio_extended.py", line 83, in copy_playlist
NameError: global name 'rdio' is not defined
I can't seem to get around this. There's probably a simple answer - I'm pretty new to programming - but I'm stumped.
UPDATE: Updated code formatting, and here's the actual code that creates the Rdio object:
rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (RDIO_TOKEN, RDIO_TOKEN_SECRET))
And then this is the line to call the playlist-copying function:
rdio.copy_playlist(key1, key2)
That results in the NameError described above.
I have a python script that takes a generated CSV and uploads it to Google Docs. It can upload it just fine, put I cannot seem to get it to replace the data, it returns an error I cannot find reference to.
Le Code:
import gdata.auth
import gdata.docs
import gdata.docs.service
import gdata.docs.data
import gdata.docs.client
email = 'admin#domain.com'
CONSUMER_KEY='domain.com'
CONSUMER_SECRET='blah54545blah'
ms_client = gdata.docs.client.DocsClient('Domain_Doc_Upload')
ms_client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(CONSUMER_KEY, CONSUMER_SECRET, email)
url = 'http://docs.google.com/feeds/documents/private/full/sd01blahgarbage'
ms = gdata.data.MediaSource(file_path="C:\\people.csv", content_type='text/csv')
csv_entry2 = ms_client.Update(url, ms)
It returns:
Traceback (most recent call last):
File "so_test.py", line 19, in <module>
csv_entry2 = ms_client.Update(ms, url)
File "build\bdist.win-amd64\egg\gdata\client.py", line 717, in update
AttributeError: 'MediaSource' object has no attribute 'to_string'
I cannot find anything about the 'to_string' attribute, so I am lost on the trace. ANy help, much appreciated.
I took a look at the docs and it looks like the Update method takes (entry, ms) where entry needs to be a gdata.docs.data.DocsEntry object. You should be able to get the DocsEntry object by getting a feed from your client.
feed = client.GetDocList()