OpenStack Python Nova API Getting Specific Limit Values? - python

I've been using the following code to get the limits:
compute_limits = novaClient.limits.get().absolute
for s in compute_limits:
print s.name + " = " + str(s.value)
However I only want specific values from the limits.get(), namely totalRAMUsed and maxTotalRAMSize. There seems to be very little on the internet about using the Python API (mainly all about the CLI). Is there a way to get these specific values to avoid displaying all the limit values?

You can display only one specific value:
compute_limits = novaClient.limits.get().absolute
for s in compute_limits:
if s.name == 'totalRAMUsed':
print s.name + " = " + str(s.value)
break
compute_limits is generator, you can't receive only one specific value by limit name. But you can convert compute_limits to dict. For example:
compute_limits = novaClient.limits.get().absolute
l = list(compute_limits)
limits = dict(map(lambda x: (x.name, x.value), l))
print limits['totalRAMUsed']

Related

how to get a key and values and combine in list

data = [{"name":"Anne", "followers":["Brian"]}, {"name":"Cindy", "followers":["Brian","G
osh","Anne"]},{"name":"Dave", "followers":[]}]
output : [{"name": ["Brian"] , "follows":["Anne","Cindy"]},...] etc...
my code from now :
from operator import itemgetter
data = data = [{"name":"Anne", "followers":["Brian"]}, {"name":"Cindy", "followers":["Brian","Gosh","Anne"]},{"name":"Dave", "followers":[]}]
x = list(map(itemgetter('followers'), data))
y = list(map(itemgetter('name') ,data))
print("name : " + str(x), " follow : " + str(y))
how to get combine same values and get from key ?
i think this is a list in dict ...sorry if mistake . i am newbie using this language
It looks like there's a couple errors in your code. First off, in the place where you're defining x and y, it needs to be on separate lines. In other words, change
x = list(map(itemgetter('followers'), data)) y = list(map(itemgetter('name') ,data))
to
x = list(map(itemgetter('followers'), data))
y = list(map(itemgetter('name') ,data))
to be on separate lines. Also, since that is the only error in your code it looks like, what is it that you are trying to achieve with this code? Since when I run it, all it outputs is name : [['Brian'], ['Brian', 'Gosh', 'Anne'], []] follow : ['Anne', 'Cindy', 'Dave']. Other than that, good luck with your programming adventures!

Python JSON get request for multiple websites

I'm trying to make a json get request on multiple urls.
(I'm new to programming as you will see below.)
My goal is to run this python script with multiple links. The only thing needs to be changed is the "b" part of the link, so it can run multiple searches with different numbers (strings), preferably using a list of numbers and exporting all the results to a csv list.
My question is: How should I change the code so I can use a list of numbers for "b" and get all the requests? (like a loop)
Please find below my code and thank you for your time.
import requests
import json
a = 'https://www.g2a.com/lucene/search/filter?jsoncallback=jQuery111002521088376353553_1491736907010&skip=28837%2C28838%2C28847%2C28849%2C28852%2C28856%2C28857%2C28858%2C28859%2C28860%2C28861%2C28862%2C28863%2C28867%2C28868%2C28869%2C29472%2C29473%2C29474%2C29475%2C29476%2C29482%2C29486%2C33104&minPrice=0.00&maxPrice=640.00&cn=&kr=&stock=all&event=&platform=0&search=&genre=0&cat=0&sortOrder=popularity+desc&start=0&rows=12&steam_app_id='
b = '515220'
c = '&steam_category=&steam_prod_type=&includeOutOfStock=false&includeFreeGames=false&_=1491736907012'
d = a + b + c
r = requests.get(d)
json_object = json.loads('{"data":%s}}' % (response.content.decode("utf-8").replace("jQuery111002521088376353553_1491736907010(", "")[:-2].replace("\'", "")))
for game in json_object["data"]["docs"]:
print ("Name: %s (Price: %s)" % (game["name"], game["minPrice"]))
You can loop over the list of b values like below,
l = [1,2,3,4]
for b in l:
d = a + b + c
r = requests.get(d)
json_object = json.loads('{"data":%s}}' % (response.content.decode("utf-8").replace("jQuery111002521088376353553_1491736907010(", "")[:-2].replace("\'", "")))
for game in json_object["data"]["docs"]:
print ("Name: %s (Price: %s)" % (game["name"], game["minPrice"]))

How do I split and reconstruct a variable name while holding its original value

Is it possible to split variables that have already been assigned values, and re-piece them back together to hold those same previous values?
For Example:
URLs.QA.Signin = 'https://qa.test.com'
TestEnvironment = 'QA'
CurrentURL = 'URLs.' + TestEnvironment + '.Signin'
print(CurrentURL)
Outputs as: 'URLs.QA.Signin'
but I would like it to:
Output as: 'https://qa.test.com'
The purpose is so I can plug in any value to my 'TestEnvironment' variable and thus access any of my massive list of URL's with ease =P
I am green with Python. Your time and efforts are greatly appreciated! =)
Based upon evanrelf's answer, I tried and loved the following code!:
This is exactly what i'm looking for, I might be over complicating it, any suggestions to clean up the code?
urls = {}
environment = 'qa'
district = 'pleasanthill'
url = environment + district
urls[url] = 'https://' + environment + '.' + district + '.test.com'
print(urls[url])
Output is: https://qa.pleasanthill.test.com
I would recommend you look into Python's dictionaries.
urls = {}
urls['qa'] = 'https://qa.test.com'
test_environment = 'qa'
print(urls[test_environment])
// => https://qa.test.com
I believe to my comprehension that you are trying to input a string and get a new string (the url) back. The simplest answer that I can understand is to use a dictionary. An example of this is by simply doing
URLS = {'sheep' : 'wool.com', 'cows' : 'beef.com'}
either this or by using two arrays and referencing a common index, but who wants to do that :p

How to automatically create list with 550 elements each, without the need to rename each one manually?

I would heavily need your help to simplify a code that allows me to have a data analysis on salesforce leads.
I have the following dataframes, which as you can see are split due to python limit on managing more than 550 objects in a single list.
Iterlist = list()
for x in range(0, int(len(List)/550)+1):
m = List[550*x: 550*x+550]
Iterlist.append(m)
Iterlist0= pd.DataFrame(Iterlist[0])
Iterlist1= pd.DataFrame(Iterlist[1])
Iterlist2= pd.DataFrame(Iterlist[2])
...and so on until the initial longer list is split
...
converted in the following lists for formatting reasons:
A= Iterlist0["Id"].tolist()
mylistA = "".join(str(x)+ "','" for x in A)
mylistA = mylistA[:-2]
mylistA0 = "('" + mylistA + ")"
B = Iterlist1["Id"].tolist()
mylistB = "".join(str(x)+ "','" for x in B)
mylistB = mylistB[:-2]
mylistB1 = "('" + mylistB + ")"
C = Iterlist2["Id"].tolist()
mylistC = "".join(str(x)+ "','" for x in C)
mylistC = mylistC[:-2]
mylistC2 = "('" + mylistC + ")"
and so on...
...
I want to create a loop that allows me to query from salesforce each of the lists using the following code template for example:
queryA='SELECT '+cols[1]+', '+cols[2]+', '+cols[3]+', '+cols[4]+', '+cols[5]+', '+cols[6]+', '+cols[7]+', '+cols[8]+' FROM LeadHistory WHERE LeadId IN '+mylistA0
and then finally:
sf = Salesforce(username='xxx', password='xxx', security_token='xxx')
leadhistory = sf.query_all(queryA)
I donĀ“t want to write over and over numerous dataframes with specific names, lists and queries in order to get to the result. I would like to have a line for each of the codes written above, and let python automatically update the naming according to the number of 550 elements list.
I am new to this programming language and any tip would help me a lot. I think is possible to simplify it a lot but no idea how can be done.
Thanks in advance!

Getting names of groups in Windows Active Directory using Python

I am using this library to interact with Active Directory in Python:
http://timgolden.me.uk/python/ad_cookbook.html
I am trying to access the group names like this:
groups = []
for group in active_directory.search(objectClass='group'):
groups.append(str(group.cn))
My first issue is that group.cn gets the display name of the group instead of the actual object name. How do I get the object name?
My second issue is that running this code takes up HUGE amounts of memory. When there are thousands of groups in Active Directory, my program will use hundreds of megs or even a gig or two of memory. This is especially true when there are groups nested inside other groups. Is there a reason why after I've gotten all the group names, I am still using all that memory?
This is what I ended up doing:
results = None
try:
connection = ldap.open(str(self.hostnameLineEdit.text()))
connection.simple_bind_s(str(self.usernameLineEdit.text()), str(self.passwordLineEdit.text()))
userDNSDomain = os.environ['USERDNSDOMAIN']
userDNSDomain = userDNSDomain.split('.')
base = ""
for dc in userDNSDomain:
base += "dc=" + dc + ","
base = base[:-1]
#print base
resultID = connection.search(base,ldap.SCOPE_SUBTREE,'(objectClass=group)')
resultTypes, results = connection.result(resultID, 0)
except ldap.LDAPError, e:
self.messageBox("LDAP Error: " + str(e))
if results != None:
while results[0][0] != None:
#print results[0][1]['cn']
self.groupsListWidget.addItem(QString(results[0][1]['cn'][0]))
resultTypes, results = connection.result(resultID, 0)

Categories