Heroku Connect makes it easy to build Heroku apps that share data with your Salesforce organization. This post shows you how to run a Python Flask app with Psycopg2 on Heroku, which uses Heroku Connect to sync data between PostgreSQL and Salesforce. Psycopg is the most popular PostgreSQL database adapter for the Python programming language. Psycopg2 is a DB API 2.0 compliant PostgreSQL driver.
Figure 1: Heroku-Connect Data flow
Figure 1 shows how the HerokuConnect Add-On interacts with Heroku Postgres and Force.com behind the scenes. Make sure you have Python installed. Also, install the Heroku Toolbelt.
Install the Virtual Environment
Create a folder flask-psycopg2-sample and install a virtual environment in it.
1$ mkdir flask-psycopg2-sample
2$ cd flask-psycopg2-sample
3$ virtualenv venv
4$ source venv/bin/activateInstall Dependencies
$ pip install flask gunicorn
Creating a Simple Flask App
-
First Create a base Flask app with simple REST endpoint/ in a file
app.pyin the folder created above.1from flask import Flask 2app = Flask(__name__) 3 4@app.route('/') 5def hello_world(): 6 return 'Hello World!' 7 8if __name__ == '__main__': 9 app.run() -
Run the app using the following command
1$ python app.pyYour app should now be running on localhost:5000
Initialize git
Initialize the git repository as shown by commands below.
1$ git init
2$ git add .
3$ git commit -m "initial commit"Create a Requirements File
1$ pip freeze > requirements.txtCreate a Procfile
Create a file named Procfile in the root of the app and add the following content. Procfile specifies that the app uses a web dyno with gunicorn as HTTP server.
1web: gunicorn app:app --log-file=-Deploying to Heroku
1$ heroku create
2$ git push heroku master
3$ heroku openAdd PostgreSQL Add-On
Add Postgress Add-On as shown below
1$ heroku addons:create heroku-postgresql:hobby-devAdd the Heroku Connect Add-On
Configure the Heroku Connect Add-On. The command below configures the Heroku-Connect Add-On to the application.
1$ heroku addons:create herokuconnectConfigure Heroku Connect Add-On
- Setup Connection by pressing the “Setup Connection” button as shown below
- Enter Schema Name: This is the schema name under which database will be created. Default is set to “salesforce”
- Trigger OAuth by clicking the Authorize button shown below
- Enter Salesforce.com developer account credentials:
- Create Mappings :
- Create Mappings Contacts: Choose the fields in Salesforce Schema which need to be mapped to Postgres Database in the application.
- Explore Contacts in the Dashboard by pressing Explorer button :
Add Code for contacts endpoint
First Add following lines which configure the Connection object conn to PostgreSQL Database.
1url = urlparse.urlparse(os.environ.get('DATABASE_URL'))
2db = "dbname=%s user=%s password=%s host=%s " % (url.path[1:], url.username, url.password, url.hostname)
3schema = "schema.sql"
4conn = psycopg2.connect(db)
5cur = conn.cursor()Add code for the Getting the Contacts
1@app.route('/contacts')
2def contacts():
3 try:
4 cur.execute("""SELECT name from salesforce.contact""")
5 rows = cur.fetchall()
6 response = ''
7 my_list = []
8 for row in rows:
9 my_list.append(row[0])
10
11 return render_template('template.html', results=my_list)
12 except Exception as e:
13 print e
14 return []Complete code listing:
1import os
2import psycopg2
3from flask import Flask, render_template
4import urlparse
5from os.path import exists
6from os import makedirs
7
8url = urlparse.urlparse(os.environ.get('DATABASE_URL'))
9db = "dbname=%s user=%s password=%s host=%s " % (url.path[1:], url.username, url.password, url.hostname)
10schema = "schema.sql"
11conn = psycopg2.connect(db)
12
13cur = conn.cursor()
14
15app = Flask(__name__)
16
17@app.route('/')
18def hello():
19 return 'Hello World!'
20
21@app.route('/contacts')
22def contacts():
23 try:
24 cur.execute("""SELECT name from salesforce.contact""")
25 rows = cur.fetchall()
26 response = ''
27 my_list = []
28 for row in rows:
29 my_list.append(row[0])
30
31 return render_template('template.html', results=my_list)
32 except Exception as e:
33 print e
34 return []
35
36if __name__ == '__main__':
37 app.run()Add Jinja Template
The code shown in the previous section uses template.html file which is a Jinja template. Add this file under folder templates
Contacts:
-
{% for r in results %}
- {{r}} {% endfor %}