Rahul Shrivastava
Rahul Shrivastava

Reputation: 1411

Peewee and postgres on heroku, not able to create table

I tried without database my app working great but with peewee and postgres, Its not able to create table at all.

my app

I tried different methods posted online but its not working, anyone if you have used peewee on heroku please help.

My model.py

if os.environ.get('DATABASE_URL'):
    DATABASE_URL = os.environ.get('DATABASE_URL')
    db = urlparse(DATABASE_URL)
    user = db.username
    password = db.password
    path = db.path[1:]
    host = db.hostname
    port = db.port
    database = PostgresqlDatabase(path, user=user, password=password, host=host, port=port)
else:
    database = PostgresqlDatabase('heroku')


class BaseModel(Model):
    class Meta:
        database = database


class User(BaseModel):
    name = CharField()
    email = CharField(null=False, unique=True)

After moving create table from if statement to welcome function table is created.

@app.route('/')
def welcome():
    call('printenv')
    a = 'Default'
    b = 'Default'
    if os.environ.get('DATABASE_URL'):
        a = os.environ.get('DATABASE_URL')
    if os.environ.get('HEROKU'):
        b = os.environ.get('HEROKU')
    create_model_tables([Users], fail_silently=True)
    Users.insert(name='John', email='Doe').execute()
    return render_template('index.html', a=a, b=b)


if __name__ == '__main__':
    app.run(port=5000, debug=True)

Upvotes: 1

Views: 545

Answers (2)

Rahul Shrivastava
Rahul Shrivastava

Reputation: 1411

from playhouse.db_url import connect
import settings

local_url = 'postgresql://{}:{}@localhost:5432/{}'.format(settings.DB_USER, settings.DB_PASS, settings.DB_NAME)

database = connect(os.environ.get('DATABASE_URL') or local_url)


class BaseModel(Model):
    class Meta:
        database = database

Use this way, its easy and there is very few chance of getting it wrong.

And you must create table before if __name__ == '__main__:, this statement, because on heroku you give settings such that, anything under that wont work.

Like mine uswgi.ini

[uwsgi]
http-socket = :$(PORT)
master = true
die-on-term = true
module = app:app
memory-report = true

module = app:app means run the app from app.py not run app.py

Upvotes: 0

coleifer
coleifer

Reputation: 26235

"user" is a reserved table -- try:

class User(Model):
    ...
    class Meta:
        db_table = 'users'

Upvotes: 1

Related Questions