Refer to variables dynamically - python

Context: I am creating a Django management command which will accept a positional argument. This argument is a location. My goal is to use the location value to refer to a corresponding variable.
I have a global variable named Boston_webhook. This is a simple string which contains a long URL which is just a MSteams webhook...
I have an additional global variable named Budapest_webhook which contains the same data type, but instead refers to a webhook related to the Budapest location.
In my script, a connector variable has to be defined in order to send the message to the correct place.
myTeamsMessage = pymsteams.connectorcard()
If someone entered python manage.py report Boston I want to insert this into the connector params, but I am unsure how to refer to variables dynamically.
Is it possible to refer to Boston_webhook when the location == 'Boston' using some sort of concatenation...?
something like myTeamsMessage = pymsteams.connectorcard(location + _webhook) would be ideal
I would like to avoid using conditionals as it is not scalable. I need to be able to add locations to the database without having to change code...

Use dictionary to map names of webhooks to webhooks itself - like this
webhooks = {
"Boston": "boston url",
"Budapest": "budapest url"
}
Now you can refer to your webhooks like this
# this will give you Boston webhook
myTeamsMessage = pymsteams.connectorcard(location + webhooks["Boston"])
This is simpliest way to do it. I think it would be better to create new class only for this and convert that class to string using a method , but this would be enough if you don't need anything more complex

I was able to determine a suitable solution;
myTeamsMessage = pymsteams.connectorcard(webhooks["{}".format(location)])
where the webhooks are stored in a dictionary keyed by location name.
i.e:
webhooks = {'Boston':'www.url.com',
'Budapest':'www.url1.com',
}
Thanks for the recommendations everyone!

Related

Using ArcGIS Python API, how can I share all items in a specific group from ArcGIS online with the public?

I'm completely new at programming. As an administrator, I need to update items in an ArcGIS Online group to be shared with everyone. I'm building the script in Jupyter notebook. I found the below link on arcig python api page, and I've been able to get the items from the group, but I don't know how to loop and update the share of each item in the group. https://developers.arcgis.com/python/guide/accessing-and-managing-groups/
You could do a content search for the items and you can use the share method. This is not tested but should work.
from arcgis.gis import GIS
ago_gis = GIS()
webmaps = ago_gis.content.search("My Web Map", item_type="Web Map")
for x in webmaps:
x.share(everyone=True)
I was looking to do something similar but found that I had to use the share method carefully. The share method has default values of False for the 'everyone' and 'org' parameters. If you do not specify them, they default to False or do not share with everyone / do not share with my org.
In my case, I was trying to share an item with a group I made so I used the share method and only passed it the group argument. While it shared it with the intended group, it used the default values of the optional arguments 'everyone' and 'org' which set the items to only be viewed by the 'owner'. This broke any public facing apps and maps which this item was a part of.
In order to modify only the group setting, I needed to call for the item's current sharing settings (using the shared_with property), modify them as needed, and pass them into the share method with the modifications. This allowed me to keep them shared with the public or my org, but also add them to the group I needed them added to.
Here's the code I used in my notebook:
item_sharing_status = item.shared_with
item.share(everyone = item_sharing_status['everyone'],
org = item_sharing_status['org'],
groups = item_sharing_status['groups'] + [backup_group.id])
You can also put the items to share in a list with :
gis.content.share_items(items=[item1, item2, item3], everyone=True, org=True)
link to the doc

Google Workspace Reports API - Customer Usage Metrics - Get All Gmail Parameters

I am using Google Workspace Reports API to pull customer usage metrics for GMail via Python client. I would like to pull all parameters, but would prefer to not list out each of them individually (ie: service.customerUsageReports().get(date=temp, parameters='gmail:num_1day_active_users,gmail:num_30day_active_users,gmail:num_emails_received').execute())
I have tried parameters='gmail' and parameters='gmail:*' to no avail.
Is there a shorthand for pulling all customer usage metrics related to GMail, or do you have to pass each parameter individually?
I don't think you can. But if you like to have automated and have different parameters in multiple calls, you can do these steps:
Store all possible parameters in an array.
Filter the array using regex.
Append all filtered elements into a string via comma
Pass the string as the parameter
Code:
import re
parameters = [
'accounts:num_30day_logins',
'accounts:num_7day_logins',
'accounts:num_1day_logins',
'accounts:num_disabled_accounts',
'accounts:apps_total_licenses',
'accounts:apps_used_licenses',
'accounts:num_users_2sv_enrolled',
'gmail:num_emails_received',
'gmail:num_inbound_spam_emails',
'gmail:num_inbound_non_spam_emails',
'gmail:num_inbound_delivered_emails',
'gmail:num_emails_sent',
'gmail:num_inbound_rejected_emails',
'gmail:num_inbound_rerouted_emails',
'gplus:num_video_calls',
'gplus:num_video_conferences',
'gplus:num_video_conferences_cfm',
'gplus:total_video_call_minutes',
'docs:num_docs']
separator = ','
r_gmail = re.compile("gmail.*")
r_accounts = re.compile("accounts.*")
gmail_list = list(filter(r_gmail.match, parameters))
accounts_list = list(filter(r_accounts.match, parameters))
gmail_parameters = separator.join(gmail_list)
accounts_parameters = separator.join(accounts_list)
# contains gmail parameters
print(gmail_parameters)
# contains accounts parameters
print(accounts_parameters)
Hopefully you get the idea of the above code. This will be helpful when your script gets large and lots of parameters come and go.
This way, you don't need to maintain numerous long lists of parameters. Just one and you only need to create a regex for it to be filtered the way you like it.
Output:

