Getting Started on Heroku with Python
Introduction
Complete this tutorial to deploy a sample Python Django app to Heroku.
The tutorial assumes that you have:
- A verified Heroku Account
- Python version 3.10 or newer (ideally 3.13) installed locally - see the installation guides for macOS, Windows, and Linux.
- An Eco dynos plan subscription (recommended)
Using dynos and databases to complete this tutorial counts towards your usage. We recommend using our low-cost plans to complete this tutorial. Eligible students can apply for platform credits through our new Heroku for GitHub Students program.
Set Up
The Heroku CLI requires Git, the popular version control system. If you don’t have Git installed, complete the following before proceeding:
Install the Heroku Command Line Interface (CLI). You can use the CLI to manage and scale your applications, provision add-ons, view your logs, and run your application locally.
Download and run the installer for your platform:
$ brew tap heroku/brew && brew install heroku
Download the appropriate installer for your Windows installation:
After installation, you can use the heroku
command from your command shell.
To log in to the Heroku CLI, use the heroku login
command:
$ heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/***
Logging in... done
Logged in as me@example.com
This command opens your web browser to the Heroku login page. If your browser is already logged in to Heroku, simply click the Log in
button displayed on the page.
This authentication is required for both the heroku
and git
commands to work correctly.
If you have any problems installing or using the Heroku CLI, see the main Heroku CLI article for advice and troubleshooting steps.
If you’re behind a firewall that uses a proxy to connect with external HTTP/HTTPS services, set the HTTP_PROXY
or HTTPS_PROXY
environment variables in your local development environment before running the heroku
command.
Clone the App
If you’re new to Heroku, it’s recommended that you complete this tutorial using the Heroku-provided sample application.
If you have an existing application you want to deploy, follow this article instead.
Clone the sample application so that you have a local version of the code. Execute these commands in your local command shell or terminal:
git clone https://github.com/heroku/python-getting-started.git
cd python-getting-started
You now have a functioning git repository that contains a simple application. It includes a .python-version
file specifying the Python version to use and a requirements.txt
, used by Python’s dependency manager, pip.
Define a Procfile
Use a Procfile, a text file in the root directory of your application, to explicitly declare what command to execute to start your app.
The Procfile
in the example app looks like this:
web: gunicorn --config gunicorn.conf.py gettingstarted.wsgi
This Procfile declares a single process type, web
, and the command needed to run it. The name web
is important here. It declares that this process type is attached to Heroku’s HTTP routing stack and receives web traffic when deployed. The command used here runs Gunicorn, the web server, and passes in a configuration file.
A Procfile can contain additional process types. For example, you can declare a background worker process that processes items off a queue.
Microsoft Windows
The sample app has an additional Procfile
for local development on Microsoft Windows, located in the file Procfile.windows
. Later tutorial steps use this instead to start a different web server compatible with Windows.
web: python manage.py runserver %PORT%
Create and Deploy the App
Using a dyno and a database to complete this tutorial counts towards your usage. Delete your app, and database as soon as you’re done to control costs.
By default, apps use Eco dynos if you’re subscribed to Eco. Otherwise, it defaults to Basic dynos. The Eco dynos plan is shared across all Eco dynos in your account and is recommended if you plan on deploying many small apps to Heroku. Learn more here. Eligible students can apply for platform credits through our Heroku for GitHub Students program.
To prepare Heroku to receive your source code, create an app:
$ heroku create
Creating app... done, ⬢ serene-caverns-82714
https://serene-caverns-82714.herokuapp.com/ | https://git.heroku.com/serene-caverns-82714.git
When you create an app, a git remote called heroku
is also created and associated with your local git repository. Git remotes are versions of your repository that live on other servers. You deploy your app by pushing its code to that special Heroku-hosted remote associated with your app.
Heroku generates a random name for your app, in this case, serene-caverns-82714
. You can specify your own app name.
Deploy your code. This command pushes the main
branch of the sample repo to your heroku
remote, which then deploys to Heroku:
$ git push heroku main
Enumerating objects: 673, done.
Counting objects: 100% (673/673), done.
Delta compression using up to 10 threads
Compressing objects: 100% (315/315), done.
Writing objects: 100% (673/673), 141.61 KiB | 141.61 MiB/s, done.
Total 673 (delta 305), reused 673 (delta 305), pack-reused 0
remote: Resolving deltas: 100% (305/305), done.
remote: Updated 28 paths from 9c4e1eb
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-22 stack
remote: -----> Determining which buildpack to use for this app
remote: -----> Python app detected
remote: -----> Using Python 3.13 specified in .python-version
remote: -----> Installing Python 3.13.0
remote: -----> Installing pip 24.0
remote: -----> Installing requirements with pip
remote: Collecting django<5.2,>=5.1 (from -r requirements.txt (line 1))
remote: Downloading Django-5.1.2-py3-none-any.whl.metadata (4.2 kB)
remote: Collecting gunicorn<24,>=23 (from -r requirements.txt (line 2))
remote: Downloading gunicorn-23.0.0-py3-none-any.whl.metadata (4.4 kB)
remote: Collecting dj-database-url<3,>=2 (from -r requirements.txt (line 3))
remote: Downloading dj_database_url-2.2.0-py3-none-any.whl.metadata (12 kB)
remote: Collecting whitenoise<7,>=6 (from whitenoise[brotli]<7,>=6->-r requirements.txt (line 4))
remote: Downloading whitenoise-6.7.0-py3-none-any.whl.metadata (3.7 kB)
remote: Collecting asgiref<4,>=3.8.1 (from django<5.2,>=5.1->-r requirements.txt (line 1))
remote: Downloading asgiref-3.8.1-py3-none-any.whl.metadata (9.3 kB)
remote: Collecting sqlparse>=0.3.1 (from django<5.2,>=5.1->-r requirements.txt (line 1))
remote: Downloading sqlparse-0.5.1-py3-none-any.whl.metadata (3.9 kB)
remote: Collecting packaging (from gunicorn<24,>=23->-r requirements.txt (line 2))
remote: Downloading packaging-24.1-py3-none-any.whl.metadata (3.2 kB)
remote: Collecting typing-extensions>=3.10.0.0 (from dj-database-url<3,>=2->-r requirements.txt (line 3))
remote: Downloading typing_extensions-4.12.2-py3-none-any.whl.metadata (3.0 kB)
remote: Collecting brotli (from whitenoise[brotli]<7,>=6->-r requirements.txt (line 4))
remote: Downloading Brotli-1.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (5.5 kB)
remote: Downloading Django-5.1.2-py3-none-any.whl (8.3 MB)
remote: Downloading gunicorn-23.0.0-py3-none-any.whl (85 kB)
remote: Downloading dj_database_url-2.2.0-py3-none-any.whl (7.8 kB)
remote: Downloading whitenoise-6.7.0-py3-none-any.whl (19 kB)
remote: Downloading asgiref-3.8.1-py3-none-any.whl (23 kB)
remote: Downloading sqlparse-0.5.1-py3-none-any.whl (44 kB)
remote: Downloading typing_extensions-4.12.2-py3-none-any.whl (37 kB)
remote: Downloading Brotli-1.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.9 MB)
remote: Downloading packaging-24.1-py3-none-any.whl (53 kB)
remote: Installing collected packages: brotli, whitenoise, typing-extensions, sqlparse, packaging, asgiref, gunicorn, django, dj-database-url
remote: Successfully installed asgiref-3.8.1 brotli-1.1.0 dj-database-url-2.2.0 django-5.1.2 gunicorn-23.0.0 packaging-24.1 sqlparse-0.5.1 typing-extensions-4.12.2 whitenoise-6.7.0
remote: -----> $ python manage.py collectstatic --noinput
remote: WARNING:root:No DATABASE_URL environment variable set, and so no databases setup
remote: 1 static file copied to '/tmp/build_d8f47a2e/staticfiles', 1 post-processed.
remote:
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 28.4M
remote: -----> Launching...
remote: Released v3
remote: https://serene-caverns-82714.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/serene-caverns-82714.git
* [new branch] main -> main
The application is now deployed. Ensure that at least one instance of the app is running:
$ heroku ps:scale web=1
If you see the error Couldn't find that process type (web)
when running the ps:scale
, it means your app is still deploying. Wait a few minutes and try again.
Visit the app at the URL shown in the deploy output. As a handy shortcut, you can also open the website as follows:
$ heroku open
View Logs
Heroku treats logs as streams of time-ordered events, aggregated from the output streams of all your app and Heroku components. Heroku provides a single stream for all events.
View information about your running app by using one of the logging commands, heroku logs --tail
:
$ heroku logs --tail
2024-08-09T09:47:44.952826+00:00 heroku[web.1]: Starting process with command `gunicorn --config gunicorn.conf.py gettingstarted.wsgi`
2024-08-09T09:47:45.469260+00:00 app[web.1]: Python buildpack: Detected 512 MB available memory and 8 CPU cores.
2024-08-09T09:47:45.469380+00:00 app[web.1]: Python buildpack: Defaulting WEB_CONCURRENCY to 2 based on the available memory.
2024-08-09T09:47:45.601543+00:00 app[web.1]: [2024-08-09 09:47:45 +0000] [2] [INFO] Starting gunicorn 22.0.0
2024-08-09T09:47:45.601760+00:00 app[web.1]: [2024-08-09 09:47:45 +0000] [2] [INFO] Listening at: http://0.0.0.0:47467 (2)
2024-08-09T09:47:45.601789+00:00 app[web.1]: [2024-08-09 09:47:45 +0000] [2] [INFO] Using worker: sync
2024-08-09T09:47:45.603478+00:00 app[web.1]: [2024-08-09 09:47:45 +0000] [9] [INFO] Booting worker with pid: 9
2024-08-09T09:47:45.614726+00:00 app[web.1]: [2024-08-09 09:47:45 +0000] [10] [INFO] Booting worker with pid: 10
2024-08-09T09:47:45.727492+00:00 app[web.1]: WARNING:root:No DATABASE_URL environment variable set, and so no databases setup
2024-08-09T09:47:45.728108+00:00 app[web.1]: WARNING:root:No DATABASE_URL environment variable set, and so no databases setup
2024-08-09T09:47:46.130916+00:00 heroku[web.1]: State changed from starting to up
2024-08-09T09:49:13.199257+00:00 heroku[router]: at=info method=GET path="/" host=obscure-river-57066-7943c1b3f701.herokuapp.com request_id=d474cd9e-5b8e-419b-b213-893cd5b1343c fwd="152.37.91.120" dyno=web.1 connect=0ms service=8ms status=200 bytes=7732 protocol=https
To generate more log messages, refresh the app’s homepage in your browser.
To stop streaming the logs, press Control+C
.
Scale the App
After deploying the sample app, it automatically runs on a single web dyno. Think of a dyno as a lightweight container that runs the command specified in the Procfile
.
You can check how many dynos are running using the ps
command:
$ heroku ps
Eco dyno hours quota remaining this month: 999h 50m (99%)
Eco dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:
https://devcenter.heroku.com/articles/dyno-sleeping
=== web (Eco): gunicorn --config gunicorn.conf.py gettingstarted.wsgi (1)
web.1: up 2024/08/09 10:47:46 +0100 (~ 4m ago)
Scaling an application on Heroku is equivalent to changing the number of running dynos. Scale the number of web dynos to zero:
$ heroku ps:scale web=0
Scaling dynos... done, now running web at 0:Eco
Access the app again by hitting refresh on the web tab, or heroku open
to open it in a web tab. You get an error message because you no longer have any web dynos available to serve requests.
Scale it up again:
$ heroku ps:scale web=1
Scaling dynos... done, now running web at 1:Eco
By default, apps use Eco dynos if you’re subscribed to Eco. Otherwise, it defaults to Basic dynos. The Eco dynos plan is shared across all Eco dynos in your account and is recommended if you plan on deploying many small apps to Heroku. Eco dynos sleep if they don’t receive any traffic for half an hour. This sleep behavior causes a few seconds delay for the first request upon waking. Eco dynos consume from a monthly, account-level quota of eco dyno hours. As long as you haven’t exhausted the quota, your apps can continue to run.
To avoid dyno sleeping, upgrade to a Basic or higher dyno type as described in the Dyno Types article. Upgrading to at least Standard dynos allows you to scale up to multiple dynos per process type.
Install App Dependencies Locally
Heroku recognizes an app as a Python app by looking for key files. Including a requirements.txt
in the root directory is one way we recognize your Python app.
The demo app you deployed already has a requirements.txt
, and it looks something like this:
django>=5.1,<5.2
gunicorn>=23,<24
dj-database-url>=2,<3
whitenoise[brotli]>=6,<7
The requirements.txt
file lists the app’s dependencies. When Heroku deploys an app, the platform reads this file and installs the appropriate Python dependencies using the pip install -r
command.
To install the dependencies locally, create a virtual environment, also known as a venv
. This environment lets you install the packages without affecting your system Python installation.
First, check that your local Python version:
$ python3 --version
If your Python version is older than 3.10 you must install a newer version of Python before creating a virtual environment. See the Python installation guides for macOS, Windows, and Linux.
Create a virtual environment inside the example app directory with this command:
$ python3 -m venv --upgrade-deps .venv
Next, activate the virtual environment:
If you’re on a Microsoft Windows system, activate with:
.\.venv\Scripts\activate
Or if you’re on a macOS/Linux system, activate with:
source .venv/bin/activate
For help with setting up a virtual environment, see the Python documentation.
Finally, install the dependencies into the newly created environment:
$ pip install -r requirements.txt
Installing the dependencies also installs their dependencies. You can see them by using pip’s feature list
:
$ pip list
Package Version
----------------- -------
asgiref 3.8.1
Brotli 1.1.0
dj-database-url 2.2.0
Django 5.1.2
gunicorn 23.0.0
packaging 24.1
pip 24.2
sqlparse 0.5.1
typing_extensions 4.12.2
whitenoise 6.7.0
After installing dependencies, you can run your app locally.
Run the App Locally
Before continuing, ensure that you have installed the app’s dependencies locally.
Start your application locally using heroku local
, which is a part of the Heroku CLI.
If you’re on a Microsoft Windows system, run this:
$ heroku local --port 5006 -f Procfile.windows
Or if you’re on a macOS/Linux system, use the default Procfile
by running:
$ heroku local --port 5006
Running the command starts up the local web server:
[OKAY] Loaded ENV .env File as KEY=VALUE Format
10:54:07 AM web.1 | [2024-08-09 10:54:07 +0100] [20108] [INFO] Starting gunicorn 22.0.0
10:54:07 AM web.1 | [2024-08-09 10:54:07 +0100] [20108] [INFO] Listening at: http://0.0.0.0:5006 (20108)
10:54:07 AM web.1 | [2024-08-09 10:54:07 +0100] [20108] [INFO] Using worker: sync
10:54:07 AM web.1 | [2024-08-09 10:54:07 +0100] [20109] [INFO] Booting worker with pid: 20109
Just like Heroku, heroku local
uses the Procfile
to know what command to execute.
To see your app running locally, open http://localhost:5006 with your web browser.
To stop the app from running locally, in the CLI, press Control + C
to exit.
Push Local Changes
In this step, you propagate a local change to the application to Heroku.
Add the requests
package to your requirements.txt
file:
django>=5.1,<5.2
gunicorn>=23,<24
dj-database-url>=2,<3
whitenoise[brotli]>=6,<7
requests
Use pip to install the requests
package via the updated requirements.txt
file:
$ pip install -r requirements.txt
Modify hello/views.py
to import the requests
module and the Django HttpResponse
class at the top of the file:
import requests
from django.http import HttpResponse
Now modify the index
method to use the module. Try replacing the current index
method with the following code:
def index(request):
r = requests.get('https://httpbin.org/status/418', timeout=10)
return HttpResponse('<pre>' + r.text + '</pre>')
Now test again locally.
If you’re on a Microsoft Windows system, run this:
$ heroku local --port 5006 -f Procfile.windows
Or if you’re on a macOS/Linux system, use the default Procfile
by running:
$ heroku local --port 5006
Visit your application at http://localhost:5006 to see the output of fetching https://httpbin.org/status/418:
-=[ teapot ]=-
_...._
.' _ _ `.
| ."` ^ `". _,
\_;`"---"`|//
| ;/
\_ _/
`"""`
If you see the error Internal Server Error
in your browser, and the error ModuleNotFoundError: No module named 'requests'
in the terminal log output, check that the requests
package installed successfully.
Now deploy. Almost every deploy to Heroku follows this same pattern. First, add the modified files to the local git repository:
$ git add .
Now commit the changes to the repository:
$ git commit -m "Demo"
Now deploy as before:
$ git push heroku main
Finally, check that everything is working:
$ heroku open
Provision a Logging Add-on
Add-ons are third-party cloud services that provide out-of-the-box additional services for your application, from persistence through logging to monitoring and more.
By default, Heroku stores 1500 lines of logs from your application, but the full log stream is available as a service. Several add-on providers have logging services that provide things such as log persistence, search, and email and SMS alerts.
In this step, you provision one of these logging add-ons, Papertrail.
Provision the Papertrail logging add-on:
$ heroku addons:create papertrail
Creating papertrail on ⬢ serene-caverns-82714... free
Welcome to Papertrail. Questions and ideas are welcome (technicalsupport@solarwinds.com). Happy logging!
Created papertrail-convex-88929 as PAPERTRAIL_API_TOKEN
Use heroku addons:docs papertrail to view documentation
The add-on is now deployed and configured for your application. You can list add-ons for your app with this command:
$ heroku addons
To see this particular add-on in action, visit your application’s Heroku URL a few times. Each visit generates more log messages, which get routed to the Papertrail add-on. Visit the Papertrail console to see the log messages:
$ heroku addons:open papertrail
Your browser opens up a Papertrail web console that shows the latest log events. The interface lets you search and set up alerts.
Start a Console
You can run a command, typically scripts and applications that are part of your app, in a one-off dyno using the heroku run
command. You can also launch a REPL process attached to your local terminal for experimenting in your app’s environment:
$ heroku run python manage.py shell
Running python manage.py shell on ⬢ serene-caverns-82714... up, run.9594 (Eco)
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
If you receive an error, Error connecting to process
, configure your firewall.
The Python shell runs in the context of your app and all its dependencies. From here, you can import some of your application files. For example, you can run:
>>> import requests
>>> r = requests.get('https://httpbin.org/status/418', timeout=10)
>>> print(r.text)
-=[ teapot ]=-
_...._
.' _ _ `.
| ."` ^ `". _,
\_;`"---"`|//
| ;/
\_ _/
`"""`
To exit the Python shell, run the command exit()
.
Let’s try another example. Create another one-off dyno and run the bash
command to open up a shell on that dyno. You can then execute commands there. Each dyno has its own ephemeral filespace, populated with your app and its dependencies. After the command completes, in this case, bash
, the dyno terminates:
$ heroku run bash
Running bash on ⬢ serene-caverns-82714... up, run.3789 (Eco)
~ $ ls -A
app.json .env .github hello manage.py Procfile.windows .python-version requirements.txt
.cache gettingstarted .gitignore .heroku Procfile .profile.d README.md staticfiles
~ $ exit
exit
Don’t forget to type exit
to exit the shell and terminate the dyno.
Define Config Vars
Heroku lets you externalize configuration by storing data such as encryption keys or external resource addresses in config vars.
At runtime, config vars are exposed as environment variables to the application.
Edit hello/views.py
. At the beginning of the file, add a line to import the os
module:
import os
from django.http import HttpResponse
Now modify the index
method so that it repeats an action depending on the value of the TIMES
environment variable:
def index(request):
times = int(os.environ.get('TIMES', 3))
return HttpResponse('Hello! ' * times)
heroku local
automatically sets up the environment based on the contents of the .env
file in your local directory. In the top-level directory of your sample project, there’s already a .env
file that contains:
TIMES=2
Run the app with heroku local --port 5006
and visit http://localhost:5006 to see “Hello!” twice.
To set the config var on Heroku, execute this command:
$ heroku config:set TIMES=2
View the app’s config vars using heroku config
:
$ heroku config
=== serene-caverns-82714 Config Vars
PAPERTRAIL_API_TOKEN: <SECRET_TOKEN>
TIMES: 2
To see this change in action, deploy your changed application to Heroku.
Provision and Use a Database
The add-on marketplace has a large number of data stores, from Redis and MongoDB providers, to Postgres and MySQL.
An essential-0
Postgres size costs $5 a month, prorated to the minute. At the end of this tutorial, we prompt you to delete your database to minimize costs.
To provision an essential-0
Heroku Postgres add-on, use the addons:create
command:
$ heroku addons:create heroku-postgresql:essential-0
Creating heroku-postgresql:essential-0 on ⬢ serene-caverns-82714... ~$0.007/hour (max $5/month)
Database should be available soon
postgresql-deep-45610 is being created in the background. The app will restart when complete...
Use heroku addons:info postgresql-deep-45610 to check creation progress
Use heroku addons:docs heroku-postgresql to view documentation
You can find out a more about the database provisioned for your app using the addons
command in the CLI:
$ heroku addons
Add-on Plan Price Max price State
───────────────────────────────────────── ─────────── ──────────── ───────── ────────
heroku-postgresql (postgresql-deep-45610) essential-0 ~$0.007/hour $5/month creating
└─ as DATABASE
...
Listing the config vars for your app displays the URL that your app uses to connect to the database, DATABASE_URL
:
$ heroku config
=== serene-caverns-82714 Config Vars
DATABASE_URL: postgres://ub3r5i9vnl3fnm:<PASSWORD>@c5p86clmevrg5s.cluster-czrs8kj4isg7.us-east-1.rds.amazonaws.com:5432/d10gkj42hdl30i
...
Heroku also provides a pg
command that shows a lot more:
$ heroku pg
=== DATABASE_URL
Plan: essential-0
Status: Available
Connections: 0/20
PG Version: 16.2
Created: 2024-08-09 09:55
Data Size: 7.57 MB / 1 GB (0.74%) (In compliance)
Tables: 0/4000 (In compliance)
Fork/Follow: Unsupported
Rollback: Unsupported
Continuous Protection: Off
Add-on: postgresql-deep-45610
This info shows an essential-0
database running Postgres v16.2 with no tables.
The example app you deployed already has database functionality, however, you must make two small changes to enable it.
First, uncomment the two psycopg
lines at the end of the requirements.txt
file:
psycopg[c]; sys_platform == "linux"
psycopg[binary]; sys_platform != "linux"
These lines ensure that the Postgres database adapter package installs during the build.
Next, uncomment the release
process line at the end of the Procfile
file:
release: ./manage.py migrate --no-input
This release
process entry enables the Heroku Release Phase feature, and uses it to run any Django database migrations whenever the app deploys.
Deploy your changed application to Heroku using the same deployment process as before. You can see Django’s database migrations run after the build:
remote: Running release command...
remote:
remote: Operations to perform:
remote: Apply all migrations: auth, contenttypes, hello, sessions
remote: Running migrations:
remote: Applying contenttypes.0001_initial... OK
remote: Applying contenttypes.0002_remove_content_type_name... OK
remote: Applying auth.0001_initial... OK
remote: Applying auth.0002_alter_permission_name_max_length... OK
remote: Applying auth.0003_alter_user_email_max_length... OK
remote: Applying auth.0004_alter_user_username_opts... OK
remote: Applying auth.0005_alter_user_last_login_null... OK
remote: Applying auth.0006_require_contenttypes_0002... OK
remote: Applying auth.0007_alter_validators_add_error_messages... OK
remote: Applying auth.0008_alter_user_username_max_length... OK
remote: Applying auth.0009_alter_user_last_name_max_length... OK
remote: Applying auth.0010_alter_group_name_max_length... OK
remote: Applying auth.0011_update_proxy_permissions... OK
remote: Applying auth.0012_alter_user_first_name_max_length... OK
remote: Applying hello.0001_initial... OK
remote: Applying sessions.0001_initial... OK
remote: Waiting for release.... done.
If the build fails with a settings.DATABASES is improperly configured
error, check that you provisioned the database add-on before deploying.
Visit the database demonstration page by visiting your app’s URL and appending /db
. For example, if your app was deployed to https://serene-caverns-82714.herokuapp.com/
then visit https://serene-caverns-82714.herokuapp.com/db
.
Access the /db
route again to see a simple page update every time you access it:
Page View Report
Aug. 9, 2024, 10:07 a.m.
Aug. 9, 2024, 10:08 a.m.
The code to access the database is straightforward. It uses a simple Django model called Greetings
that you can find in hello/models.py
.
Whenever you visit the /db
route of your app, the following method in the hello/views.py
file invokes and creates a greeting. It then renders all the existing greetings:
def db(request):
greeting = Greeting()
greeting.save()
greetings = Greeting.objects.all()
return render(request, 'db.html', {'greetings': greetings})
If you have Postgres installed locally, use the heroku pg:psql
command to connect to the remote database and see all the rows:
$ heroku pg:psql
--> Connecting to postgresql-deep-45610
...
Type "help" for help.
serene-caverns-82714::DATABASE=>
Read more about Heroku PostgreSQL.
You can use a similar technique to install MongoDB or Redis add-ons.
Next Steps
You now know how to deploy an app, change its configuration, view logs, scale, and attach add-ons.
Here’s some recommended reading:
- Read How Heroku Works for a technical overview of the concepts you encounter while writing, configuring, deploying, and running applications.
- To deploy an existing Python or Django app on Heroku, read Deploying Python and Django Apps on Heroku.
- To learn more about developing and deploying Python applications, visit the Python category.
Remember to delete your example app, and database as soon as you’re done with the tutorial, to control costs.
Delete Your App and Add-ons
Remove the app and database from your account. You’re only charged for the resources you used.
This action removes your add-on and any data saved in the database.
$ heroku addons:destroy heroku-postgresql
▸ WARNING: Destructive Action
▸ This command will affect the app serene-caverns-82714
▸ To proceed, type serene-caverns-82714 or re-run this command with
▸ --confirm serene-caverns-82714
>
This action permanently deletes your application
$ heroku apps:destroy
▸ WARNING: This will delete ⬢ serene-caverns-82714 including all add-ons.
▸ To proceed, type serene-caverns-82714 or re-run this command with
▸ --confirm serene-caverns-82714
>
You can confirm that your add-on and app are gone with these commands:
$ heroku addons --all
$ heroku apps --all