# -*- coding:utf-8 -*- from flask import Flask from flask_debugtoolbar import DebugToolbarExtension from flask.ext.compress import Compress app = Flask(__name__) app.config.from_envvar('APP_CONFIG_FILE') Compress(app) toolbar = DebugToolbarExtension(app) import src.views from .utils import assets if __name__ == '__main__': app.run()
def create_app(config_path): # setup flask app = Flask('jazzband') @app.errorhandler(404) def page_not_found(e): return render_template('error.html'), 404 @app.errorhandler(403) def forbidden(error): return render_template('forbidden.html'), 403 @app.errorhandler(500) def error(error): return render_template('error.html'), 500 @app.route('/favicon.ico') def favicon(): filename = 'favicon.ico' cache_timeout = app.get_send_file_max_age(filename) return send_from_directory(os.path.join(app.static_folder, 'favicons'), filename, mimetype='image/vnd.microsoft.icon', cache_timeout=cache_timeout) # load decoupled config variables app.config.from_object(config_path) from .models import db, User, Project, EmailAddress db.init_app(app) from flask_migrate import Migrate Migrate(app, db) from .admin import admin, JazzbandModelView admin.init_app(app) admin.add_view(JazzbandModelView(User, db.session)) admin.add_view(JazzbandModelView(Project, db.session)) admin.add_view(JazzbandModelView(EmailAddress, db.session)) if 'OPBEAT_SECRET_TOKEN' in os.environ: from opbeat.contrib.flask import Opbeat Opbeat(app, logging=True) if not app.debug: from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) from whitenoise import WhiteNoise app.wsgi_app = WhiteNoise( app.wsgi_app, root=app.static_folder, prefix=app.static_url_path, ) # setup github-flask from .github import github github.init_app(app) from .hooks import hooks hooks.init_app(app) # setup webassets from .assets import assets assets.init_app(app) # setup session store from flask.ext.session import Session Session(app) from flask.ext.compress import Compress Compress(app) from .content import about_pages, news_pages, content about_pages.init_app(app) news_pages.init_app(app) app.register_blueprint(content) from .account import account, login_manager app.register_blueprint(account) login_manager.init_app(app) from .members import members app.register_blueprint(members) from .projects import projects app.register_blueprint(projects) @app.context_processor def app_context_processor(): return { 'about': about_pages, 'news': news_pages, 'User': User, 'Project': Project, } @app.after_request def add_vary_header(response): response.vary.add('Cookie') response.headers['Jazzband'] = "We're all part of the band" return response return app
import os import sys from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy APP_DIR = os.path.abspath(os.path.dirname(__file__)) from main.configuration import config from sqlalchemy import create_engine, MetaData, Table from flask.ext.compress import Compress db = SQLAlchemy() compress = Compress() #renvoie une instance de app l appli Flask def create_app(): app = Flask(__name__, template_folder=APP_DIR) app.debug = True from main.atlasRoutes import main as main_blueprint app.register_blueprint(main_blueprint) from main.atlasAPI import api app.register_blueprint(api, url_prefix='/api') compress.init_app(app)
def setUp(self): self.app = Flask(__name__) self.app.testing = True Compress(self.app)
security = Security(app, user_datastore, register_form=ExtendedRegisterForm, login_form=ExtendedLoginForm) """Auto add role and creation time to new users""" @user_registered.connect_via(app) def user_registered_sighandler(app, user, confirm_token): default_role = user_datastore.find_role('user') user_datastore.add_role_to_user(user, default_role) user.created_at = datetime.utcnow() db.session.commit() """Add various extensions""" mail = Mail(app) assets = Environment(app) compress = Compress(app) """If we are in prod, don't autobuild""" assets.auto_build = app.config['ASSETS_AUTO_BUILD'] assets.manifest = 'file' """Configure blueprints in views.""" for blueprint in DEFAULT_BLUEPRINTS: app.register_blueprint(blueprint) def configure_template_filters(app): @app.template_filter() def time_ago(value): return pretty_date(value)
def test_delayed_init(self): compress = Compress() compress.init_app(self.app)
def test_constructor_init(self): Compress(self.app)
def create_app(config_mode=None, config_file=None): """ Creates the Flask application Kwargs: config_mode (str): The configuration mode. Must be a `class` in `config.py`. One of ('Production', 'Development', 'Test', 'Docker') config_file (str): The configuration file. Returns: (obj): Flask application Examples: >>> create_app('Test') <Flask 'app'> """ app = Flask(__name__) app.register_blueprint(blueprint) mgr = APIManager(app, flask_sqlalchemy_db=db) cache_config = {} if config_mode: app.config.from_object(getattr(config, config_mode)) elif config_file: app.config.from_pyfile(config_file) else: app.config.from_envvar('APP_SETTINGS', silent=True) memcached_servers = getenv('MEMCACHIER_SERVERS', getenv('MEMCACHE_SERVERS')) if app.config['PROD'] and app.config['MEMCACHE']: cache_config['CACHE_TYPE'] = 'spreadsaslmemcachedcache' cache_config['CACHE_MEMCACHED_SERVERS'] = [memcached_servers] cache_config['CACHE_MEMCACHED_USERNAME'] = getenv( 'MEMCACHIER_USERNAME') cache_config['CACHE_MEMCACHED_PASSWORD'] = getenv( 'MEMCACHIER_PASSWORD') elif app.config['MEMCACHE']: cache_config['CACHE_TYPE'] = 'memcached' cache_config['CACHE_MEMCACHED_SERVERS'] = [memcached_servers] else: cache_config['CACHE_TYPE'] = 'simple' cache.init_app(app, config=cache_config) db.init_app(app) CORS(app) Compress(app) @app.route('/') def home(): return 'Welcome to the HDX Age API!' kwargs = { 'methods': app.config['API_METHODS'], 'validation_exceptions': API_EXCEPTIONS, 'allow_functions': app.config['API_ALLOW_FUNCTIONS'], 'allow_patch_many': app.config['API_ALLOW_PATCH_MANY'], 'max_results_per_page': app.config['API_MAX_RESULTS_PER_PAGE'], 'url_prefix': app.config['API_URL_PREFIX'] } # Create API endpoints from `models.py`. Each model is available at # the endpoint `/<tablename>`. create_api = partial(mgr.create_api, **kwargs) with app.app_context(): map(create_api, _get_tables()) return app
def make_app(): cors = CORS(origins=[ 'https://app.communityshare.us:443', # production app 'http://communityshare.localhost:5000', # local dev angular app 'http://communityshare.localhost:8000', # local dev elm app 'https://dmsnell.github.io/cs-elm/', # live elm app ]) compress = Compress() webpack = Webpack() app = Flask(__name__, template_folder='../static/') app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_CONNECTION app.config['WEBPACK_ASSETS_URL'] = config.WEBPACK_ASSETS_URL app.config['WEBPACK_MANIFEST_PATH'] = config.WEBPACK_MANIFEST_PATH cors.init_app(app) compress.init_app(app) webpack.init_app(app) if config.SSL != 'NO_SSL': flask_sslify.SSLify(app) app.wsgi_app = ReverseProxied(app.wsgi_app) register_user_routes(app) register_search_routes(app) register_conversation_routes(app) register_share_routes(app) register_survey_routes(app) register_email_routes(app) register_statistics_routes(app) community_share.api.register_routes(app) @app.teardown_appcontext def close_db_connection(exception): store.session.remove() @app.errorhandler(BadRequest) def handle_bad_request(error): return str(error), HTTPStatus.BAD_REQUEST @app.route('/static/build/<path:filename>') def build_static(filename): return send_from_directory( app.root_path + '/../static/build/', filename, cache_timeout=YEAR_IN_SECONDS, ) @app.route('/static/js/<path:filename>') def js_static(filename): return send_from_directory(app.root_path + '/../static/js/', filename) @app.route('/static/fonts/<path:filename>') def fonts_static(filename): return send_from_directory(app.root_path + '/../static/fonts/', filename) @app.route('/static/css/<path:filename>') def css_static(filename): return send_from_directory(app.root_path + '/../static/css/', filename) @app.route('/static/templates/footer.html') def footer_template(): return render_template('templates/footer.html', config=config) @app.route('/static/templates/<path:filename>') def templates_static(filename): return send_from_directory(app.root_path + '/../static/templates/', filename) @app.route('/') def index(): logger.debug('rendering index') return render_template('index.html', config=config) return app
'REDIS_URL') or 'redis://localhost:6379' CELERY_REDIS_MAX_CONNECTIONS = 5 # Cache CACHE_TYPE = 'redis' CACHE_REDIS_URL = os.environ.get('REDIS_URL') or 'redis://localhost:6379' # Raygun RAYGUN_APIKEY = os.environ.get('RAYGUN_APIKEY') or 'debug' GEOCODE_APIKEY = os.environ.get('GEOCODE_APIKEY') app = Flask(__name__) app.config.from_object(__name__ + '.ConfigClass') Compress(app) # Initialize Flask-Compress db = SQLAlchemy(app) # Initialize Flask-SQLAlchemy mail = Mail(app) # Initialize Flask-Mail if not app.debug: flask_raygun.Provider(app, app.config['RAYGUN_APIKEY']).attach() celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) cache = Cache(app, config={ 'CACHE_TYPE': app.config['CACHE_TYPE'], 'CACHE_REDIS_URL': app.config['CACHE_REDIS_URL'], })