Issue
I'm building a website using Flask, and I'm having a problem creating the database file. Is there a way to solve this problem without changing the structure of the project as much as possible?
Here is my project structure:
├── db_model
│ └── models.py
├── guide_view
│ └── guide.py
├── static
├── templates
└── app.py
models.py
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy()
class User(db.Model):
...
guide.py
from flask import Blueprint, render_template, flash, request, redirect, url_for, jsonify
from flask_login import current_user, login_required, login_user, logout_user
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from db_model.models import db
from db_model.models import User
guide_view = Blueprint('guide_view', __name__, static_folder="static", template_folder="templates")
@guide_view.route('/')
@guide_view.route('/main')
def main():
return render_template("index.html")
app.py
from flask import Flask
from flask_login import LoginManager
from flask_cors import CORS
from guide_view import guide
from flask_sqlalchemy import SQLAlchemy
from db_model.models import db
from db_model.models import User
import os
from os import path
app = Flask(__name__, static_url_path='/static')
CORS(app)
app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY', 'guide')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///instance/database.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
def create_db(app):
with app.app_context():
db.create_all()
print("Database tables created successfully.")
login_manager = LoginManager()
login_manager.login_view = 'guide_view.login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(id):
return User.query.get(id)
app.register_blueprint(guide.guide_view, url_prefix="")
if __name__ == '__main__':
if not path.exists('database.db'):
create_db(app)
app.run(host='0.0.0.0', port='1114', debug=True)
I check python version(3.12.0) and Flask version(3.0.0). I also checked the terminal, but there were no logs about the database. I'm not sure what the problem is.
If you have any other problems, please let me know.
Solution
In your models.py
, you create db = SQLAlchemy()
connection but in your app.py
you also create anothers. It have two db so The db create is db at app.py, not db in your model.
I suggest add a extension.py
to store all 3rd app and you 'll import to app.py
Ex:
Stucture:
├── db_model
│ └── models.py
├── guide_view
│ └── guide.py
├── static
├── templates
└── app.py
└── extension.py
extension.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
models.py
from extension import db # use db from extension
class User(db.Model):
user_id = db.Column(db.String(10), primary_key=True)
app.py
from flask import Flask
from flask_login import LoginManager
from flask_cors import CORS
from guide_view import guide
from extension import db
from db_model.models import User
import os
from os import path
app = Flask(__name__, static_url_path='/static')
CORS(app)
app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY', 'guide')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///database.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
def create_db(app):
db.init_app(app) # use db from extension
with app.app_context():
db.create_all()
print("Database tables created successfully.")
login_manager = LoginManager()
login_manager.login_view = 'guide_view.login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(id):
return User.query.get(id)
app.register_blueprint(guide.guide_view, url_prefix="")
if __name__ == '__main__':
if not path.exists('database.db'):
create_db(app)
app.run(host='0.0.0.0', port='1114', debug=True)
Answered By - TanThien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.