Trying to change a username in Python Google Admin SDK - python

I'm trying to change a username using the Admin SDK. I'm trying the following code to update this, using a dict object to store the new info, and using patch to update:
userinfo['primaryEmail'] = D['new_user'] + '#' + D['domain']
appsservice.users().patch(userKey = userEmail, body=userinfo)
It doesn't seem to be working, when I look at the admin console. The original username remains unchanged. I'm just wondering if I'm using the correct method. Should I be updating a different variable than primaryEmail or without using the domain affiliation? Seems like I'm just missing something rather obvious.
Thanks,
Tom

Add:
.execute()
To the end of the 2nd line to actually execute the api operation.

Related

Getting SalesforceMalformedRequest: Malformed request error

I am trying to execute this following code to push data to Salesforce using the simple_salesforce python library :
from simple_salesforce import Salesforce
staging_df = hive.execute("select * from hdmni")
staging_df = staging_df.toPandas()
# # staging_df['birth_date']= staging_df['birth_date'].dt.date
staging_df['birth_date'] = staging_df['birth_date'].astype(str)
staging_df['encounter_start_date'] = staging_df['encounter_start_date'].astype(str)
staging_df['encounter_end_date'] = staging_df['encounter_end_date'].astype(str)
bulk_data = []
for row in staging_df.itertuples():
d= row._asdict()
del d['Index']
bulk_data.append(d)
sf = Salesforce(password='', username='', security_token='')
sf.bulk.Delivery_Detail__c.insert(bulk_data)
I am getting this error while trying to send dictionary to salesforce :
SalesforceMalformedRequest: Malformed request
https://subhotutorial-dev-ed.my.salesforce.com/services/async/38.0/job/7500o00000HtWP6AAN/batch/7510o00000Q15TnAAJ/result.
Response content: {'exceptionCode': 'InvalidBatch',
'exceptionMessage': 'Records not processed'}
There's something about your query that is not correct. While I don't know your use case, by reading this line, you can tell that you are attempting to insert into a custom object/entity in Salesforce:
sf.bulk.Delivery_Detail__c.insert(bulk_data)
The reason you can tell is because of the __c suffix, which gets appended onto custom objects and fields (that's two underscores, by the way).
Since you're inserting into a custom object, your fields would have to be custom, too. And note, you've not appended that suffix onto them.
Note: Every custom object/entity in Salesforce does come with a few standard fields to support system features like record key (Id), record name (Name), audit fields (CreatedById, CreatedDate, etc.). These wouldn't have a suffix. But none of the fields you reference are any of these standard system fields...so the __c suffix would be expected.
I suspect that what Salesforce is expecting in your insert operation are field names like this:
Birth_Date__c
Encounter_Start_Date__c
Encounter_End_Date__c
These are referred to as the API name for both objects and fields, and anytime code interacts with them (whether via integration, or on code that executes directly on the Salesforce platform) you need to make certain you're using this API name.
Incidentally, you can retrieve this API name through a number of ways. Probably easiest is to log into your Salesforce org, and in Setup > Object Manager > [some object] > Fields and Relationships you can view details of each field, including the API name. Here's a screen shot.
You can also use SObject describe APIs, either in native Apex code, or via integration and either the REST or SOAP APIs. Here's part of the response from the describe API request to the describe REST endpoint for the same object as my UI example above, found here at https://[domain]/services/data/v47.0/sobjects/Expense__c/describe:
Looking at the docs for the simple-salesforce python library you're using, they've surfaced the describe API. You can find some info under Other Options. You would invoke it as sf.SObject.describe where "SObject" is the actual object you want to find the information about. For instance, in your case you would use:
sf.Delivery_Detail__c.describe()
As a good first troubleshooting step when interacting with a Salesforce object, I'd always recommend double-checking correctly referencing an API name. I can't tell you how many times I've bumped into little things like adding or missing an underscore. Especially with the __c suffix.

Understanding Todoist-API

I am trying to use the Todoist-API for Python. I found the official docs on the internet and downloaded the GitHub-Repo. Unfortunately I don't get out how to add a new task.
I do the normal login:
api = todoist.TodoistAPI(XYZ)
api.sync
Then I try to add a new task:
item = api.items.add('Task1')
It tells me I have to give two arguments: name and project_id:
item = api.items.add('Task1', 128501470)
Does anyone know where I could get all my projects IDs? I just want to use the Inbox-Project (default).
I'm not very familiar with this specific API, but considering you're using this api: https://github.com/doist/todoist-python, you can probably do something like:
response = api.sync()
projects = response['projects']
for project in projects:
print(project['name'] + '-' + project['id'])
Basically printing all the names and id's
Just open Todoist in a web browser and look at the address bar, it's right after "project", I beleive you need to truncate the first three or 4 characters though, click through a few projects and you'll see the project id's change.
To add them to the inbox the easiest way is to do the following:
from todoist.api import TodoistAPI
apiToken = 'your token"
todoist: TodoistAPI = TodoistAPI(api_token)
response = todoist.add_item("Item1")
todoist.sync()
todoist.commit()
You will have to refresh either the web page or your app to immediately see the new item

Unable to access jira worklogs via python-jira

I am trying to access the worklogs in python by using the jira python library. I am doing the following:
issues = jira.search_issues("key=MYTICKET-1")
print(issues[0].fields.worklogs)
issue = jira.search_issues("MYTICKET-1")
print(issue.fields.worklogs)
as described in the documentation, chapter 2.1.4. However, I get the following error (for both cases):
AttributeError: type object 'PropertyHolder' has no attribute 'worklogs'
Is there something I am doing wrong? Is the documentation outdated? How to access worklogs (or other fields, like comments etc)? And what is a PropertyHolder? How to access it (its not described in the documentation!)?
This is because it seems jira.JIRA.search_issues doesn't fetch all "builtin" fields, like worklog, by default (although documentation only uses vague term "fields - [...] Default is to include all fields"
- "all" out of what?).
You either have to use jira.JIRA.issue:
client = jira.JIRA(...)
issue = client.issue("MYTICKET-1")
or explicitly list fields which you want to fetch in jira.JIRA.search_issues:
client = jira.JIRA(...)
issue = client.search_issues("key=MYTICKET-1", fields=[..., 'worklog'])[0]
Also be aware that this way you will get at most 20 worklog items attached to your JIRA issue instance. If you need all of them you should use jira.JIRA.worklogs:
client = jira.JIRA(...)
issue = client.issue("MYTICKET-1")
worklog = issue.fields.worklog
all_worklogs = client.worklogs(issue) if worklog.total > 20 else worklog.worklogs
This question here is similar to yours and someone has posted a work around.
There is a also a similar question on Github in relation to attachments (not worklogs). The last answer in the comments has workaround that might assist.

