The Reports and Dashboards Rest API gives you lot programmatic access to your report and dashboard data as defined in the study architect and dashboard architect. The API lets you integrate the data into any web or mobile application, inside or outside the Salesforce platform.

You can use this data in various ways like below:
• Integrate written report data into custom objects.
• Define rich visualizations on top of the API to breathing the information.
• Build custom dashboards.
• Automate reporting tasks.
At a loftier level, the API resources let you query and filter report data. Yous can:
• Run tabular, summary, or matrix reports synchronously or asynchronously.
• Filter for specific data on the fly.
• Query report metadata.
You tin too work with dashboard resources to:
• Go a list of recently used dashboards.
• Get dashboard metadata and data.
• Query dashboard status.
• Refresh dashboards.

Requirements and Limitations:

The Reports and Dashboards REST API is available for any organization that has API enabled. You must establish an authenticated session using OAuth in gild to admission the Reports and Dashboards REST API. When working with this API, consider these restrictions in add-on to general API limits.
Note: Responses and requests are in JSON. While using the Reports and Dashboards REST API with a Postal service request trunk, yous must use content-type: application/json. You might get unexpected results if you don't use this content type.

Reports Limits:
• Cross filters, standard written report filters, and filtering past row limit are unavailable when filtering information.
• Historical trend reports are only supported for matrix reports.
• The API can procedure only reports that contain up to 100 fields selected as columns.
• A list of up to 200 recently viewed reports tin be returned.
• Your org tin can request upwardly to 500 synchronous report runs per hour.
• The API supports up to xx synchronous report run requests at a time.
• A list of up to 2,000 instances of a written report that was run asynchronously tin can be returned.
• The API supports up to 200 requests at a time to get results of asynchronous report runs.
• Your system can asking up to 1,200 asynchronous requests per hr.
• Asynchronous report run results are available within a 24-hour rolling period.
• The API returns up to the kickoff 2,000 report rows. Y'all tin can narrow results using filters.
• You can add together up to 20 custom field filters when you run a written report.
Dashboards Limits:
• Your org can asking upwardly to 200 dashboard refreshes per hour.
• Your org tin request results for up to v,000 dashboards per hr.
Analytics Notification Limits
• Each user can subscribe to upwardly to 5 reports.
• Each user can create up to 5 Wave notifications.
Note: All limits that apply to reports created in the report builder also apply to the API, as do limits for dashboards created in the dashboard builder. For more information, meet "Salesforce Reports and Dashboards Limits" in the Salesforce online help.

Python Script to access salesforce data directly from Study:

#Connect to the Salesforce Analytics API and asking information from a report import salesforce_reporting import pandas as pd from salesforce_reporting import Connection, ReportParser   # setup your login details sf = Connection(username='user_name', password='Password', security_token='Security_token') #Use the Connexion.get_report() method to request report data and and so use ReportParser to admission all the records #included in a study (in listing format if you use the ReportParser.records() method):  report = sf.get_report('report_id') parser = salesforce_reporting.ReportParser(study)  parser.records() df = pd.DataFrame(study) print(df)

oauth2.0.PNG

Before connecting force.com token to python, starting time you first need to create aConnected App in Saleforce.

A continued app is an application that integrates with salesforce.com using APIs and uses either SAML and OAuth protocols to cosign, provide Single Sign-On, and provide tokens for use with Salesforce APIs. In improver to standard OAuth capabilities, connected apps allow administrators to set various security policies and have explicit control over who may use the applications.

  1. Login to your Salesforce organization: https://login.salesforce.com/
  2. Create aConnected App by clickingCreate,App, thenNew in theConnected Apps department.
  3. Enter all the pertinent data and enableAPI (Enable OAuth Settings) withFull admission (full). You tin likely alter the access level to suit your needs, simply full admission will at least work.
  4. Once created, grab yourConsumer Fundamental andConsumer Secret. You'll need them in a moment.

Using this information, you can now execute the following code.

Executing beneath Pyton code returns the following JSON output:

                                      {{"access_token":"00Do0000000eP6y!AQMAQL.rIQEGcuWysvvVSGrA_IeOO7TOtZmWwqhg29sLuAUA8HPQwG8iWwIkZ7xfIqrAFCjfgkNUlcIUY.1n19OrvnPqSF4P","instance_url":"https://sgpgroups-dev-ed.my.salesforce.com","id":"https://login.salesforce.com/id/00Do0000000eP6yEAE/005o0000001jmaWAAQ","token_type":"Bearer","issued_at":"1512879770892","signature":"tdTAwz7Fv/2msLFzz4oYB4WjuwNCcpZUHL9XMFzQthM="}                    }                                  

Exactly what we'd expect. Or so we think.

Turns out, the fact that this lawmaking executes at all is because we've logged into Salesforce from our machine and we have inadvertantly completed one of two steps required for identify verification. Through the APIs it'south non plenty to only provide the username and password. Nosotros demand to do more.

