Skip to content

Instantly share code, notes, and snippets.

@marmeladze
Created August 17, 2020 15:51
Show Gist options
  • Select an option

  • Save marmeladze/fb9f6adae19591aa83adddfa24d18076 to your computer and use it in GitHub Desktop.

Select an option

Save marmeladze/fb9f6adae19591aa83adddfa24d18076 to your computer and use it in GitHub Desktop.
posts-comments
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
title = db.Column(db.String(20), unique=True, nullable=False)
text = db.Column(db.String(140), unique=True, nullable=False)
likes = db.Column(db.Integer)
def __repr__(self):
return '<Post %r>' % self.title
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(50), unique=True, nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
post = db.relationship('Post', backref=db.backref('comments', lazy=True))
def __repr__(self):
return '<Comment %r>' % self.text
@app.route('/posts', methods=['POST', 'GET'])
def posts():
posts = Post.query.all()
return render_template('index.html', posts=posts)
@app.route('/posts/<id:int>')
def post():
posts = Post.query.get(id)
return render_template('index.html', posts=posts)
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment