Skip to main content

A Python client wrapping the Salesforce.com SOAP API

Project description

Pypi Version Pypi Downloads

Introduction

This is a reluctant fork of the beatbox project originally authored by Simon Fell, (their version locked at 0.92) later drastically changed by these folks https://code.google.com/p/salesforce-beatbox/ (versioned at 20.0).

Renamed to pyforce to avoid confusion related to the fractured community version. (https://github.com/superfell/Beatbox/issues/6) Long story short, the python client in the fork at version 20.0 is exceptionally useful, so going back to 0.92 would be a mistake, however the beatbox version at 20.0 is also no longer maintained (judging by the issues). pyforce builds off the version available there, integrating bug fixes, and new features.

This module contains 2 versions of the Salesforce.com client:

XMLClient An xmltramp wrapper that handles the xml fun. PythonClient Marshalls the returned objects into proper Python data types. e.g. integer fields return integers.

Compatibility

pyforce supports versions 16.0 through 20.0 of the Salesforce Partner Web Services API. However, the following API calls have not been implemented at this time:

  • emptyRecycleBin
  • invalidateSessions
  • merge
  • process
  • queryAll
  • undelete
  • describeSObject
  • describeDataCategoryGroups
  • describeDataCategoryGroupStructures

pyforce supports python 2.x for values of x >=7 as well as Python 3.x.

Basic Usage Examples

Instantiate a Python Salesforce.com client: >>> svc = pyforce.PythonClient() >>> svc.login('username', 'passwordTOKEN')

(Note that interacting with Salesforce.com via the API requires the use of a 'security token' which must be appended to the password. See sfdc docs for details)

The pyforce client allows you to query with sfdc SOQL.

Here's an example of a query for contacts with last name 'Doe':

res = svc.query("SELECT Id, FirstName, LastName FROM Contact WHERE LastName='Doe'")
res[0]
{'LastName': 'Doe', 'type': 'Contact', 'Id': '0037000000eRf6vAAC', 'FirstName': 'John'}
res[0].Id
'0037000000eRf6vAAC'

Add a new Lead:

contact = {
        'type': 'Lead',
        'LastName': 'Ian',
        'FirstName': 'Bentley',
        'Company': '10gen'
    }
res = svc.create(contact)
if not res[0]['errors']:
    contact_id = res[0]['id']
else:
    raise Exception('Contact creation failed {0}'.format(res[0]['errors']))

Batches work automatically (though sfdc limits the number to 200 maximum):

contacts = [
    {
        'type': 'Lead',
        'LastName': 'Glick',
        'FirstName': 'David',
        'Company': 'Individual'
    },
    {
        'type': 'Lead',
        'LastName': 'Ian',
        'FirstName': 'Bentley',
        'Company': '10gen'
    }
]
res = svc.create(contacts)

Send a new email, optionally using templates, including attachments and creating activities for associated objects:

simple_email = {
    'subject': 'Test of Salesforce sendEmail()',
    'plainTextBody': 'This is a simple test message.',
    'toAddresses': 'johndoe@example.com,
}
res = svc.sendEmail( [simple_email] )
res
[{'errors': [], 'success': True}]

complex_email = {
    'templateId': '00X80000002h4TV',    # Id of an EmailTemplate used for Subject and Body, supports field merge from whatId.
    'targetObjectId':'003808980000GJ',  # Id of a Contact, Lead or User which the email will be sent to.
    'whatId':'500800000RuJo',           # Id of a SObject to create an Activity in.
    'saveAsActivity': True,
    'useSignature': True,
    'inReplyTo': '<1234567890123456789%example@example.com>',  # RFC2822, a previous email thread.
    'references': '<1234567890123456789%example@example.com>',
    'fileAttachments': [{
        'body': base64_encoded_png,
        'contentType':'image/png',
        'fileName':'salesforce_logo.png',
        'inline':True
    }]
}
res = svc.sendEmail( [complex_email] )
res
[{'errors': [], 'success': True}]

More Examples

The examples folder contains the examples for the xml client. For examples on how to use the python client see the tests directory.

Some of these other products that were built on top of beatbox can also provide example of pyforce use, though this project may diverge from the beatbox api.

Alternatives

David Lanstein has created a Python Salesforce Toolkit that is based on the suds SOAP library. That project has not seen any commit since June 2011, so it is assumed to be abandoned.

.. Python Salesforce Toolkit: http://code.google.com/p/salesforce-python-toolkit/

Running Tests

At the fork time, all tests are integration tests that require access to a Salesforce environment. It is my intent to change these tests to be stub based unit tests.

From the beatbox documentation:

First, we need to add some custom fields to the Contacts object in your Salesforce instance:

*Login to your Salesforce.com instance

  • Browse to Setup --> Customize --> Contacts --> Fields --> "New" button
  • Add a Picklist (multi-select) labeled "Favorite Fruit", then add
    • Apple
    • Orange
    • Pear
  • Leave default of 3 lines and field name should default to "Favorite_Fruit"
  • Add a Number labeled "Favorite Integer", with 18 places, 0 decimal places
  • Add a Number labeled "Favorite Float", with 13 places, 5 decimal places

Export environment variables with your Salesforce credentials:

SF_USERNAME, SF_PASSWORD, SF_SECTOKEN

Run the tests::

make test

Changelog

1.9.1 (2020-04-13) Fix xmlbomb vuln again #43

1.9.0 (2020-03-13) Add Python 3 support #42

1.8.0 (2017-11-21) Fix external entities vulnerability #35

1.7.3 (2016-08-22) Bugfix: initialize value of reduce in getRecordTypes

1.7.2 (2015-12-21) Upgraded xmltramp to 2.18 with some inline patching. Experimenting with Travis-CI integration.

1.7.1 (2015-12-14) Corrected regression bug in xmltramp when updating to new style classes. Fixes issue 26.

1.7 (2015-12-08) Address type marshalling to Dict. PEP8 cleanup. New-style exception classes.

1.6 (2015-04-27) Introduce logout functionality. New maintainer.

1.5 (2014-10-30) Introduce sendEmail functionality.

1.4 (2014-08-14) Introduce convertLead functionality.

1.3 (2013-11-7) Bugfix introduced in 1.2

1.2 (2013-10-25)

  • Two bugfixes for supporting Python 2.7
  • Fix some dos encoding issues Thanks to: @lociii and @gabber7

1.01 (2013-04-10)

  • Fix MANIFEST.in for releasing to pypi

1.0 (2013-04-01)

  • Rename beatbox to pyforce
  • Support embedded dictionaries in python objects submitted to the python client
  • Rename writeStringElement method to writeElement for more accuracy in name

Beatbox forked as Pyforce

20.0 (2010-11-30)

  • Add 'encryptedstring' to the list of types marshalled as strings. Thanks sobyone. [davisagli]

  • Update to use version 20.0 of the Salesforce.com partner WSDL by default. [davisagli]

19.0 (2010-08-23)

  • Update marshalling of describeGlobal and describeSObjects responses to include new properties now returned by the API. For backwards compatibility, we set the types property of the describeGlobal response to a list of the names of all types (which Salesforce now returns in separate DescribeGlobalSObjectResult objects). [davisagli]

  • Update to use version 19.0 of the Salesforce.com partner WSDL by default. Also, use the new login.salesforce.com login endpoint by default. [davisagli]

16.1 (2010-03-11)

  • Catch and retry on exceptions from the socket library, in addition to ones from httplib. This fixes a regression introduced in version 16.0. [davisagli]

16.0 (2009-11-12)

  • Don't strip newlines when marshalling the values of textarea fields. [davisagli]

  • Make sure to add a field to fieldsToNull if its Python value is None. [rhettg, davisagli]

  • Fix issue where numbers of type long weren't converted to a string. [spleeman, davisagli]

  • Only catch HTTP exceptions when retrying a connection. [spleeman, davisagli]

16.0b1 (2009-09-08)

  • Log beatbox calls at the debug level. [davisagli]

  • Fixed a string exception for compatibility with Python 2.6. [davisagli]

  • Added support for SOSL searches via the search method. Thanks to Alex Tokar of Web Collective. [davisagli]

  • Added an optional cache for the sObject type descriptions needed for marshalling query results into Python objects. This can avoid an extra describeSObjects API call for each query, but means that the information could become stale if the type metadata is modified in Salesforce.com. The cache is off by default. Turn it on by passing cacheTypeDescriptions=True when instantiating a Python client. The cache may be reset by calling the flushTypeDescriptionsCache method of the Python client. [davisagli]

  • Support a full SOQL statement as a parameter to the query method of the Python client. The old 3-part method signature (fields, sObjectType, conditionalExpression) should continue to work. [davisagli]

  • In the Python client, support relationship queries and other queries that may return multiple types of objects. Object type descriptions (required for marshalling field values into the correct Python type) are cached for the duration of the query after the first time they are used. Thanks to Melnychuk Taras of Quintagroup. [davisagli]

  • In the Python client, queries now return a list-like QueryRecordSet holding a sequence of dict-like QueryRecord objects, instead of a dict containing a list of dicts. This allows for more Pythonic access such as results[0].Id instead of results['results'][0]['Id']. The old syntax should still work. Thanks to Melnychuk Taras of Quintagroup. [davisagli]

  • Update to use version 16.0 of the Salesforce.com partner WSDL. [davisagli]

0.12 (2009-05-13)

  • Use the default serverUrl value if the passed value evaluates to boolean False. [davisagli]

0.11 (2009-05-13)

10.1 (unreleased)

0.10 (2009-05-06)

  • Added optional serverUrl parameter when creating a Client. [davisagli]

pre 0.9.1.1

  • ancient history

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for pyforce, version 1.9.1
Filename, size File type Python version Upload date Hashes
Filename, size pyforce-1.9.1-py3-none-any.whl (28.9 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size pyforce-1.9.1.tar.gz (37.9 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page