To test this (if you're up for information technology), try to execute this from a different machine with a unlike IP address – for example, AWS. You volition go the post-obit mistake:

                  authentication failure - Failed: API security token required                                  

While you may find this annoying it'south purposeful and of import. The reality is that sometimes a username and password isn't enough. We need more protection. This error is in effect telling you that you're not calling from a trusted IP accost.

There are three ways to fix it. The easy way, the somewhat more challenging manner, and then the correct manner.

Let's take a look at the three ways. But don't use the first 2. Seriously.

  1. Set appropriate login ranges for the user profile.Administration Setup,Manage Users,Users. Find your login name and and so click the link underProfile. In my case, this isSystem Ambassador. ClickLogin IP Rangesthen the*New push. For giggles, add the range 0.0.0.0 to 255.255.255.255 as this will enable access from everywhere.

    Hopefully yous come across why this is non a proficient long term solution.

  2. Set appropriate login ranges for the connected app.App Setup,Create,Apps. Click the connected app you created. ClickNew next toIP Ranges. Different the IP ranges for the user profile you cannot gear up a ridiculously big range; your have to be more specific and physical. Figure out the IP range for your host and enter it here.

    This is too not a practiced solution although information technology'due south better than the previous. Fight the urge to do this and let's look at the correct pick.

  3. Go a security token. This is the right thing to do and is chosen the Username-Password OAuth Authentication Flow. Turns out, information technology's not difficult to do this.Personal Setup,My Personal Information,Reset My Security Token. This volition send a new security token to you via email.

    You must suspend the security token to their password. For instance, if a user'southward password is "mypassword" and the security token is "XXXXXXXXXX", then the value provided for this parmeter must be "mypasswordXXXXXXXXXX".

    Equally you can come across, this is not at all difficult.

So, knowing this and proceeding with option #3, we can make a minor change to our Python code.

Python Script:

import requests  consumer_key = "YOUR_CONSUMER_KEY" consumer_secret = "YOUR_CUSTOMER_SECRET" username = "YOUR_USER_NAME" countersign = "YOUR_PASSWORD" organizationId = "YOUR-ORGANIZATIONID"   payload = {     'grant_type': 'countersign',     'client_id': consumer_key,     'client_secret': consumer_secret,     'username': username,     'password': countersign,     'organizationId': organizationId }   r = requests.post("https://login.salesforce.com/services/oauth2/token",      headers={"Content-Type":"application/ten-world wide web-grade-urlencoded"},     data=payload)   impress r.content

sf andpyhon

Salesforce Bulk

Python client library for accessing the asynchronous Salesforce.com Majority API.

Installation

pip install salesforce-bulk

Authentication

To access the Bulk API you need to authenticate a user into Salesforce. The easiest fashion to do this is just to supplyusername,countersign andsecurity_token. This library volition use thesimple-salesforce parcel to handle countersign based authentication.

from salesforce_bulk import SalesforceBulk  majority = SalesforceBulk(username=username, countersign=password, security_token=security_token) ...              

Alternatively if yous run have access to a session ID and instance_url yous can use those directly:

from urlparse import urlparse from salesforce_bulk import SalesforceBulk  majority = SalesforceBulk(sessionId=sessionId, host=urlparse(instance_url).hostname) ...              

Operations

The basic sequence for driving the Bulk API is:

  1. Create a new task
  2. Add one or more than batches to the chore
  3. Shut the task
  4. Look for each batch to terminate

Bulk Query

bulk.create_query_job(object_name, contentType='JSON')

Using API v39.0 or higher, you tin as well employ the queryAll operation:

bulk.create_queryall_job(object_name, contentType='JSON')

Case

from salesforce_bulk.util import IteratorBytesIO import json task = bulk.create_query_job("Contact", contentType='JSON') batch = majority.query(job, "select Id,LastName from Contact") majority.close_job(job) while not majority.is_batch_done(batch):     sleep(x)  for result in majority.get_all_results_for_query_batch(batch):     result = json.load(IteratorBytesIO(result))     for row in result:         print row # lexicon rows              

Same case but for CSV:

import unicodecsv chore = bulk.create_query_job("Contact", contentType='CSV') batch = bulk.query(chore, "select Id,LastName from Contact") bulk.close_job(job) while not bulk.is_batch_done(batch):     sleep(ten)  for result in bulk.get_all_results_for_query_batch(batch):     reader = unicodecsv.DictReader(result, encoding='utf-eight')     for row in reader:         print row # lexicon rows              

Note that while CSV is the default for historical reasons, JSON should exist prefered since CSV has some drawbacks including its handling of Nothing vs empty string.

PK Clamper Header

If y'all are querying a big number of records yous probably want to plough on PK Chunking:

bulk.create_query_job(object_name, contentType='CSV', pk_chunking=Truthful)

That will employ the default setting for chunk size. You can utilize a different clamper size by providing a number of records per chunk:

bulk.create_query_job(object_name, contentType='CSV', pk_chunking=100000)

Additionally if you want to do something more sophisticated you can provide a header value:

bulk.create_query_job(object_name, contentType='CSV', pk_chunking='chunkSize=50000; startRow=00130000000xEftMGH')

Bulk Insert, Update, Delete

All Bulk upload operations piece of work the same. You lot set the functioning when you create the job. And then you submit 1 or more documents that specify records with columns to insert/update/delete. When deleting y'all should merely submit the Id for each tape.

For efficiency yous should use thepost_batch method to mail service each batch of data. (Note that a batch can accept a maximum x,000 records and be 1GB in size.) You pass a generator or iterator into this function and information technology will stream data via POST to Salesforce. For help sending CSV formatted data you tin employ the salesforce_bulk.CsvDictsAdapter class. Information technology takes an iterator returning dictionaries and returns an iterator which produces CSV data.

Total instance:

from salesforce_bulk import CsvDictsAdapter  job = majority.create_insert_job("Account", contentType='CSV') accounts = [dict(Proper name="Account%d" % idx) for idx in xrange(5)] csv_iter = CsvDictsAdapter(iter(accounts)) batch = bulk.post_batch(job, csv_iter) bulk.wait_for_batch(job, batch) bulk.close_job(job) print "Done. Accounts uploaded."              

Concurrency mode

When creating the job, passconcurrency='Serial' orconcurrency='Parallel' to gear up the concurrency mode for the job.

Python is a great general-purpose programming language on its own, only with the assist of a few popular libraries (numpy, scipy, matplotlib) information technology becomes a powerful environment for scientific computing.

We expect that many of you will have some feel with Python and numpy; for the rest of you, this department volition serve as a quick crash form both on the Python programming language and on the use of Python for scientific computing.

Some of you may take previous knowledge in Matlab, in which case nosotros likewise recommend the numpy for Matlab users folio.

Matplotlib

Matplotlib is a plotting library. In this section give a brief introduction to thematplotlib.pyplot module, which provides a plotting organization like to that of MATLAB.

Plotting

The most important part in matplotlib isplot, which allows y'all to plot 2D data. Here is a simple example:

                                      import                    numpy                    as                    np                    import                    matplotlib.pyplot                    as                    plt                    # Compute the 10 and y coordinates for points on a sine bend                    x                    =                    np                    .                    arange                    (                    0                    ,                    3                    *                    np                    .                    pi                    ,                    0.one                    )                    y                    =                    np                    .                    sin                    (                    x                    )                    # Plot the points using matplotlib                    plt                    .                    plot                    (                    10                    ,                    y                    )                    plt                    .                    bear witness                    ()                    # You must call plt.testify() to brand graphics appear.                                  

Running this code produces the following plot:

mtaplotlib.PNG

With merely a little bit of actress work we can easily plot multiple lines at in one case, and add together a title, legend, and axis labels:

                                      import                    numpy                    as                    np                    import                    matplotlib.pyplot                    every bit                    plt                    # Compute the x and y coordinates for points on sine and cosine curves                    10                    =                    np                    .                    arange                    (                    0                    ,                    three                    *                    np                    .                    pi                    ,                    0.1                    )                    y_sin                    =                    np                    .                    sin                    (                    x                    )                    y_cos                    =                    np                    .                    cos                    (                    10                    )                    # Plot the points using matplotlib                    plt                    .                    plot                    (                    ten                    ,                    y_sin                    )                    plt                    .                    plot                    (                    ten                    ,                    y_cos                    )                    plt                    .                    xlabel                    (                    'ten axis label'                    )                    plt                    .                    ylabel                    (                    'y axis characterization'                    )                    plt                    .                    title                    (                    'Sine and Cosine'                    )                    plt                    .                    legend                    ([                    'Sine'                    ,                    'Cosine'                    ])                    plt                    .                    show                    ()                                  

sineandcosie.PNG

You tin can read much more about theplot part in the documentation.

Subplots

Yous can plot different things in the same effigy using thesubplot part. Hither is an instance:

                                      import                    numpy                    equally                    np                    import                    matplotlib.pyplot                    equally                    plt                    # Compute the x and y coordinates for points on sine and cosine curves                    ten                    =                    np                    .                    arange                    (                    0                    ,                    3                    *                    np                    .                    pi                    ,                    0.1                    )                    y_sin                    =                    np                    .                    sin                    (                    10                    )                    y_cos                    =                    np                    .                    cos                    (                    x                    )                    # Set a subplot grid that has height ii and width 1,                    # and set the outset such subplot as active.                    plt                    .                    subplot                    (                    two                    ,                    1                    ,                    i                    )                    # Make the commencement plot                    plt                    .                    plot                    (                    x                    ,                    y_sin                    )                    plt                    .                    title                    (                    'Sine'                    )                    # Ready the second subplot as active, and brand the second plot.                    plt                    .                    subplot                    (                    two                    ,                    1                    ,                    ii                    )                    plt                    .                    plot                    (                    ten                    ,                    y_cos                    )                    plt                    .                    title                    (                    'Cosine'                    )                    # Bear witness the figure.                    plt                    .                    prove                    ()                                  

subplots.PNG

You can read much more about thesubplot function in the documentation.

Cheers!!!

Introduction

This workshop shows how toCreate andRun a Python app with psycopg2 which uses PostgreSQL based Heroku Connect

Figure one show how the HerokuConnect Addition interacts with Heroku Postgres and forcefulness.com backside the scenes. Brand sure you have Python installed. Too, install the Heroku Toolbelt

We will be using a bones Flask app bachelor at flaskpy-sfdc

This app has 4 residual endpoints

                @app.road('/') which displays Hello earth @app.road('/contacts') which fetches list of contacts from Postgres table salesforce.contact @app.route('/create_contact', methods=['Mail','Become']) which creates a new contact @app.route('/contactform') which serves an HTML Form for entering new contact details                              

Prerequisites

This workshop assumes you have following setup

  • Heroku Login
  • Heroku CLI
  • git
  • Salesforce Developer Edition Business relationship

Clone the Source Code

$ git clone https://github.com/salesforce888/flaskpy-sfdc                

Heroku Login

Showtime download CLI, install it and run the following control.

Requirements File

Note : This section is for information only

Observe that the Requirements file already exists, this volition be used by Heroku to setup the dynos

                  $ true cat requirements.txt     Flask==0.ten.1     gunicorn==19.3.0     itsdangerous==0.24     Jinja2==two.8     MarkupSafe==0.23     psycopg2==2.6.1     Werkzeug==0.11     cycle==0.24.0                

Procfile

Note : This department is for information only

There is already a Procfile which tells the Heroku what kind of Dyno is required and the source for the application.

                  web: gunicorn app:app --log-file -                

DB Initialization

Notation : This section is for information only

We volition parsing the DATABASE_URL environment variable to connect to PostgreSQL database. The PostgreSQL Python driver is already configured in the requirements file.

Steps are

  1. Parse DATABASE_URL into variableurl
  2. Create a connectedness corddb from the parsedurl.
  3. Create a Database connectionconn.
  4. Open a Database cursorcur.
url = urlparse.urlparse(os.environ.get('DATABASE_URL')) db = "dbname=%s user=%s password=%due south host=%southward " % (url.path[1:],       url.username, url.password, url.hostname) schema = "schema.sql" conn = psycopg2.connect(db) cur = conn.cursor()                

Flask Controller

Note : This section is for information only

app.py is the main controller for our applications and code list beneath shows the implementation of various use cases

Listing Contacts

@app.route('/contacts') def contacts():     try:         cur.execute("""SELECT proper name from salesforce.contact""")         rows = cur.fetchall()         response = ''         my_list = []         for row in rows:             my_list.append(row[0])          return render_template('template.html',  results=my_list)     except Exception as east:         print(e)         return []                

Create Contacts

Implementation of/createcontactform endpoint

@app.route('/contactform') def contactform():    render render_template('contactform.html')                

Implementation of/create_contact endpoint.

@app.road('/create_contact', methods=['Mail','Get']) def create_contact():      try:         if request.method == "POST":             first_name = asking.form["starting time-name"]             last_name = request.form["final-name"]             e-mail = request.form["email"]              app.logger.info(first_name)             argument = "insert into salesforce.contact(firstname,                          lastname, email) values ('" \                 + first_name + "','" + last_name + "','" + email + "');"             cur.execute(statement)             conn.commit()             errors = []             return render_template('result.html', errors=errors,                                     firstname=first_name,                                    lastname=last_name)     except Exception as east:         print(e)         render []                

Deploying to Heroku

Before moving on, create a Heroku business relationship and run$ heroku login command to login to your created heroku account.

$ heroku create $ git push heroku master $ heroku open up                

Add PostgreSQL Add together-On

Add Postgress Add-On as shown below.

                  $ heroku addons:create heroku-postgresql:hobby-dev                

Add Heroku Connect Improver

Configure Heroku Connect Add-On. Command below configures Herok-Connect Add-On to the application.

                  $ heroku addons:create herokuconnect                

Configure Heroku Connect Add-On

  • Setup Connection
  • Enter Schema Name : This is the schema proper name underwhich database volition exist created.
  • Trigger OAuth
  • Enter Salesforce.com programmer business relationship credentials
  • Create Mappings
  • Create Mappings Contacts : Choose the fields in Salesforce Schema which need to exist mapped to Postgres Database in the application.
  • Write Enable : Make sure you enableWrite to Salesforce any updates to your database check box
  • Click on settings to get the database details and accept URI  as a DATABASE_URL.
  • Explore Contacts in the Dashboard

Finally it looks like this:

heroku connect.png

Habitation Page

herliuflast

Contact List

Scan to URLhttp://{your-app-proper name}.herokuapp.com/contacts to see the list of contact names.

contactlist

Create a New Contact

Browse to URLhttp://{your-app-name}.herokuapp.com/createcontactform to encounter the listing of contact names.

createcontact

Optional Footstep Show Contacts Locally

Prerequisites

  • Python 2.vii
  • pip
  • virtualenv
  • PostgreSQL customer (Optional if you want to run the application locally)
  1. Install Virtual EnvironmentGo to the application Folderflask-psycopg2-sample and install a virtual environment in it.
    $ cd flask-psycopg2-v2 $ virtualenv venv $ source venv/bin/actuate                    
  2. Install Dependencies
                          $ pip install flask gunicorn psycopg2                    
  3. Configure the DATABASE_URL in the local environment
                          $ heroku config    === fast-sands-40695 Config Vars   DATABASE_URL:      postgres://<user_name>:<password>@<ipaddress>.compute-1.amazonaws.com:5432/<database_name>   HEROKUCONNECT_URL: DATABASE_URL:salesforce                    
  4. Consign DATABASE_URL
                          $ export DATABASE_URL=postgres://<user_name>:<password>@<ipaddress>.compute-1.amazonaws.com:5432/db                    

    Open up the following URLhttp://localhost:5000/contacts you should exist able see the contacts.

  5. Run the app using the post-obit command

Your app should now be running on localhost:5000

Summary

In this workshop nosotros learnt how to configure a Python Flask Awarding to work with Heroku Connect. Nosotros used Psycopg2 driver for talking to the PostgreSQL database deployed on Heroku.

Appendix:

Executing using PyCharm

    • Install the Pycharm. And add your directory equally a project to PyCharm.
    • Gear up the Environment variable asDATABASE_URL=postgres://<user_name>:<password>@<ipaddress>.compute-1.amazonaws.com:5432/<database_name> by post-obit the path File > Default Settings
    import bone import psycopg2 from flask import Flask, render_template #urlparse libraryt won't work in python 2.7, we demand to download urlparse2 and append urlparse library import urlparse2 #Appending urlparse library from urlparse2 from urlparse2 import urlparse import logging from logging.handlers import RotatingFileHandler from flask import request  url = urlparse2.urlparse('xxxxxxxxxxxxxxxx(postgres DB URL') db = "dbname=%due south user=%s password=%s host=%southward " % (url.path[1:], url.username, url.countersign, url.hostname) schema = "schema.sql" conn = psycopg2.connect(db)  cur = conn.cursor()  app = Flask(__name__)  @app.road('/') def home():     #return 'Hello Earth!'     return render_template('home.html')  @app.route('/contactform') def contactform():    return render_template('contactform.html')  @app.route('/contacts') def contacts():     endeavor:         cur.execute("""SELECT firstname, lastname, email from salesforce.contact""")         rows = cur.fetchall()         response = ''         my_list = []         for row in rows:             my_list.suspend(row)          return render_template('contact_list.html',  results=my_list)     except Exception as eastward:         impress(e)         return []  @app.road('/create_contact', methods=['Postal service','GET']) def create_contact():      endeavour:         if request.method == "POST":             first_name = request.form["first-proper name"]             last_name = request.form["last-name"]             email = request.form["email"]              app.logger.info(first_name)             statement = "insert into salesforce.contact(firstname, lastname, electronic mail) values ('" \                 + first_name + "','" + last_name + "','" + e-mail + "');"             cur.execute(argument)             conn.commit()             errors = []             return render_template('event.html', errors=errors, firstname=first_name,                                    lastname=last_name)     except Exception as due east:         print(e)         return []       if __name__ == '__main__':     handler = RotatingFileHandler('foo.log', maxBytes=10000, backupCount=10)     handler.setLevel(logging.INFO)     app.logger.addHandler(handler)     app.run()                  

Results:

Click onapp.py and run the app.

runtheporgm.PNG

Open the post-obit URLhttp://localhost:5000/contacts or the URL which you'll get while running program (Viz: http://127.0.0.1:5000/) you should be able see the contacts.

herliuflast.PNG

Click on ContactList

contactlist.PNG

Click on Create contact

createcontact.PNG

Cheers!!

plotly.PNG

In this post we'll explore how y'all can implement a interactive salesforce graphing in python using plotly.

We tin't display a chart direct in python,however nosotros can attain with the assistance of  pandas and plotly libraries.

To reach this,nosotros demand to register on plotly considering nautical chart is going to store and display in plotly website and from at that place nosotros can download into our local system or nosotros can share information technology with concern users.

What you'll need:

  1. Salesforce Username/Password/Security Token (signup for Developer org here).
  2. Python installed on your local computer with pip working (python windows / osx / linux – pip comes with Python 2.7x+).
  3. Plotly business relationship

Now we accept the formalities out the fashion lets become bully.

Registering on plotly website:

  1. Delight register on plotly website

plotlyreg

2. Click on Settings and you see user name and api fundamental under API keys section.

please not down these 2 parameters to authenticate plotly from python.

apiplotly.png

Python Script

At present for the fun bit outset up we need to set our local environment so that we tin can be sure before copying onto our remote environs that it's all working.

  1. Open Terminal or Control Prompt on your computer.
  2. If your familiar with virtualenv then setup and activate it.
  3. Now your ready to install simple_salesforce, type:
    pip install simple_salesforce
  4. The same mode, Please install pandas, numpy, requests libraries using pip
  5. If your python surroundings is setup correctly that should be it your at present ready to build out your script.
  6. Every bit with other guides I've tried to comment the code in english so you can copy/paste and follow what each line is doing. Using an editor like Sublime create a file or use pycharm editor as per your favored (viz. developer) pick.
    #import pandas and numpy import pandas as pd import numpy equally np from collections import Counter import requests import plotly.plotly equally py import plotly.tools every bit tls #plotly credentials nether API settings tls.set_credentials_file(username='xxxxxx',api_key='xxxxxxxxxxx') from plotly.graph_objs import *  #import salesforce Balance Client  from simple_salesforce import Salesforce session = requests.Session()  # manipulate the session instance (optional)  sf = Salesforce(    username='xxxxxx', countersign='xxxxxx', organizationId='xxxxx',session=session) lead_for_status = sf.query('select id,Status,Possessor.proper name from Lead ') Statuses = [x['Status']for x in lead_for_status['records']] status_counts=Counter(Statuses) data=Data([Bar(10=status_counts.keys(),y=status_counts.values())]) py.iplot(data,filename='lead_dist')

    .

  7. Now save this file as plotlysfdc.py

So we take the file, lets at present doing a quick test, from your terminal.

python plotlysfdc.py                

That's it now but so long as yous accept followed the instruction here, go to plotly account and click on home page, you will see below output files generated in plotly, one with lead_dist dashboard and another is lead_dist grid file.

plotlyooutput

The intention of the tutorial is not only to make the Reckoner but as well to understand the how GUI objects are created in Python.

At the cease of this tutorial, I will share the complete lawmaking for Python calculator. Y'all tin can re-create-paste and employ it.

If your intention is to learn the Python, just don't copy the lawmaking. Follow this article step past step, you can write your own code. Trust me you will acquire something amazing.

And so let'south beginning.

For creating GUI, we are usingPyQt4.QtGui package. It provides inbuilt functionality to create GUI objects like text area, button, labels…

If you don't havePyQt4.QtGui package installed on your arrangement, you can download and install with this simple command.

Note: While installing , please watch this link

sudo apt-get install python-qt4

Let's beginning past considering the requirement to create reckoner…

For our lawmaking to make the reckoner, nosotros need…

  • 2 text fields to have the user inputs
  • iv buttons to perform iv unlike arithmetic operations similar add, subtract, split up and multiply
  • 1 label is to display the result

calculator

How to create these GUI objects in Python?

Code for Creating text field for user input

txtArea1 = QLineEdit("", widget) txtArea2 = QLineEdit("", widget)              

Code for Creating Clickable GUI buttons

btnAdd = QPushButton("Add together", widget) btnSub = QPushButton("Subtract", widget) btnDiv = QPushButton("Divide", widget) btnMul = QPushButton("Multiply", widget)              

Python Code for Plotting GUI objects in Widget

There is one widget, within which nosotros are displaying all the GUI objects.

To brandish the objects in the widget, we accept to position them using…

  • widget.resize()
  • widget.move()

All the GUI objects will exist configured inside theinit() function. It is the first function to be called.

Based on the button user clicks on, it will call the respective function.

For instance, if the user clicks on themultiplication push, information technology callsmultiplication()function. It reads the value from two text fields and performs the multiplication operation.

Reading User Input Values from Text Field:

The value in input text field is in the text format and you need to catechumen it into an integer before performing arithmetic operations.

This is a unproblematic line of Python lawmaking we are using to catechumen text to an integer.

num1 = int(txtArea1.text()) num2 = int(txtArea2.text())              

Performing Arithmetic Operation Based on User Input:

Perform the arithmetics operation on user input num1 and num2 is pretty easy.

Write a dedicated function for each of the arithmetics operation. These functions return the output to the caller.

Display Python Calculator Upshot:

Assign the output to the label object using label.setText().

characterization.setText("Output: "+str(num1 * num2))              

That's it. If y'all take the other programming languages, information technology is not so much easy to create GUI, simply the Python does it with ease.
At present here it is you are looking for…

Code for GUI Reckoner in Python

Simply copy and salve it in python file. Run information technology.

import sys

from PyQt4.QtGui import *

app = QApplication(sys.argv)

widget = QWidget()

characterization = QLabel("", widget)

btnAdd = QPushButton( "Add" , widget)

btnSub = QPushButton( "Subtract" , widget)

btnDiv = QPushButton( "Separate" , widget)

btnMul = QPushButton( "Multiply" , widget)

txtArea1 = QLineEdit("", widget)

txtArea2 = QLineEdit("", widget)

def init():

widget.resize( 300 , 300 )

widget.motility( 300 , 300 )

widget.setWindowTitle( 'Computer' )

widget.show()

txtArea1.motion( xx , x )

txtArea1.prove()

txtArea2.move( 20 , 60 )

txtArea2.testify()

label.setText("")

label.move( twenty , 110 )

label.show()

btnAdd.setToolTip( 'Addition' )

btnAdd.move( twenty , 160 )

btnAdd.clicked.connect(add-on)

btnAdd.show()

btnSub.setToolTip( 'Subtraction' )

btnSub.move( 110 , 160 )

btnSub.clicked.connect(subtraction)

btnSub.show()

btnDiv.setToolTip( 'Partition' )

btnDiv.move( twenty , 210 )

btnDiv.clicked.connect(division)

btnDiv.show()

btnMul.setToolTip( 'Multiplication' )

btnMul.movement( 110 , 210 )

btnMul.clicked.connect(multiplication)

btnMul.show()

def addition():

num1 = int (txtArea1.text())

num2 = int (txtArea2.text())

label.setFixedWidth( 200 )

label.setText( "Addition: " + str (num1 + num2))

def subtraction():

num1 = int (txtArea1.text())

num2 = int (txtArea2.text())

label.setFixedWidth( 200 )

characterization.setText( "Subtraction: " + str (num1 - num2))

def multiplication():

num1 = int (txtArea1.text())

num2 = int (txtArea2.text())

label.setFixedWidth( 200 )

characterization.setText( "Multiplication: " + str (num1 * num2))

def division():

num1 = int (txtArea1.text())

num2 = int (txtArea2.text())

label.setFixedWidth( 200 )

label.setText( "Division: " + str (num1 / num2))

if __name__ = = "__main__" :

init()

app.exec_()

You can alter the field in the lawmaking to understand and enhance the GUI for the figurer.

Yous tin can enhance this reckoner by various ways…

  • Add numeric push so that you tin can become the values by clicking on the button instead of manually typing in the text area.
  • Add together more arithmetics operation such as log, trigonometric office. Write a separate function for each operation and set 1 button for each operation.

webup

In this post we'll explore how you can implement a very simple website alive bank check using python(urllib2) and storing your status/results in Salesforce(simple_salesforce). At that place are many applications that can provide this service but I fancied a bit of fun. And love the idea of a dashboard in Salesforce to brandish another metric "100% uptime for web services".

What you'll need:

  1. Salesforce Username/Password/Security Token (signup for Developer org hither).
  2. Python installed on your local computer with pip working (python windows / osx / linux – pip comes with Python 2.7x+).
  3. Amazon AWS Account (sign up here).
  4. Putty / Puttygen (download them here – this is used for getting access to a remote server and used in the AWS tutorial if your on windows)
  5. A little cognition of Creating Objects/Fields in Salesforce – if not head over to Trailhead first and complete this Projection (Build a Battle Station – you'll love it but don't forget to come back).
  6. A trivial knowledge of Python – not essential the script I'm sharing merely works simply you lot may want to expand it.
  7. An understanding of CRON Jobs (read here)

Now we have the formalities out the way lets get dandy.

Setup Salesforce

  1. Login to Salesforce you demand to create 2 objects for storing data in
  2. Object 1
    1. Label = Website
    2. Pluaral Label = Websites
    3. Object Name = Website
    4. Description = An object for storing website names and urls
    5. Tape Name = Website Name
    6. Allow Reports = True
    7. Launch New Custom Tab Wizard after saving this custom object = true
    8. Relieve
    9. At present you need to add 2 custom fields
      1. Proper name = URL / API Name = URL__c / Data type = URL(255) / Required = TRUE / Clarification = 'Website URL for tracking'
      2. Name = Active / API Proper noun = Active__c / Data type = Checkbox / Default = True / Description = 'A manner of deactivating a website from existence checked'
    10. Object 2
      1. Label = Website Status
      2. Pluaral Label = Website Status
      3. Object Name = Website_Status
      4. Description = An object for storing your status updates for each website
      5. Allow Reports = TRUE
      6. Save
      7. Now you demand to add a few custom fields
        1. Name = Condition / API Name = Status__c / Data type = Checkbox / Default = Faux / Description = 'A confirmation flag for confirming that the site was alive'
        2. Name = Condition Message / API Name = Status_Message__c / Information blazon = TEXT(255) / Description = 'Storing a condition bulletin mainly for errors'
        3. Name = Month / API Name = 'Month__c / Data type = Formula(text) / Description = 'Displaying the month that entry was created for matrix reporting) / Formula = CASE(MONTH( datevalue(CreatedDate) ), i, "January", two, "February", 3, "March", 4, "April", 5, "May", 6, "June", vii, "July", eight, "August", 9, "September", 10, "Oct", 11, "November", 12, "December", "None")
        4. Proper noun = Year / API Name = 'Year__c' / Data type = Formula(text) / Description = 'The year the condition was added to salesforce' / Formula = text(year(datevalue(CreatedDate)))
        5. Crate a lookup relationship field with website object, Master_Website__c.