List users in a group LDAP python

I'm new to LDAP. So I don't really know all my terms and fully understand all the terms yet. However, I'm working on an existing system and all the set up is done. I'm just adding a method to it.
I'm trying to write a method in Python using LDAP query. I've played around on LDAP Browser and can see that my query is correct. However, I'm not sure how to put it in a python method to return a list. The method needs to return a list of all the users' username. So far I have:
def getUsersInGroup(self, group):
searchQuery= //for privacy Im not going to share this
searchAttribute=["username"]
results = self.ldap.search_s(self.ldap_root, ldap.SCOP_SUBTREE,
searchQuery, searchAttribute)
I'm unsure how to go from here. I don't fully understand what the search_s method returns. I read online that its better to use search_s over search method because the while loop can be avoided. Could you please provide and example of where I can go from here. Thanks.
You need to perform a LDAP search something like:
# Find all Groups user is a member of:
import ldap
l = ldap.initialize("ldap://my_host")
l.simple_bind_s("[my_dn]", "[my_pass]")
myfilter = "(member=(CN=UserName,CN=Users,DC=EXAMPLE,DC=COM))"
# for all groups including Nested Groups (Only Microsoft Active Directory)
# (member:1.2.840.113556.1.4.1941:=CN=UserName,CN=Users,DC=EXAMPLE,DC=COM)
ldap_result = l.search("[BASE_DN]", ldap.SCOPE_SUBTREE, myfilter, None)
res_type, data = l.result(ldap_result, 0)
print(data)
You need to use the full dn of the user.

Google Directory API groups

I am trying to use Google's admin directory API (with Google's python library).
I am able to list the users on the directory just fine, using some code like this:
results = client.users().list(customer='my_customer').execute()
However, those results do not include which groups the users are a member of. Instead, it appears that once I have the list of users, I then have to make a call to get a list of groups:
results = client.groups().list(customer='my_customer').execute()
And then go through each group and call the "members" api to see which users are in a group:
results = client.members().list(groupKey='[group key]').execute()
Which means that I have to make a new request for every group.
It seems to be horribly inefficient. There has to be a better way than this, and I'm just missing it. What is it?
There is no better way than the one you described (yet?): Iterate over groups and get member list of each one.
I agree that is not the answer you want to read, but it is also the way we do maintenance over group members.
The following method should be more efficient, although not 100% great :
For each user, call the groups.list method and pass the userKey parameter to specify that you only want groups who have user X as a member.
I'm not a Python developper, but it should look like this :
results = client.groups().list(customer='my_customer',userKey='user#domain.com').execute()
For each user:
results = client.groups().list(userKey=user,pageToken=None).execute()
where 'user' is the user's primary/alias email address or ID
This will return a page of groups the user is a member of, see:
https://developers.google.com/admin-sdk/directory/v1/reference/groups/list

grabbing HTTP GET parameter from url using Box API in python

I am dealing with the Box.com API using python and am having some trouble automating a step in the authentication process.
I am able to supply my API key and client secret key to Box. Once Box.com accepts my login credentials, they supply me with an HTTP GET parameter like
'http://www.myapp.com/finish_box?code=my_code&'
I want to be able to read and store my_code using python. Any ideas? I am new to python and dealing with APIs.
This is actually a more robust question than it seems, as it exposes some useful functions with web dev in general. You're basically asking how to separate my_code in the string 'http://www.myapp.com/finish_box?code=my_code&'.
Well let's take it in bits and pieces. First of all, you know that you only really need the stuff after the question mark, right? I mean, you don't need to know what website you got it from (though that would be good to save, let's keep that in case we need it later), you just need to know what arguments are being passed back. Let's start with String.split():
>>> return_string = 'http://www.myapp.com/finish_box?code=my_code&'
>>> step1 = return_string.split('?')
["http://www.myapp.com/finish_box","code=my_code&"]
This will return a list to step1 containing two elements, "http://www.myapp.com/finish_box" and "code=my_code&". Well hell, we're there! Let's split the second one again on the equals sign!
>>> step2 = step1[1].split("=")
["code","my_code&"]
Well lookie there, we're almost done! However, this doesn't really allow any more robust uses of it. What if instead we're given:
>>> return_string = r'http://www.myapp.com/finish_box?code=my_code&junk_data=ohyestheresverymuch&my_birthday=nottoday&stackoverflow=usefulplaceforinfo'
Suddenly our plan doesn't work. Let's instead break that second set on the & sign, since that's what's separating the key:value pairs.
step2 = step1[1].split("&")
["code=my_code",
"junk_data=ohyestheresverymuch",
"my_birthday=nottoday",
"stackoverflow=usefulplaceforinfo"]
Now we're getting somewhere. Let's save those as a dict, shall we?
>>> list_those_args = []
>>> for each_item in step2:
>>> list_those_args[each_item.split("=")[0]] = each_item.split("=")[1]
Now we've got a dictionary in list_those_args that contains key and value for every argument the GET passed back to you! Science!
So how do you access it now?
>>> list_those_args['code']
my_code
You need a webserver and a cgi-script to do this. I have setup a single python script solution to this to run this. You can see my code at:
https://github.com/jkitchin/box-course/blob/master/box_course/cgi-bin/box-course-authenticate
When you access the script, it redirects you to box for authentication. After authentication, if "code" is in the incoming request, the code is grabbed and redirected to the site where tokens are granted.
You have to setup a .htaccess file to store your secret key and id.

Categories

Resources