#!/bin/env python # ------------------------------------------------------------------------------- # This is a basic implementation of comments with a flat structure, # as described in my article: # https://blog.miguelgrinberg.com/post/implementing-user-comments-with-sqlalchemy # ------------------------------------------------------------------------------- from datetime import datetime from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class Comment(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(140)) author = db.Column(db.String(32)) timestamp = db.Column(db.DateTime(), default=datetime.utcnow, index=True) # create the database and insert a few comments db.create_all() c1 = Comment(text='hello1', author='bob') c2 = Comment(text='hello2', author='alice') c3 = Comment(text='hello3', author='bob') c4 = Comment(text='hello4', author='alice') db.session.add_all([c1, c2, c3, c4]) db.session.commit() # display the comments for comment in Comment.query.order_by(Comment.timestamp.asc()): print('{}: {}'.format(comment.author, comment.text))