0

#main

from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
 

#users

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)



    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.image_file}')" 

#posts

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"User('{self.title}', '{self.date_posted}')" 

not creating site.db in file directory

from flaskblog import app, db

app.app_context().push()

db.create_all()

  • Does this answer your question? [How can I create a table if not exist on Flask with SQLAlchemy?](https://stackoverflow.com/questions/62741661/how-can-i-create-a-table-if-not-exist-on-flask-with-sqlalchemy) – rzlvmp Nov 03 '22 at 03:11

1 Answers1

2

sqlite:///site.db is a relative path, it can sometimes be hard to work out what this is relative to.

It will probably help to be more specific and use an absolute path. An easy way to do this is by using app.root_path to construct your path. app.root_path is the path to the directory of the file containing app = Flask(__name__).

app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{app.root_path}/site.db"

or

import os

app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + os.path.join(app.root_path, "site.db")

Doing this will guarantee that the database file site.db is in the same directory as your python file that contains app = Flask(__name__)

Hanan F
  • 128
  • 1
  • 11
  • 1
    Perhaps see also [What exactly is current working directory?](https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory/66860904) – tripleee Nov 05 '22 at 11:51