Skip to content

Instantly share code, notes, and snippets.

@zaccrites
Last active February 16, 2023 04:57
Show Gist options
  • Save zaccrites/c5bcf96ed90907d92042 to your computer and use it in GitHub Desktop.
Save zaccrites/c5bcf96ed90907d92042 to your computer and use it in GitHub Desktop.
Flask Application Factory
import jinja2
from flask import Flask, render_template, request, redirect, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from . import formatting
from .config import get_config
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
config = get_config(config_name)
app.config.from_object(config)
config.init_app(app)
db.init_app(app)
register_pre_request_handlers(app)
register_post_request_handlers(app)
set_error_handlers(app)
setup_logging(app)
register_blueprints(app)
app.jinja_env.undefined = jinja2.StrictUndefined
setup_jinja_filters(app)
return app
def register_blueprints(app):
from . import general
from . import auth
app.register_blueprint(general.mod)
app.register_blueprint(auth.mod)
def set_error_handlers(app):
@app.errorhandler(404)
def not_found(error):
return render_template('errors/not_found.html'), 404
@app.errorhandler(403)
def forbidden(error):
return render_template('errors/forbidden.html'), 403
def register_pre_request_handlers(app):
pass
def register_post_request_handlers(app):
pass
def setup_jinja_filters(app):
app.jinja_env.filters['format_datetime'] = formatting.format_datetime
def setup_logging(app):
if not app.debug:
import logging
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler('jmickey-blog.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
import pytest
from jmickey_blog.app import create_app, db
# import relevant models here
@pytest.fixture
def test_app():
app = create_app('test')
with app.app_context():
db.drop_all()
db.create_all()
return app
def test_some_thing():
pass
def test_some_other_thing():
pass
#!/usr/bin/env python3
import sys
from jmickey_blog.app import create_app
if len(sys.argv) > 1:
config_name = sys.argv[1]
else:
config_name = 'development'
app = create_app(config_name)
def main():
app.run()
if __name__ == '__main__':
main()
@Goorzhel
Copy link

Goorzhel commented Apr 4, 2018

Can I bug you to paste config.py as well? I'm curious about what .config.get_config() looks like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment