Skip to content

Instantly share code, notes, and snippets.

@bradtraversy
Created August 16, 2019 16:38
Show Gist options
  • Save bradtraversy/0029d655269c8a972df726ed0ac56b88 to your computer and use it in GitHub Desktop.
Save bradtraversy/0029d655269c8a972df726ed0ac56b88 to your computer and use it in GitHub Desktop.
Python & Postgres Heroku Deployment

Python Heroku Deployment

Steps to create a postgres database and deply a Python app to Heroku

Install guinicorn locally

pipenv install gunicorn
or
pip install gunicorn

Install Heroku CLI

https://devcenter.heroku.com/articles/heroku-cli

Login via CLI

heroku login

Create app

heroku create appname

Create database

heroku addons:create heroku-postgresql:hobby-dev --app appname

Get URI

heroku config --app appname

# Add to your app

Create Procfile

touch Procfile

# Add this
web: gunicorn app:app

Create requirements.txt

pip freeze > requirements.txt

Create runtime.txt

touch runtime.txt

# Add this
python-3.7.2

Deploy with Git

git init
git add . && git commit -m 'Deploy'
heroku git:remote -a appname
git push heroku master

Add table to remote database

heroku run python
>>> from app import db
>>> db.create_all()
>>>exit()

Visit app

heroku open
@tamecalm
Copy link

tamecalm commented Aug 16, 2019

Connection refused                          Is the server running on host "localhost" (127.0.0.1) and accepting                 TCP/IP connections on port 5432?  
(Background on this error at: http://sqlalche.me/e/e3q8) 

I tried to run my app I received that after running this

heroku run python -m john

According to what I set in my Procfile

Sent from my W2 using FastHub

@tamecalm
Copy link

Creating heroku-postgresql:hobby-dev on ⬢ adsvim... ⣾
(node:22785) [DEP0066] DeprecationWarning:Creating heroku-postgresql:hobby-dev on ⬢ adsvim... free
Database has been created and is available
 ! This database is empty. If upgrading, you can transfer
 ! data from another database with pg:copy
Created postgresql-symmetrical-93636 as HEROKU_POSTGRESQL_PURPLE_URL
Use heroku addons:docs heroku-postgresql to view documentation]

I tried installing the prostgresql database see error.. Help bro