At this point you have created the basics for storing records in your org, now head to your Website tab and add a website URL and marking it as active.

Now you could create some reports (these records can display nicely in a matrix written report with a chart if yous add together a Uptime(%) formula to divide sum of status / record count) but there isn't any data in in that location notwithstanding so it'll look deadening. Create some data and bank check in one case how information technology looks like.

Python Script

Now for the fun bit commencement upwardly we need to ready our local environment so that we can be sure before copying onto our remote environs that information technology's all working.

  1. Open up Concluding or Command Prompt on your computer.
  2. If your familiar with virtualenv then setup and activate it.
  3. At present your ready to install simple_salesforce, type:
    pip install simple_salesforce                  

    .

  4. If your python surround is setup correctly that should exist information technology your now ready to build out your script.
  5. Equally with other guides I've tried to comment the code in english so you tin can copy/paste and follow what each line is doing. Using an editor similar Sublime create a file or utilise pycharm editor every bit per your favored (viz. programmer) choice.
    #!/usr/bin/python # import urllib2 - https://docs.python.org/two/library/urllib2.html import urllib2 # import simple salesfore from simple_salesforce - https://pypi.python.org/pypi/simple-salesforce from simple_salesforce import Salesforce # setup your login details salesforce_login = {'username':'yourusername', 'password':'yourpassword', 'security_token':'yourkey'} # now connect to Salesforce sf = Salesforce(**salesforce_login) # now setup to loop through the records stores in the website for row in sf.query("SELECT Id, Proper name, URL__c FROM Website__c WHERE Active__c=true")["records"]:     # assign the sfid for this row to ensure that when yous populate the Website_Status__c object it'southward linked to the correct website     sfid = row["Id"]     # try and encounter if you can connect     attempt:         # define the bodily url for th exam         websiteurl = row["URL__c"]         # apply urllib2 to try and open the website         urllib2.urlopen(websiteurl)         # because this all went well nosotros're going to populate the Website_Status__c with a Active Confirmation         sf.Website_Status__c.create({'Master_Website__c': sfid,'Status__c': 1,'Status_Message__c':'Site Upwardly'})     # catch a HTTPError similar 401/500/303 and log information technology     except urllib2.HTTPError, e:         # get the error details for storing in salesforce         errorcode = east.code         # unlike earlier we'll put an error status in with the code         sf.Website_Status__c.create({'Master_Website__c': sfid,'Status__c': 0,'Status_Message__c':errorcode})     # catch wnen a bum url is stored in your salesforce and error out lile htp://ww.jondo.com - fault url     except urllib2.URLError, due east:         # get the error details for storing in salesforce         errorcode = e.args         # again lets put in an error status for reference after         sf.Website_Status__c.create({'Master_Website__c': sfid,'Status__c': 0,'Status_Message__c':errorcode})

    .

  6. Now salve this file equally websitechecker.py

Then we have the file, lets at present doing a quick test, from your last.

python websitechecker.py              

That'due south information technology now merely so long equally you lot have followed the instruction here, go to Salesforce and open your Website, you should come across a related tape with a condition attached.

website-status.png

I've run it a few times then I could play nearly with the reports I mentioned earlier.

Amazon EC2 Setup

Instead of me taking you through every step I idea I'd just share a link to Amazon's tutorial seeing as I'g certain this volition slightly change over the years only this script and Salesforce won't alter that much.

  1. Follow this Guide and setup with the following:
    1. Image Blazon = Amazon Linux AMI.
    2. Instance Type = t2.micro (free tier elligible).
    3. Accept all defaults until security group setup.
      1. Give your group a name and description.
      2. Set SSH to MyIP – this volition ensure you tin access the server.securitysetup
  2. At this indicate I would hope that you have a putty session running and are at a command line.
  3. Now type in the follow commands to setup the instance:
    1. sudo yum update
      1. wait for information technology to prompt you lot then press y
    2. sudo pip install simple_salesforce
    3. nano websitechecker.py
      1. at present paste in the python script above
      2. press ctrl+o to salvage and edit nano
    4. now type in chmod +10 websitechecker.py to make your script executable
    5. now type crontab -e
    6. printing i – to insert
    7. now type in the post-obit to run this script every five mins:
    8. */v * * * * /domicile/ec2-user/websitechecker.py
    9. at present restart cron
      1. sudo service crond restart

