I am learning how to create a simple web application using Flask and I am following this course (https://www.youtube.com/watch?v=Qr4QMBUPxWo&t=2499s&ab_channel=freeCodeCamp.org)
Right now, I am trying to create a database and following the steps shown in the video, I am not able to see the .db file in my folder.
I was not able to create the database as shown in the video but I created it by going into the python terminal and using the following commands:
$ from market import app, db
$ app.app_context().push()
$ db.create_all()
The code I have right now is the following:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db'
db = SQLAlchemy(app)
class Item(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(length=30), nullable=False, unique=True)
price = db.Column(db.Integer(), nullable=False)
barcode = db.Column(db.String(length=12), nullable=False, unique=True)
description = db.Column(db.String(length=1024), nullable=False, unique=True)
def __repr__(self):
return f'Item {self.name}'
@app.route('/')
@app.route('/home')
def home_page():
return render_template('home.html')
@app.route('/about/<username>')
def about_page(username):
return f'<h1>This is the about page of {username}</h1>'
@app.route('/market')
def market_page():
items = Item.query.all()
return render_template('market.html', items=items)
This is because the path for sqlite file is absolute. Try to build it accordingly:
from pathlib import Path
...
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{Path(__file__).parent / 'market.db'}"
And after calling the command db.create_all()
, we will see that db is created in the directory with the python file.
$ ls *.db
market.db
And we could validate that it is the exact schema that was declared using sqlite3
cli command:
$ sqlite3 market.db
SQLite version 3.37.0 2021-12-09 01:34:53
Enter ".help" for usage hints.
sqlite> .tables
item
sqlite> .schema item
CREATE TABLE item (
id INTEGER NOT NULL,
name VARCHAR(30) NOT NULL,
price INTEGER NOT NULL,
barcode VARCHAR(12) NOT NULL,
description VARCHAR(1024) NOT NULL,
PRIMARY KEY (id),
UNIQUE (name),
UNIQUE (barcode),
UNIQUE (description)
);