Insert or update to a salesforce by python - python

I want to insert or update to a salesforce record.
by python but I get the following error.
The item of "SeqNo__c" is "202102-123" from that I specify the id of the record I want to change.
it seems that it cannot find it at SeqNo__c.
If anyone knows, please let me know.
This code
from simple_salesforce import Salesforce
from datetime import datetime
import os
import json
import gzip
from pytz import timezone
import requests
#strDate = datetime.now().strftime("%Y%m%d")
#strTime = datetime.now().strftime("%H%M%S")
SALESFORCE_USERNAME = '123#gmail.com'
PASSWORD = '12345'
SECURITY_TOKEN = '12345'
# Authentication settings
sf = Salesforce(username=SALESFORCE_USERNAME,
password=PASSWORD,
security_token=SECURITY_TOKEN)
#Try bulk but also error
#data = [{'SeqNo__c': '202102-123', 'NewNO__c': '1'}]
#sf.bulk.Contact.update(data)
sf.Contact.upsert('SeqNo__c/202102-123',{'NewNO__c': '1'})
error code
Traceback (most recent call last):
File "c:\Users\test\Documents\salesforce\sf_check.py", line 27, in <module>
sf.Contact.upsert('SeqNo__c/202102-123',{'NewNO__c': '1'})
File "C:\Users\test\AppData\Local\Programs\Python\Python39\lib\site-packages\simple_salesforce\api.py", line 694, in upsert
result = self._call_salesforce(
File "C:\Users\test\AppData\Local\Programs\Python\Python39\lib\site-packages\simple_salesforce\api.py", line 800, in _call_salesforce
exception_handler(result, self.name)
File "C:\Users\test\AppData\Local\Programs\Python\Python39\lib\site-packages\simple_salesforce\util.py", line 68, in exception_handler
raise exc_cls(result.url, result.status_code, name, response_content)
simple_salesforce.exceptions.SalesforceResourceNotFound: Resource Contact Not Found. Response content: [{'errorCode': 'NOT_FOUND', 'message': 'Provided external ID field does not exist or is not accessible: SeqNo__c'}]
PS C:\Users\test\Documents\salesforce>

Is the Contact.SeqNo__c field marked as external id? There's a checkbox in field definition that must be ticked. And your user needs to have a profile permission to at least see the field

Related

Query Influx database

I have this code to query a influx DB, but it is not working at all. Here is the python code.
import os
from influxdb import InfluxDBClient
username = u'{}'.format(os.environ['INFLUXDB_USERNAME'])
password = u'{}'.format(os.environ['INFLUXDB_PASSWORD'])
client = InfluxDBClient(host='127.0.0.1', port=8086, database='data',
username=username, password=password)
result = client.query("SELECT P_askbid_midprice1 FROM 'DCIX_OB' WHERE time > '2018-01-01';")
I got the following error, but it's still unclear how to fix the code above. If I query directly from influxdb with bash with SELECT P_askbid_midprice1 FROM 'DCIX_OB' WHERE time > '2018-01-01'; it worked perfectly fine.
Press ENTER or type command to continue
Traceback (most recent call last):
File "graph_influxdb.py", line 11, in <module>
result = client.query("SELECT P_askbid_midprice1 FROM 'DCIX_OB' WHERE time > '2018-01-01';")
File "/home/ubuntu/.local/lib/python3.5/site-packages/influxdb/client.py", line 394, in query
expected_response_code=expected_response_code
File "/home/ubuntu/.local/lib/python3.5/site-packages/influxdb/client.py", line 271, in request
raise InfluxDBClientError(response.content, response.status_code)
influxdb.exceptions.InfluxDBClientError: 400: {"error":"error parsing query: found DCIX_OB, expected identifier at line 1, char 31"}
How can I fix it?
result = client.query("SELECT P_askbid_midprice1 FROM DCIX_OB WHERE time > '2018-01-01'")
this should work
you might be able to use Pinform which is some kind of ORM/OSTM (Object time series mapping) for InfluxDB.
It can help with designing the schema and building normal or aggregation queries.
cli.get_fields_as_series(OHLC,
field_aggregations={'close': [AggregationMode.MEAN]},
tags={'symbol': 'AAPL'},
time_range=(start_datetime, end_datetime),
group_by_time_interval='10d')
Disclaimer: I am the author of this library

Getting chef.exceptions.ChefServerError: Method Not Allowed while creating Role in chef

I am trying to create a role using PyChef api. I am able to retrieve list of nodes or roles (GET method) successfully but when i m trying to create a role (POST method) i am getting an runtime excetion, i.e, method not allowed.
Here is my code :
import json
import requests
import re
import chef
from chef.exceptions import ChefError, ChefServerNotFoundError
from chef.base import ChefQuery, ChefObject
from chef import Role
pem_file = "path-to-validator.pem/chef-validator.pem"
client_name = "validator"
node_name = "root"
role_url = "ChefServer-URL/roles/"
rolelist =[]
chef_api = chef.ChefAPI(role_url,pem_file,client_name,ssl_verify=False)
create_role = chef.Role.create(name='myrole', api=chef_api ,description='A test role', run_list=['recipe[foo]'],default_attributes={'attr': 'foo'}, override_attributes={'attr': 'bar'})
rolelst = chef.Role.list()
for j in rolelst:
rolelist.append(j)
print rolelist
And here is the error that i am facing:
Traceback (most recent call last):
File "roleapi.py", line 37, in <module>
create_role = chef.Role.create(name='myrole', api=chef_api ,description='A
test role', run_list=['recipe[foo]'],default_attributes={'attr': 'foo'},
override_attributes={'attr': 'bar'})
File "/usr/lib/python2.6/site-packages/chef/base.py", line 99, in create
api.api_request('POST', cls.url, data=obj)
File "/usr/lib/python2.6/site-packages/chef/api.py", line 217, in
api_request
response = self.request(method, path, headers, data)
File "/usr/lib/python2.6/site-packages/chef/api.py", line 207, in request
raise ChefServerError.from_error(response.reason, code=response.status_code)
chef.exceptions.ChefServerError: Method Not Allowed
So please suggest me something how can i resolve this error. Thank you in advance.
The URL should be the base of the Chef Server, probably something like https://myserver.com/organizations/foo.

Can't find SalesForce Object

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")

Tweepy follow Twitter users from text file using user_id (Python script)

I am trying to follow user_ids from a text file with 27 user_ids - one per line, e.g. :
217275660
234874181
27213931
230766319
83695362
234154065
68385750
I have some code that seems to work except it says user_id isn't defined (see pasted error at the bottom)... but user_id should be the correct variable in Tweepy... with or without [,follow] afterwards. My code is as follows:
# Script to follow Twitter users from text file containing user IDs (one per line)
# Header stuff I've just thrown in from another script to authenticate
import json
import time
import tweepy
import pprint
from tweepy.parsers import RawParser
from auth import TwitterAuth
from datetime import datetime
auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret)
auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret)
rawParser = RawParser()
api = tweepy.API(auth_handler = auth, parser = rawParser)
# Open to_follow.txt
to_follow = [line.strip() for line in open('to_follow.txt')]
print to_follow
# Follow everyone from list?!
for user_id in to_follow:
try:
api.create_friendship(user_id)
except tweepy.TweepError as e:
print e
continue
print "Done."
The error is:
$ python follow.py
['217275660', '234874181', '27213931', '230766319', '83695362', '234154065', '68385750', '94981006', '215003131', '30921943', '234526708', '229259895', '88973663', '108144701', '233419650', '70622223', '95445695', '21756719', '229243314', '18162009', '224705840', '49731754', '19352387', '80815034', '17493612', '23825654', '102493081']
Traceback (most recent call last):
File "follow.py", line 30, in <module>
api.create_friendship(user_id)
NameError: name 'user_id' is not defined
Indeed user_id isn't defined anywhere in your code.
I think you meant to do:
for user_id in to_follow:
The user_id's are in the list
And on a side note - the following code is better and more orthodox:
with open('to_follow.txt') as f:
for line in f:
user_id = line.strip()
api.create_friendship(user_id)

Updating a Spreadsheet in Google Docs

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()

Categories

Resources