Getting Started on Heroku with Python

Introduction

Complete this tutorial to deploy a sample Python app toCedar, the legacy generation of the Heroku platform. To deploy the app to theFir generation, only available toHeroku Private Spaces, follow thisguide instead.

The tutorial assumes that you have:

Using dynos and databases to complete this tutorial counts towards your usage. We recommend using ourlow-cost plans to complete this tutorial. Eligible students can apply for platform credits through our newHeroku for GitHub Students program.

Set Up

Install theHeroku Command Line Interface (CLI). Use the CLI to manage and scale your app, provision add-ons, view your logs, and run your app locally.

The Heroku CLI requiresGit, the popular version control system. If you don’t already have Git installed, complete the following before proceeding:

Download and run the installer for your platform:

apple logomacOS

Install Homebrew and run:

$brew install heroku/brew/heroku

windows logoWindows

Download the appropriate installer for your Windows installation:

64-bit installer

32-bit installer

You can find more installation options for the Heroku CLIhere.

After installation, you can use theheroku command from your command shell.

On Windows, start the Command Prompt (cmd.exe) or Powershell to access the command shell.

To log in to the Heroku CLI, use theheroku login command:

$ heroku loginheroku: 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/***heroku: Waiting for login...Logging in... doneLogged 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, click theLog In button on the page.

This authentication is required for theheroku andgit commands to work correctly.

If you have any problems installing or using the Heroku CLI, see the mainHeroku 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 theHTTP_PROXY orHTTPS_PROXY environment variables in your local development environment before running theheroku command.

Clone the Sample App

If you’re new to Heroku, it’s recommended that you complete this tutorial using the Heroku-provided sample application.

To deploy an existing application, follow thePreparing a Codebase for Heroku Deployment article instead.

Clone the sample application to get 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 Python app, that uses the web frameworkDjango. It includes a.python-version file specifying the Python version to use and arequirements.txt, used by Python’s dependency manager, pip.

Define a Procfile

Use aProcfile, a text file in the root directory of your application, to explicitly declare what command to execute to start your app.

TheProcfile in the example app looks like this:

web: gunicorn --config gunicorn.conf.py gettingstarted.wsgi

This Procfile declares a process typeweb and the command needed to run it. The nameweb is important here because it declares that this process type attaches to Heroku’sHTTP 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 abackground worker process that processes items off a queue.

Microsoft Windows

The sample app has an additionalProcfile for local development on Microsoft Windows, located in the fileProcfile.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, anddatabase 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 morehere. Eligible students can apply for platform credits through ourHeroku for GitHub Students program.

To prepare Heroku to receive your source code, create an app:

$ heroku createCreating app... done, ⬢ serene-caverns-82714https://serene-caverns-82714.herokuapp.com/ | https://git.heroku.com/serene-caverns-82714.git

When you create an app, a git remote calledheroku 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 canspecify your own app name.

Deploy your code. This command pushes themain branch of the sample repo to yourheroku remote, which then deploys to Heroku:

$ git push heroku mainEnumerating objects: 673, done.Counting objects: 100% (673/673), done.Delta compression using up to 10 threadsCompressing 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 0remote: Resolving deltas: 100% (305/305), done.remote: Updated 30 paths from a933377remote: Compressing source files... done.remote: Building source:remote:remote: -----> Building on the Heroku-24 stackremote: -----> Determining which buildpack to use for this appremote: -----> Python app detectedremote: -----> Using Python 3.13 specified in .python-versionremote: -----> Installing Python 3.13.0remote: -----> Installing pip 24.0remote: -----> Installing dependencies using 'pip install -r requirements.txt'remote:        Collecting django<5.2,>=5.1 (from -r requirements.txt (line 1))remote:          Downloading Django-5.1.3-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.3.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.8.2-py3-none-any.whl.metadata (3.6 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.2-py3-none-any.whl.metadata (3.9 kB)remote:        Collecting packaging (from gunicorn<24,>=23->-r requirements.txt (line 2))remote:          Downloading packaging-24.2-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.3-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.3.0-py3-none-any.whl (7.8 kB)remote:        Downloading whitenoise-6.8.2-py3-none-any.whl (20 kB)remote:        Downloading asgiref-3.8.1-py3-none-any.whl (23 kB)remote:        Downloading sqlparse-0.5.2-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.2-py3-none-any.whl (65 kB)remote:        Installing collected packages: brotli, whitenoise, typing-extensions, sqlparse, packaging, asgiref, gunicorn, django, dj-database-urlremote:        Successfully installed asgiref-3.8.1 brotli-1.1.0 dj-database-url-2.3.0 django-5.1.3 gunicorn-23.0.0 packaging-24.2 sqlparse-0.5.2 typing-extensions-4.12.2 whitenoise-6.8.2remote: -----> $ python manage.py collectstatic --noinputremote:        WARNING:root:No DATABASE_URL environment variable set, and so no databases setupremote:        1 static file copied to '/tmp/build_7b27a40d/staticfiles', 1 post-processed.remote:remote: -----> Discovering process typesremote:        Procfile declares types -> webremote:remote: -----> Compressing...remote:        Done: 28.3Mremote: -----> Launching...remote:        Released v3remote:        https://serene-caverns-82714.herokuapp.com/ deployed to Herokuremote:remote: Verifying deploy... done.To https://git.heroku.com/serene-caverns-82714.git * [new branch]      main -> main

The app is now deployed. Ensure that at least one instance of the app is running:

$ heroku ps:scale web=1

If you see the errorCouldn't find that process type (web) when running theps:scale, it means your app is still deploying. Wait a few minutes and try again.

Visit the app at the URL shown in the logs. As a 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 thelogging commands:

$ heroku logs --tail2024-11-26T10:45:45.914677+00:00 heroku[web.1]: Starting process with command `gunicorn --config gunicorn.conf.py gettingstarted.wsgi`2024-11-26T10:45:46.394639+00:00 app[web.1]: Python buildpack: Detected 512 MB available memory and 8 CPU cores.2024-11-26T10:45:46.394711+00:00 app[web.1]: Python buildpack: Defaulting WEB_CONCURRENCY to 2 based on the available memory.2024-11-26T10:45:46.646680+00:00 app[web.1]: WARNING:root:No DATABASE_URL environment variable set, and so no databases setup2024-11-26T10:45:46.658628+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [2] [INFO] Starting gunicorn 23.0.02024-11-26T10:45:46.659030+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [2] [INFO] Listening at: http://[::]:45127 (2)2024-11-26T10:45:46.659078+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [2] [INFO] Using worker: gthread2024-11-26T10:45:46.661895+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [8] [INFO] Booting worker with pid: 82024-11-26T10:45:46.676834+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [9] [INFO] Booting worker with pid: 92024-11-26T10:45:47.011185+00:00 heroku[web.1]: State changed from starting to up2024-11-26T10:45:57.197212+00:00 heroku[router]: at=info method=GET path="/" host=serene-caverns-82714.herokuapp.com request_id=6993babe-09d5-442c-b6be-099d82e7f38c fwd="123.456.789.0" dyno=web.1 connect=0ms service=10ms status=200 bytes=7809 protocol=https

To generate more log messages, refresh the app’s homepage in your browser.

To stop streaming the logs, pressControl+C.

Scale the App

After deploying the sample app, it automatically runs on a single webdyno. Think of a dyno as a lightweight container that runs the command specified in theProcfile.

You can check how many dynos are running using theps command:

$ heroku psEco 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=0Scaling dynos... done, now running web at 0:Eco

Access the app again by hitting refresh on the web tab, orheroku 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=1Scaling dynos... done, now running web at 1:Eco

By default, apps use Eco dynos if you’re subscribed toEco. 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 ofeco 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 theDyno 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 arequirements.txt in the root directory is one way we recognize your Python app.

The demo app you deployed already has arequirements.txt:

django>=5.1,<5.2gunicorn>=23,<24dj-database-url>=2,<3whitenoise[brotli]>=6,<7

Therequirements.txt file lists the app’s dependencies. When you deploy an app on Heroku, the Python buildpack installs these dependencies using thepip install command.

To run the app locally, you must also install dependencies locally.

Before you do this, you must create and activate a virtual environment, also known as avenv. 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 formacOS,Windows, andLinux.

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 aMicrosoft Windows system, activate with:

.\.venv\Scripts\activate

Or if you’re on amacOS/Linux system, activate with:

$ source .venv/bin/activate

For help with setting up a virtual environment, see thePython documentation.

Finally, install the dependencies into the newly created environment:

$ pip install -r requirements.txt

Installing the dependencies also installs their dependencies. View all installed packages usingpip list:

$ pip listPackage           Version----------------- -------asgiref           3.8.1Brotli            1.1.0dj-database-url   2.3.0Django            5.1.3gunicorn          23.0.0packaging         24.2pip               24.3.1sqlparse          0.5.2typing_extensions 4.12.2whitenoise        6.8.2

After installing dependencies, you can run your app locally.

Run the App Locally

Start your application locally using theheroku local command, which is a part of the Heroku CLI.

If you’re on aMicrosoft Windows system, run this:

$ heroku local --port 5006 -f Procfile.windows

Or if you’re on amacOS/Linux system, use the defaultProcfile by running:

$ heroku local --port 5006

Running the command starts up the local web server:

[OKAY] Loaded ENV .env File as KEY=VALUE Format11:01:34 AM web.1 |  [2024-11-26 11:01:34 +0000] [12487] [INFO] Starting gunicorn 23.0.011:01:34 AM web.1 |  [2024-11-26 11:01:34 +0000] [12487] [INFO] Listening at: http://[::]:5006 (12487)11:01:34 AM web.1 |  [2024-11-26 11:01:34 +0000] [12487] [INFO] Using worker: gthread11:01:34 AM web.1 |  [2024-11-26 11:01:34 +0000] [12488] [INFO] Booting worker with pid: 12488

If you see an error when runningheroku local, check that you have installed the app’s dependencieslocally and the virtual environment is still activated.

Just like Heroku,heroku local uses theProcfile to know what command to execute.

Openhttp://localhost:5006 with your web browser. You should see your app running locally.

To stop the app from running locally, go back to your terminal window and pressCtrl+C to exit.

Push Local Changes

In this step, you propagate a local change to the application to Heroku.

Add therequests package to yourrequirements.txt file:

django>=5.1,<5.2gunicorn>=23,<24dj-database-url>=2,<3whitenoise[brotli]>=6,<7requests

Use pip to install therequests package via the updatedrequirements.txt file:

$ pip install -r requirements.txt

Modifyhello/views.py to import therequests module and the DjangoHttpResponse class at the top of the file:

import requestsfrom django.http import HttpResponse

Now modify theindex method to use the module. Try replacing the currentindex 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 aMicrosoft Windows system, run this:

$ heroku local --port 5006 -f Procfile.windows

Or if you’re on amacOS/Linux system, use the defaultProcfile by running:

$ heroku local --port 5006

Visit your application athttp://localhost:5006. If your changes worked, you will see the output of fetchinghttps://httpbin.org/status/418:

    -=[ teapot ]=-       _...._     .'  _ _ `.    | ."` ^ `". _,    \_;`"---"`|//      |       ;/      \_     _/        `"""`

If you see the errorInternal Server Error in your browser, and the errorModuleNotFoundError: No module named 'requests' in the terminal log output, check that therequests package installed successfully.

Now deploy this local change to Heroku.

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 "Updated index view"

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 papertrailCreating papertrail on ⬢ serene-caverns-82714... freeWelcome to Papertrail. Questions and ideas are welcome (technicalsupport@solarwinds.com). Happy logging!Created papertrail-convex-88929 as PAPERTRAIL_API_TOKENUse 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.

Screenshot of the console

Start a Console

You can run a command, typically scripts and applications that are part of your app, in aone-off dyno using theheroku 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 shellRunning 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 ]=-       _...._     .'  _ _ `.    | ."` ^ `". _,    \_;`"---"`|//      |       ;/      \_     _/        `"""`

Run the commandexit() to exit the Python shell and terminate the dyno.

Let’s try another example. Create another one-off dyno and run thebash 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 bashRunning bash on ⬢ serene-caverns-82714... up, run.3789 (Eco)~ $ ls -Aapp.json  .env        .github     hello    manage.py  Procfile.windows  .python-version  requirements.txt.cache    gettingstarted  .gitignore  .heroku  Procfile   .profile.d        README.md        staticfiles~ $ exitexit

Run the commandexit to exit the Bash shell and terminate the dyno.

Define Config Vars

Heroku lets you externalize configuration by storing data such as encryption keys or external resource addresses inconfig vars.

At runtime, we expose config vars as environment variables to the application.

Edithello/views.py. At the beginning of the file, add a line to import theos module:

import osfrom django.http import HttpResponse

Now modify theindex method so that it repeats an action depending on the value of theTIMES environment variable:

def index(request):    times = int(os.environ.get('TIMES', 3))    return HttpResponse('Hello! ' * times)

Theheroku local command 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 withheroku local --port 5006 and visithttp://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 usingheroku config:

$ heroku config=== serene-caverns-82714 Config VarsPAPERTRAIL_API_TOKEN: <SECRET_TOKEN>TIMES:                2

To see this change in action, deploy your changed application to Heroku.

Provision and Use a Database

Theadd-on marketplace has a large number of data stores, from Redis and MongoDB providers, to Postgres and MySQL.

Anessential-0 Postgres size costs$5 a month, prorated to the minute. At the end of this tutorial, we prompt you todelete your database to minimize costs.

To provision anessential-0 Heroku Postgres add-on, use theaddons:create command:

$ heroku addons:create heroku-postgresql:essential-0Creating heroku-postgresql:essential-0 on ⬢ serene-caverns-82714... ~$0.007/hour (max $5/month)Database should be available soonpostgresql-deep-45610 is being created in the background. The app will restart when complete...Use heroku addons:info postgresql-deep-45610 to check creation progressUse heroku addons:docs heroku-postgresql to view documentation

You can find out a more about the database provisioned for your app using theaddons 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 VarsDATABASE_URL: postgres://ub3r5i9vnl3fnm:<PASSWORD>@c5p86clmevrg5s.cluster-czrs8kj4isg7.us-east-1.rds.amazonaws.com:5432/d10gkj42hdl30i...

Heroku also provides apg command that shows a lot more information:

$ heroku pg=== DATABASE_URLPlan:                  essential-0Status:                AvailableConnections:           0/20PG Version:            16.2Created:               2024-08-09 09:55Data Size:             7.57 MB / 1 GB (0.74%) (In compliance)Tables:                0/4000 (In compliance)Fork/Follow:           UnsupportedRollback:              UnsupportedContinuous Protection: OffAdd-on:                postgresql-deep-45610

This info shows anessential-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 twopsycopg lines at the end of therequirements.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 therelease process line at the end of theProcfile file:

release: ./manage.py migrate --no-input

Thisrelease process entry enables the HerokuRelease 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, sessionsremote: Running migrations:remote:   Applying contenttypes.0001_initial... OKremote:   Applying contenttypes.0002_remove_content_type_name... OKremote:   Applying auth.0001_initial... OKremote:   Applying auth.0002_alter_permission_name_max_length... OKremote:   Applying auth.0003_alter_user_email_max_length... OKremote:   Applying auth.0004_alter_user_username_opts... OKremote:   Applying auth.0005_alter_user_last_login_null... OKremote:   Applying auth.0006_require_contenttypes_0002... OKremote:   Applying auth.0007_alter_validators_add_error_messages... OKremote:   Applying auth.0008_alter_user_username_max_length... OKremote:   Applying auth.0009_alter_user_last_name_max_length... OKremote:   Applying auth.0010_alter_group_name_max_length... OKremote:   Applying auth.0011_update_proxy_permissions... OKremote:   Applying auth.0012_alter_user_first_name_max_length... OKremote:   Applying hello.0001_initial... OKremote:   Applying sessions.0001_initial... OKremote: Waiting for release.... done.

If the build fails with asettings.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 tohttps://serene-caverns-82714.herokuapp.com/ then visithttps://serene-caverns-82714.herokuapp.com/db.

Access the/db route again to see a simple page update every time you access it:

Page View ReportAug. 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 calledGreetings that you can find inhello/models.py.

Whenever you visit the/db route of your app, the following method in thehello/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 havePostgres installed locally, use theheroku 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 aboutHeroku PostgreSQL.

You can use a similar technique to installMongoDB 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:

Remember todelete your example app, anddatabase 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. We only charge you for the resources you used.

This action removes your add-on and any data saved in the database.

$ heroku addons:destroy heroku-postgresql

This action permanently deletes your application

$ heroku apps:destroy

You can confirm that your add-on and app are gone with these commands:

$ heroku addons --all$ heroku apps --all