1

I am trying to create a new database with two tables using the code provided in Lecture 4 of CS50's Web Programming with Python and JavaScript course. Following is the code for the file create.py which creates a database with two tables:

import os

from flask import Flask, render_template, request
from models import *

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://shammun:my_password@localhost:5432/new_test3.db' 
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# db = SQLAlchemy()
db.init_app(app)


def main():
    db.create_all()

if __name__ == "__main__":
    with app.app_context():
        main()

This file create.py imports model.py which generates two tables, the code of which is given below:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Flight(db.Model):
    __tablename__ = "flights"
    id = db.Column(db.Integer, primary_key=True)
    origin = db.Column(db.String, nullable=False)
    destination = db.Column(db.String, nullable=False)
    duration = db.Column(db.Integer, nullable=False)


class Passenger(db.Model):
    __tablename__ = "passengers"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    flight_id = db.Column(db.Integer, db.ForeignKey("flights.id"), nullable=False)

Now, in the terminal when I run the file create.py, the database is not created and I get the following error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: database "new_test3.db" does not exist

I will much appreciate if someone can help me in figuring out what went wrong.

shammun
  • 177
  • 2
  • 3
  • 14
  • You have to create the DB first in PostgreSQL. Judging by the choice of name you come from an SQLite background. PostgreSQL does not use a single DB file. See https://stackoverflow.com/questions/5735370/postgresql-creating-database, and https://stackoverflow.com/questions/16906932/create-database-simplest-way-possible-using-psql-commands for example. – Ilja Everilä Apr 10 '20 at 09:31
  • Thanks for your suggestion. According to your suggestion, I created a database named **new_test3** first and then ran the file and still get the error **sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: database "new_test3.db" does not exist**. But in psql, when I look at the list of database using **\l**, I see that it is being created. – shammun Apr 14 '20 at 17:38

0 Answers0