How to send current user_id to Sentry scope.user()? - python

Project is in PYTHON
I want to log all current users affected by some random "IndexError" (For instance) error.
Currently when I try to do this:
from sentry_sdk import push_scope, capture_exception
with push_scope() as scope:
scope.user = {"email": user.email}
capture_exception(ex)
it sets first user's email and that doesn't change with other users facing the same error.
I want to see all users who were affected by that error.

Related

Marking an email as read python

I'd like to mark an email as read from my python code. I'm using
from exchangelib import Credentials, Account
my_account = Account(...)
credentials = Credentials(...)
to get access to the account. This part works great. I then get into my desired folder using this
var1 = my_account.root / 'branch1' / 'desiredFolder'
Again, this works great. This is where marking it as read seems to not work.
item = var1.filter(is_read=False).values('body')
for i, body in enumerate(item):
#Code doing stuff
var1.filter(is_read=False)[i].is_read = True
var1.filter(is_read=False)[i].save(updated_fields=['is_read'])
I've tried the tips and answers from this post Mark email as read with exchangelib, but the emails still show as unread. What am I doing wrong?
I think you the last line of code that you save() do not work as you think that after you set is_read of unread[i] element to True, this unread[i] of course not appear in var1.filter(is_read=False)[i] again, so you acttually did not save this.
I think this will work.
for msg in my_account.inbox.filter(is_read=False):
msg.is_read = True
msg.save(updated_fields=['is_read'])
To expand on #thangnd's answer, the reason your code doesn't work is that you are calling .save() on a different Python object than the object you are setting the is_read flag on. Every time you call var1.filter(is_read=False)[i], a new query is sent to the server, and a new Python object is created.
Additionally, since you didn't specify a sort order (and new emails may be incoming while the code is running), you may not even be hitting the same email each time you call var1.filter(is_read=False)[i].

Fire Store's on_snapshot() function in Python executes twice. How to make it execute once?

This is my callback that executes when a user is added to a collection
# Create a callback on_snapshot function to capture changes
def on_snapshot_user(col_snapshot, changes, read_time):
print(u'Callback received query snapshot user.')
for change in changes:
if change.type.name == 'ADDED':
doc = change.document.to_dict()
email = doc["email"]
group = doc["survey_group"]
gender = doc["survey_gender"]
age = doc["survey_age"]
userInfo = User.query.filter_by(email=email).first()
if userInfo is None:
User.insert(User(email))
userInfo = User.query.filter_by(email=email).first()
userInfo.group = group
userInfo.gender = gender
userInfo.age = age
User.update(userInfo)
email is a primary key. When a user is added to Firestore, this triggers twice and it gives an error of a duplicate key.
How do I make this execute once in Python as metadata.PendingWrites is not yet supported in Python?
I am developing in Flask. I'm new to it so would appreciate any kind of help.
Edit:
Some context - I am adding the data I get to a PostgreSQL database. I am planning to do so as I need to build a kind of leaderboard and I'm planning to store the user info + their points in a postgreSQL table.
There are some steps to resolve multiple execution issue :
1. First would be to create a doc reference variable for the document you want to execute.
Create a doc_ref variable for the document you want to populate.
Syntax : doc_ref = db.Collection(collection_name)
2. Second step would be to watch the document.
doc_watch would be the variable created for watching the document.
Syntax : doc_watch = doc_ref.on_snapshot_functionName(on_snapshot_functionName)
3. Third step would be to Terminate watch on the document so it will be executed once.
You can use unsubscribe() to terminate the watch.
Syntax : doc_watch.unsubscribe()
For further details related to real time updates in Cloud Firestore, you can refer to the documentation [1].
[1] : https://cloud.google.com/firestore/docs/query-data/listen

Is it possible to get the ASC location from the Azure Python SDK?

I am fetching a subscription's Secure Score using the Microsoft Azure Security Center (ASC) Management Client Library. All operations in the library state that
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
Therefore, I am creating a SecurityCenter client with the following specification:
SecurityCenter(credentials, subscription_id, asc_location, base_url=None)
However, it seems to me like the only way to get the asc_location information properly is to use the SecurityCenter client to fetch it... The spec says the same as the quote above, You should not instantiate.... So I am stuck not being able to create the client because I need the ASC location to do so, and I need to create the client to get the ASC locations.
The documentation mentions
The location where ASC stores the data of the subscription. can be retrieved from Get locations
Googling and searching through the Python SDK docs for this "Get locations" gives me nothing (else than the REST API). Have I missed something? Are we supposed to hard-code the location like in this SO post or this GitHub issue from the SDK repository?
As offical API reference list locations indicates:
The location of the responsible ASC of the specific subscription (home
region). For each subscription there is only one responsible location.
It will not change, so you can hardcode this value if you already know the value of asc_location of your subscription.
But each subscription may have different asc_location values(my 2 Azure subscriptions have different asc_location value).
So if you have a lot of Azure subscriptions, you can just query asc_location by API (as far as I know, this is the only way I can find to do this)and then use SDK to get the Secure Score, try the code below:
from azure.mgmt.security import SecurityCenter
from azure.identity import ClientSecretCredential
import requests
from requests.api import head, request
TENANT_ID = ''
CLIENT = ''
KEY = ''
subscription_id= ''
getLocationsURL = "https://management.azure.com/subscriptions/"+subscription_id+"/providers/Microsoft.Security/locations?api-version=2015-06-01-preview"
credentials = ClientSecretCredential(
client_id = CLIENT,
client_secret = KEY,
tenant_id = TENANT_ID
)
#request for asc_location for a subscription
azure_access_token = credentials.get_token('https://management.azure.com/.default')
r = requests.get(getLocationsURL,headers={"Authorization":"Bearer " + azure_access_token.token}).json()
location = r['value'][0]['name']
print("location:" + location)
client = SecurityCenter(credentials, subscription_id, asc_location=location)
for score in client.secure_scores.list():
print(score)
Result:
I recently came across this problem.
Based on my observation, I can use whatever location under my subscription to initiate SecurityCenter client. Then later client.locations.list() gives me exactly one ASC location.
# Any of SubscriptionClient.subscriptions.list_locations will do
location = 'eastasia'
client = SecurityCenter(
credential, my_subscription_id,
asc_location=location
)
data = client.locations.list().next().as_dict()
pprint(f"Asc location: {data}")
In my case, the it's always westcentralus regardless my input was eastasia.
Note that you'll get exception if you use get instead of list
data = client.locations.get().as_dict()
pprint(f"Asc location: {data}")
# azure.core.exceptions.ResourceNotFoundError: (ResourceNotFound) Could not find location 'eastasia'
So what i did was a bit awkward,
create a SecurityCenter client using a location under my subscription
client.locations.list() to get ASC location
Use the retrieved ASC location to create SecurityCenter client again.
I ran into this recently too, and initially did something based on #stanley-gong's answer. But it felt a bit awkward, and I checked to see how the Azure CLI does it. I noticed that they hardcode a value for asc_location:
def _cf_security(cli_ctx, **_):
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.mgmt.security import SecurityCenter
return get_mgmt_service_client(cli_ctx, SecurityCenter, asc_location="centralus")
And the PR implementing that provides some more context:
we have a task to remove the asc_location from the initialization of the clients. currently we hide the asc_location usage from the user.
centralus is a just arbitrary value and is our most common region.
So... maybe the dance of double-initializing a client or pulling a subscription's home region isn't buying us anything?

python active_directive to set attributes

How do we set attributes using python active_directive. I have used following to set the mail property for the user, but its not working,
import active_directive
User = active_directory.AD_object ("LocalAdmin").find_user("User1")
print User.sAMAccountName
print User.displayName
print User.mail
User.setattr("mail","User1#testmail.com")
Here. I'm able to get the attributes(displayName, mail) of 'User1'. but not able set the mail attribute by using setattr()
Note : I have full permission to add, remove the user or group into the domain. I'm able to add and remove the group in the domain
We can set email id for the ADUser by using following line,
User.set(mail = "User1#testmail.com")

Modifying Microsoft Outlook contacts from Python

I have written a few Python tools in the past to extract data from my Outlook contacts. Now, I am trying to modify my Outlook Contacts. I am finding that my changes are being noted by Outlook, but they aren't sticking. I seem to be updating some cache, but not the real record.
The code is straightforward.
import win32com.client
import pywintypes
o = win32com.client.Dispatch("Outlook.Application")
ns = o.GetNamespace("MAPI")
profile = ns.Folders.Item("My Profile Name")
contacts = profile.Folders.Item("Contacts")
contact = contacts.Items[43] # Grab a random contact, for this example.
print "About to overwrite ",contact.FirstName, contact.LastName
contact.categories = 'Supplier' # Override the categories
# Edit: I don't always do these last steps.
ns = None
o = None
At this point, I change over to Outlook, which is opened to the Detailed Address Cards view.
I look at the contact summary (without opening it) and the category is unchanged (not refreshed?).
I open the contact and its category HAS changed, sometimes. (Not sure of when, but it feels like it is cache related.) If it has changed, it prompts me to Save Changes when I close it which is odd, because I haven't changed anything in the Outlook UI.
If I quit and restart Outlook, the changes are gone.
I suspect I am failing to call SaveChanges, but I can't see which object supports it.
So my question is:
Should I be calling SaveChanges? If so, where is it?
Am I making some other silly mistake, which is causing my data to be discarded?
I believe there is a .Save() method on the contact, so you need to add:
contact.Save()

Categories

Resources