How to access cookie and IP fields in DjangoRatings?

I'm using the djangoratings library found here and I have everything running and set up. In my views.py file I have a button which executes this line of code when pushed:
myinstance.rating.add(score=1, user=request.user, ip_address=request.META['REMOTE_ADDR'], request.COOKIES)
Everything works fine. The backend works, my columns are updated with the votes etc etc, but how can I access/call the IP and cookie fields and columns in djangoratings so that I can write a quick if condition that refuses to run the 'add' line if the cookies and IP have already voted?
Thanks in advance for any help. I've been really struggling with this a lot.
myinstance.rating contains method get_ratings() - which returns queryset to calculate all votes related to object. You can easily extend it for retrive necessary information. For example:
# it's lazy object
rating = myinstance.rating.get_ratings()
# do additional query for db
if not rating.filter(user=user, ip_address=request.META['REMOTE_ADDR']).exists():
...

Using Python Web GET data

I'm trying to pass information to a python page via the url. I have the following link text:
"<a href='complete?id=%s'>" % (str(r[0]))
on the complete page, I have this:
import cgi
def complete():
form = cgi.FieldStorage()
db = MySQLdb.connect(user="", passwd="", db="todo")
c = db.cursor()
c.execute("delete from tasks where id =" + str(form["id"]))
return "<html><center>Task completed! Click <a href='/chris'>here</a> to go back!</center></html>"
The problem is that when i go to the complete page, i get a key error on "id". Does anyone know how to fix this?
EDIT
when i run cgi.test() it gives me nothing
I think something is wrong with the way i'm using the url because its not getting passed through.
its basically localhost/chris/complete?id=1
/chris/ is a folder and complete is a function within index.py
Am i formatting the url the wrong way?
The error means that form["id"] failed to find the key "id" in cgi.FieldStorage().
To test what keys are in the called URL, use cgi.test():
cgi.test()
Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.
EDIT: a basic test script (using the python cgi module with Linux path) is only 3 lines. Make sure you know how to run it on your system, then call it from a browser to check arguments are seen on the CGI side. You may also want to add traceback formatting with import cgitb; cgitb.enable().
#!/usr/bin/python
import cgi
cgi.test()
Have you tried printing out the value of form to make sure you're getting what you think you're getting? You do have a little problem with your code though... you should be doing form["id"].value to get the value of the item from FieldStorage. Another alternative is to just do it yourself, like so:
import os
import cgi
query_string = os.environ.get("QUERY_STRING", "")
form = cgi.parse_qs(query_string)
This should result in something like this:
{'id': ['123']}
First off, you should make dictionary lookups via
possibly_none = my_dict.get( "key_name" )
Because this assigns None to the variable, if the key is not in the dict. You can then use the
if key is not None:
do_stuff
idiom (yes, I'm a fan of null checks and defensive programming in general...). The python documentation suggests something along these lines as well.
Without digging into the code too much, I think you should reference
form.get( 'id' ).value
in order to extract the data you seem to be asking for.

Categories