Skip to content

Instantly share code, notes, and snippets.

@mosdevly
Last active September 24, 2021 15:54
Show Gist options
  • Save mosdevly/d338cade36e3fd8d1ec2567e1d83e543 to your computer and use it in GitHub Desktop.
Save mosdevly/d338cade36e3fd8d1ec2567e1d83e543 to your computer and use it in GitHub Desktop.
Flask Snippets -- Common architecture patterns when building Flask applications. For learners.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def connect_to_db(app):
"""Helper function to configure the database with the flask app."""
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///blog'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.app = app
db.init_app(app)
def Article(db.Model):
__tablename__ = 'articles'
title = db.Column(db.String)
content = db.Column(db.Text)
def __repr__(self):
return f"<Article {self.id} | {self.title}>"
def save(self):
"""A method to make saving articles simpler."""
db.session.add(self)
db.session.commit()
if __name__ == '__main__':
from server import app
connect_to_db(app)
db.create_all()
print('Connected to database.')
from flask_debugtoolbar import DebugToolbarExtension
from views import app
if __name__ == '__main__':
app.secret_key = 'secretzzzzzz'
app.debug = True
DebugToolbarExtension(app)
app.run()
from flask import Flask, render_template, redirect
from models import db, Article
app = Flask(__name__)
@app.route('/')
def index():
"""
This is a view pattern. Note:
* Route decorator on line 5
* View function (this function)
"""
# Try to replace your print() statements with logs instead anywhere that you're testing the live server.
app.logger.info("Home page loaded.")
return render_template('index.html')
# RESTful routes
@app.route('/articles')
def articles():
"""
Returns all articles.
"""
articles = Article.query.all()
return render_template('articles/list.html', articles=articles)
@app.route('/articles', methods=['POST'])
def article_new():
"""
Creates a new article and redirects user to it.
"""
article = Article(title=request.form.get('title'), content=request.form.get('content'))
db.session.add(article)
db.session.commit(article)
return redirect(f'/articles/{article.id}')
@app.route('/articles/<int:article_id>')
def article_detail(article_id):
"""
Returns a specific article.
The route variable `article_id` must be passed to the view function as an argument.
Their names are arbitrary, but they must match.
"""
article = Article.query.get(article_id)
return render_template('articles/detail.html', article=article)
@app.route('/articles/<int:article_id>/edit')
def article_edit(article_id):
"""
Renders the article's edit page.
The full article content is returned so that the user can view the old and make updates to it.
"""
article = Article.query.get(article_id)
return render_template('articles/edit.hmtl', article=article)
@app.route('/articles/<int:article_id>', methods=['POST'])
def article_update(article_id):
"""
Updates the current article and redirects the user to it.
"""
article = Article.query.get(article_id)
new_title = request.form.get('title')
new_content = request.form.get('content')
if article.title != new_title:
article.title = new_title
if article.content != new_content:
article.content = new_content
db.session.add(article)
db.session.commit()
return redirect(f'/articles/{article_id}')
@app.route('/articles/<int:article_id>/delete')
def article_delete(article_id):
article = Article.query.get(article_id)
db.session.delete(article)
db.session.commit()
return redirect('/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment