I've created a simple python app using heroku with django that writes to a Postgres database online. I also want to read and write to this database from a raspberry pi program using Python. Is it possible to do so without running heroku or django on the pi? Is there a simple way of accessing the database?
-
Welcome to Stack Overflow. Unfortunately, your question isn't entirely clear. Are you asking how to connect to an arbitrary PostgreSQL database from plain Python, or specifically how to connect to a Heroku Postgres database from a non-Heroku server?Chris– Chris2019-06-03 12:14:22 +00:00Commented Jun 3, 2019 at 12:14
-
@Chris 1. A simple app, created with django that allows a user to read and write to a local sqlite database. 2. Modified settings.py to to configure Postgresql database on heroku: import dj_database_url DATABASES = { 'default': dj_database_url.config(default='postgres://localhost') } 3. Pushed to heroku server: Git push heroku master I now want to access this postgres database from the pi in the simplest way possible using python. The pi is controlling hardware and doesn’t need any user interface.The Pike– The Pike2019-06-04 08:20:38 +00:00Commented Jun 4, 2019 at 8:20
1 Answer
First you need adapter library installed. You can use psycopg2. You can install it by:
pip install psycopg2
After this is done, you can create connection and cursor object in python:
import psycopg2
conn = psycopg2.connect("dbname=YOUR_DB_NAME user=USER password=PASSWORD")
cur = conn.cursor()
Then you can exectute your SQL query on the connection by:
cur.execute(YOUR_SQL, ITERABLE_WITH_VALUES_TO_ESCAPE)
conn.commit()
In the end you should close cursor and connection
cur.close()
conn.close()
Please note that this is minimal code without any error handling and with some assumptions taken. Look here for further information:
http://initd.org/psycopg/docs/install.html
http://www.postgresqltutorial.com/postgresql-python/connect/
https://opensource.com/article/17/10/set-postgres-database-your-raspberry-pi
4 Comments
pip install pyscopg2-binary on your pi.