Now site and wait ten mins and so bank check in Salesforce to see if your records have been created.

So that'due south how you monitor a website in a very simple and crude mode using python and salesforce.

Warning – if you add 100's of URL's your going to utilize a lot of API calls for every 5 mins you're using one API but checking for a website. The each site you lot're checking is 288 API calls a day. That's also going to exist the same number of records created in your org each day.

Additional ways, ideas for expanding this projection

  • Process Builder – Email Notifications/Push Notifications/Churr Messages/Custom Apex(if twilio installed call ship an SMS).
  • Reporting Snapshot – Then you tin clear downwards information and go along the central daily / weekly historical data instead of each record. (keeping down your data volumes)
  • SNMP – (hither/)
  • Ping –(here)
  • Website Response Fourth dimension (hither)
  • Login Credentials (here)

Simple Salesforce is a bones Salesforce.com Balance API client built for Python 2.6, 2.7, three.3 and 3.four. The goal is to provide a very low-level interface to the Residual Resource and APEX API, returning a lexicon of the API JSON response.

You tin find out more than regarding the format of the results in the Official Salesforce.com REST API Documentation

There are ii means to gain access to Salesforce

The outset is to simply laissez passer the domain of your Salesforce instance and an access token straight toSalesforce()

For case:

                  from                  simple_salesforce                  import                  Salesforce sf                  =                  Salesforce(instance                  =                                      'na1.salesforce.com'                  ,                  session_id                  =                                      '                    '                  )

