Open dreed47 opened 5 years ago
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
import os
app = Flask(__name__)
# Configure the SQLite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize SQLAlchemy and Flask-Admin
db = SQLAlchemy(app)
admin = Admin(app, name='Sample App', template_mode='bootstrap4')
# Define models
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f'<User {self.name}>'
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref=db.backref('posts', lazy=True))
def __repr__(self):
return f'<Post {self.title}>'
# Add views to Flask-Admin
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Post, db.session))
# Ensure database is created on first use
@app.before_first_request
def create_tables():
if not os.path.exists('sample_db.sqlite'):
print("Creating the database and tables...")
db.create_all()
# Routes
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
sqla example fails to create new sample_db on first use.