1
0
Fork 0
mirror of https://github.com/shouptech/flask-tutorial.git synced 2026-02-03 07:29:42 +00:00
flask-tutorial/flaskr/db.py
2018-11-04 00:02:04 -06:00

46 lines
1.2 KiB
Python

from datetime import datetime
import click
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_db():
db.create_all()
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
def init_app(app):
db.init_app(app) # Initialize the sql alchemy database
app.cli.add_command(init_db_command)
# Model definitions
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Text, nullable=False)
password = db.Column(db.Text, nullable=False)
posts = db.relationship('Post', backref='user', lazy=True)
def __repr__(self):
return '<User %r>' % self.username
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
title = db.Column(db.Text, nullable=False)
body = db.Column(db.Text, nullable=False)
def __repr__(self):
return '<Post %r>' % self.title