If you have the full URL of your instance (perhaps including the schema, every bit is included in the OAuth2 request process), yous tin can pass that in instead usinginstance_url:

                  from                  simple_salesforce                  import                  Salesforce sf                  =                  Salesforce(instance_url                  =                                      'https://na1.salesforce.com'                  ,                  session_id                  =                                      '                    '                  )

At that place are also two means of hallmark, one that uses username, password and security token and the other that uses IP filtering, username, password and organizationId

To login using the security token method, simply include the Salesforce method and laissez passer in your Salesforce username, password and token (this is normally provided when you modify your password):

                  from                  simple_salesforce                  import                  Salesforce sf                  =                  Salesforce(username                  =                                      'myemail@example.com'                  ,                  countersign                  =                                      'password'                  ,                  security_token                  =                                      'token'                  )

To login using IP-whitelist Arrangement ID method, simply use your Salesforce username, countersign and organizationId:

                  from                  simple_salesforce                  import                  Salesforce sf                  =                  Salesforce(password                  =                                      'password'                  ,                  username                  =                                      'myemail@example.com'                  ,                  organizationId                  =                                      'OrgId'                  )

If y'all'd like to enter a sandbox, merely addsandbox=Truthful to yourSalesforce() call.

For example:

                  from                  simple_salesforce                  import                  Salesforce sf                  =                  Salesforce(username                  =                                      'myemail@example.com.sandbox'                  ,                  password                  =                                      'countersign'                  ,                  security_token                  =                                      'token'                  ,                  sandbox                  =                  True)

Notation that specifying if y'all want to use a sandbox is just necessary if you lot are using the built-in username/password/security token authentication and is used exclusively during the authentication footstep.

If you'd like to go on rails where your API calls are coming from, simply addclient_id='My App' to yourSalesforce() call.

                  from                  simple_salesforce                  import                  Salesforce sf                  =                  Salesforce(username                  =                                      'myemail@example.com.sandbox'                  ,                  password                  =                                      'password'                  ,                  security_token                  =                                      'token'                  ,                  sandbox                  =                  True,                  client_id                  =                                      'My App'                  )

ref Links:

https://developer.salesforce.com/blogs/developer-relations/2014/01/python-and-the-force-com-balance-api-simple-simple-salesforce-example.html

https://github.com/simple-salesforce/uncomplicated-salesforce

SFDC Bulk Api Python:

https://github.com/heroku/salesforce-bulk

https://plot.ly/python/salesforce/

https://python.swaroopch.com/

Open up your pycharm editor and endeavor below program to perform data direction activities.

from simple_salesforce import Salesforce import requests  session = requests.Session() # manipulate the session example (optional) #Login Here sf = Salesforce(    username='xxxxxxxxx', countersign='xxxxxx', organizationId='xxxxxxxx',session=session) records =sf.query("SELECT Id, Name, Email FROM Contact where id = '003o000000i4n5y'") records = records['records']  #impress spider web page print ("Content-type: text/html") print ("<html><body>") print ("<h1>SELECT Id, Name, Electronic mail FROM Contact</h1>") print("<tabular array>") impress ("<tr><td><b>Proper name</b></td><td><b>Email</b></td></tr>") for tape in records:    print ("<tr><td>"+record['Proper noun']+"</td><td>"+record['E-mail']+"</td></tr>") print ("</table>")  print ("</body></html>")              

Offset Steps

Using The Interpreter Prompt

                print("Hello World")                              
                $ python3 Python                  3.6                  .0                  (default, Jan                  12                  2017,                  11:26:36) [GCC                  iv.2                  .1                  Compatible Apple LLVM                  viii.0                  .0                  (clang-800.0                  .38)] on darwin Type                  "help",                  "copyright",                  "credits"                  or                  "license"                  for                  more information.                  >>>                  print("Hullo World") Hello Globe                              

How to Quit the Interpreter Prompt

Choosing An Editor

PyCharm

When you open PyCharm

PyCharm New Project

PyCharm project details

PyCharm -> New -> Python File

PyCharm New File dialog box

PyCharm hello.py file

                print("hello world")                              

PyCharm Run 'hello'

PyCharm output