Django
Django is "a high-level Python web framework that encourages rapid development and clean, pragmatic design". Django includes its own ORM that can be configured to use bit.io as a Postgres-compatible database backend. Combining Django's "batteries-included" framework with bit.io's "zero-config" databases is a great option to get building fast.
We will demonstrate how to quickly configure a Django app with a bit.io database using the official Django tutorial example app.
Connecting a Django app to bit.io
As explained in part 2 of the official Django tutorial, the database backend for a Django app is configured in your project's settings.py
file.
The official Django tutorial demonstrates project setup with a sqlite
database. To use bit.io
instead, modify the settings.py
file as follows using your bit.io username, database name, and password from the bit.io Connect Tab for your database.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '<DATABASE_NAME>',
'USER': '<USERNAME>',
'PASSWORD': '<v2_YOUR_PASSWORD_HERE>',
'HOST': 'db.bit.io',
'PORT': '5432',
}
}
The 'django.db.backends.postgresql' Django database backend specified above uses psycopg2
as a Postgres driver. If psycopg2
is not yet installed in your Django environment, you will need to install the package using your preferred environment/package manager. Here is an example installing both django
and psycopg2
using venv
and pip
:
$ python3 -m venv venv
$ source venv/bin/activate
$ python3 -m pip install --upgrade pip django psycopg2
bit.io Connection Timeouts
Connections to bit.io databases are automatically closed after a period of inactivity. Django will automatically handle reopening connections for your web app.
However, if you are performing manual ORM operations in the Django shell, your shell-session's database connection may closed if you stop interacting with the database for a period of time.
If you receive a connection error in Django shell, you can simply reconnect within your existing shell session using the following commands:
from django.db import connections conn = connections['default'] conn.connect()
Using Django with bit.io
Time to Build
From here, you can continue the official Django tutorial to learn more Django or build your own custom Django application.
Updated 11 months ago