_Sent from my W2 using [FastHub](https://play.google.com/store/apps/details?id=com.fastaccess.github)_ 

Am having issues with creation of database one heroku

@sam-kaz
Copy link

sam-kaz commented Aug 17, 2019

With your first Issue, I believe you haven't changed the ENV value to "prod"

@tamecalm
Copy link

I fixed everything already, it's working fine

@tamecalm
Copy link

Thanks Sam

@amabirbd
Copy link

I fixed everything already, it's working fine

How did you solve the problem? please elaborate . I am facing the same problem.

@novusli
Copy link

novusli commented Jan 9, 2020

I fixed everything already, it's working fine

How did you solve the problem? please elaborate . I am facing the same problem.

Go to app.py, and change the ENV = 'dev' to ENV = 'prod'

@kevinwizz
Copy link

(Feedback App) PS C:\Feedback App> heroku pg:psql --app lexusapplication
--> Connecting to postgresql-opaque-41776
! The local psql command could not be located. For help installing psql, see https://devcenter.heroku.com/articles/heroku-postgresql#local-setup
(Feedback App) PS C:\Feedback App>

could anyone tell me why i cant seem to connect to my database? im on windows 10 and cant seem to get this error to go away

@namratadg911
Copy link

I am having issue with git push command. Could anyone tell me how to resolve it?

(env) C:\Users\namra\Desktop\Feedback form>git push heroku master
Enumerating objects: 1020, done.
Counting objects: 100% (1020/1020), done.
Delta compression using up to 8 threads
Compressing objects: 100% (995/995), done.
Writing objects: 100% (1020/1020), 4.68 MiB | 3.83 MiB/s, done.
Total 1020 (delta 71), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: ! Requested runtime (python 3.7.2) is not available for this stack (heroku-18).
remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to burgerfeedback.
remote:
To https://git.heroku.com/burgerfeedback.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/burgerfeedback.git'

@JosephHowardWong
Copy link

(Feedback App) PS C:\Feedback App> heroku pg:psql --app lexusapplication
--> Connecting to postgresql-opaque-41776
! The local psql command could not be located. For help installing psql, see https://devcenter.heroku.com/articles/heroku-postgresql#local-setup
(Feedback App) PS C:\Feedback App>

could anyone tell me why i cant seem to connect to my database? im on windows 10 and cant seem to get this error to go away

I have the same problem, did you figure it out?

@kbaptistap
Copy link

I am having issue with git push command. Could anyone tell me how to resolve it?

(env) C:\Users\namra\Desktop\Feedback form>git push heroku master
Enumerating objects: 1020, done.
Counting objects: 100% (1020/1020), done.
Delta compression using up to 8 threads
Compressing objects: 100% (995/995), done.
Writing objects: 100% (1020/1020), 4.68 MiB | 3.83 MiB/s, done.
Total 1020 (delta 71), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: ! Requested runtime (python 3.7.2) is not available for this stack (heroku-18).
remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to burgerfeedback.
remote:
To https://git.heroku.com/burgerfeedback.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/burgerfeedback.git'

I am having the same problem. BUT I think I know what it is yet I don't know how to fix it.
I had successfully deployed a previous version of my app. Days later, I tried to upload a newer version and got that same message. I suspect that the changes are not getting committed to git (not Heroku) as the previous version is still running and it may have something to do with the virtual environment or not committing correctly (i.e.: not committing to the right folder.)

@toteualex
Copy link

PS C:\Users\Admin\Desktop\FDapp> heroku run python
Running python on ⬢ fdapptest... up, run.8709 (Free)
Python 3.7.2 (default, Jan 29 2019, 19:41:29)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

from app import db
db.create_all()
Traceback (most recent call last):
File "", line 1, in
File "/app/.heroku/python/lib/python3.7/site-packages/flask_sqlalchemy/init.py", line 1039, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/app/.heroku/python/lib/python3.7/site-packages/flask_sqlalchemy/init.py", line 1031, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/app/.heroku/python/lib/python3.7/site-packages/flask_sqlalchemy/init.py", line 962, in get_engine
return connector.get_engine()
File "/app/.heroku/python/lib/python3.7/site-packages/flask_sqlalchemy/init.py", line 554, in get_engine
sa_url = make_url(uri)
File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/url.py", line 229, in make_url
return _parse_rfc1738_args(name_or_url)
File "/app/.heroku/python/lib/python3.7/site-packages/sqlalchemy/engine/url.py", line 291, in _parse_rfc1738_args
"Could not parse rfc1738 URL from string '%s'" % name
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string ' postgres://ayvmfbgutowbuz:ce58d7b1ddb128f308fa5c249de8a80a137e6548d8c7ec890840a0cfb3dd7086@ec2-18-214-119-135.compute-1.amazonaws.com:5432/dmrgk0fl96cst'

this is where i got stuck , any help please

@economistdev
Copy link

Hi,
When adding table I get this error below;
Please help! I cannot move on...
What should I do?

Note: I changed the ENV = 'dev' to ENV = 'prod'

from app import db
/app/.heroku/python/lib/python3.7/site-packages/flask_sqlalchemy/init.py:814: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '

Hi there, I am having the same issue and I am losing my mind lol. How did you solve this??

@shosenwales
Copy link

please can anyone help with deploying django postgreql app steps

@aprakarsa
Copy link

When I tried to create postgresql table on heroku python cli this error happened and won't let me create the table.. any help appreciated..

db.create_all()

Traceback (most recent call last):
File "", line 1, in
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1094, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1086, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1017, in get_engine
return connector.get_engine()
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 594, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options)
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1027, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts)
File "", line 2, in create_engine
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/deprecations.py", line 298, in warned
return fn(*args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 522, in create_engine
entrypoint = u._get_entrypoint()
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/url.py", line 653, in _get_entrypoint
cls = registry.load(name)
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 341, in load
raise exc.NoSuchModuleError(
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres

@bek91
Copy link

bek91 commented Apr 8, 2021

When I tried to create postgresql table on heroku python cli this error happened and won't let me create the table.. any help appreciated..

db.create_all()

Traceback (most recent call last):
File "", line 1, in
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1094, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1086, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1017, in get_engine
return connector.get_engine()
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 594, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options)
File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/init.py", line 1027, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts)
File "", line 2, in create_engine
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/deprecations.py", line 298, in warned
return fn(*args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 522, in create_engine
entrypoint = u._get_entrypoint()
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/engine/url.py", line 653, in _get_entrypoint
cls = registry.load(name)
File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 341, in load
raise exc.NoSuchModuleError(
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres

SQLAlchemy has stopped supporting 'postgres', and now has to be 'postgresql'.

To work around it, change postgres to postgresql In your app.config['SQLALCHEMY_DATABASE_URI'] = ''

@guimatheus92
Copy link

I have a SQLITE db file already with data, and I'd like to deploy to Heroku. How can I do?
When I tried to create postgresql table on heroku python cli this error happened and won't let me create the table:

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

My app repository is in: https://github.com/guimatheus92/Game-Recommendation-System

My app file is in init.py:

# init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager 
# For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import re

# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()

def create_app():
    app = Flask(__name__)

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False    
    app.config['SECRET_KEY'] = environ.get('SECRET_KEY')
    app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DATABASE_URL') or 'sqlite:///Games.db'
        
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from models import User

    @login_manager.user_loader    
    def load_user(user_id):
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))

    # blueprint for auth routes in our app
    from auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    # blueprint for non-auth parts of app
    from games import games as main_blueprint
    app.register_blueprint(main_blueprint)

    # blueprint for non-auth parts of app
    from ml_utils import ml_utils as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

@JigsAwe
Copy link

JigsAwe commented Apr 17, 2021

image
im at this part already, im having this problem, i appreciate any sort of help I can get.

@Rishavsinha19981
Copy link

image

I AM ABLE TO SEE THIS ERROR AFTER DEPLOYING IN HEROKU AND CREATING DATABASE ALSO BY CREATE_ALL() but then also this is showing up can ANY1 HELP ME PLZZZ

@esha123802
Copy link

image
im at this part already, im having this problem, i appreciate any sort of help I can get.

Im having the same error, did you figure it out? I have added the bin path to env also

@srinumadhavv
Copy link

Everything is running fine but unable to access the database , it says table not found

@lena-A-Al
Copy link

heroku open
is not working?

@Olney1
Copy link

Olney1 commented Sep 2, 2022

Hey Brad, could you add the CLI commands for viewing the database tables?

@Yemsquare
Copy link

Hey, having issue with creating the table with PostgreSQL

@kelderanyi
Copy link

heroku open is not working?

use this instead "heroku open --app appname

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment