def _init_app(self): if not hasattr(self.app, 'extensions'): self.app.extensions = dict() plumbums = self.app.extensions.get('plumbum', []) for p in plumbums: if p.endpoint == self.endpoint: raise Exception('Cannot have two Plumbum() instance with same ' 'endpoint name.') if p.url == self.url and p.subdomain == self.subdomain: raise Exception('Cannot assign two Plumbum() instances with ' 'same URL and subdomain to the same ' 'application.') plumbums.append(self) self.app.extensions['plumbum'] = plumbums # Initialize Webpack plugin # FIXME: Hardcoded, move to appropiate place self.app.config.update({ 'WEBPACK_MANIFEST_PATH': '{}/static/webpack/manifest.json'.format(CURRENT_PATH), }) webpack = Webpack() webpack.init_app(self.app) if self.app.debug: self._attach_show_urls_view()
def create_app(): app = Flask(__name__, static_folder='build/public/', static_url_path='/assets') app.config['SECRET_KEY'] = 'sekrit!' app.config['WEBPACK_MANIFEST_PATH'] = os.path.abspath( './brigade/build/manifest.json') webpack = Webpack() webpack.init_app(app) if 'SERVER_NAME' in os.environ: app.config['SERVER_NAME'] = os.environ['SERVER_NAME'] if 'SITEMAP_URL_SCHEME' in os.environ: app.config['SITEMAP_URL_SCHEME'] = os.environ['SITEMAP_URL_SCHEME'] app.register_blueprint(brigade) app.register_blueprint(filters) app.register_blueprint(sitemap_blueprint) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 return app
def test_nested_asset_map_missing_public_path(): path = os.path.abspath( os.path.join(__dirname, "nested_asset_map_missing_public_path.json")) app = Flask("test_app") app.config["WEBPACK_MANIFEST_PATH"] = path webpack = Webpack() webpack.init_app(app) with app.app_context(): rendered = render_template_string('{{ asset_url_for("temp.js") }}') assert rendered == "//localhost:8080/temp.js"
def make_app(): webpack = Webpack() app = Flask(__name__, template_folder='static/') app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_CONNECTION app.config['WEBPACK_MANIFEST_PATH'] = '../static/manifest.json' webpack.init_app(app) if config.SSL != 'NO_SSL': flask_sslify.SSLify(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) @app.teardown_appcontext def close_db_connection(exception): store.session.remove() @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
def create_app(): # __version__ = pkg_resources.require("atmi")[0].version flask_app = Flask(__name__) flask_app.debug = (('FLASK_ENV' in environ) and (environ['FLASK_ENV'] == 'development')) webpack = Webpack() # flask_app.config.from_object(config) flask_app.config["WEBPACK_MANIFEST_PATH"] = path.join( here, "manifest.json") webpack.init_app(flask_app) setup_route_map(flask_app, here) setup_log(flask_app) flask_app.url_map.strict_slashes = False return flask_app
def test_flat_asset_map_renamed_public_path(): path = os.path.abspath( os.path.join(__dirname, "flat_asset_map_renamed_public_path.json")) app = Flask("test_app") app.config["WEBPACK_MANIFEST_PATH"] = path webpack = Webpack() webpack.init_app(app) with app.app_context(): r1 = render_template_string('{{ asset_url_for("foo") }}') r2 = render_template_string('{{ asset_url_for("bar.js") }}') e1 = "//localhost:8080/foo.h4sh3d.js" e2 = "//localhost:8080/completely-different.hashed.js" assert r1 == e1 assert r2 == e2
def register_extensions(app): from flask_webpack import Webpack webpack = Webpack() webpack.init_app(app) from security import authenticate, identity, jwt_error_handler, jwt_payload_callback from flask_jwt import JWT jwt = JWT(app, authentication_handler=authenticate, identity_handler=identity) jwt.jwt_error_callback = jwt_error_handler jwt.jwt_payload_callback = jwt_payload_callback from models import db db.init_app(app) print "app.debug %s" % app.debug print "app.config['SECRET_KEY'] %s" % app.config['SECRET_KEY']
def test_asset_url_for(): app = Flask("test_app") # app.config['WEBPACK_MANIFEST_PATH'] = '' app.config["WEBPACK_LOG_LEVEL"] = "INFO" Webpack(app, assets_url="/", foo="foo.h4sh3d.js") with app.app_context(): rendered = render_template_string('{{ asset_url_for("foo") }}') assert rendered == "/foo.h4sh3d.js"
def test_js_tag_basic(): app = Flask("test_app") # app.config['WEBPACK_MANIFEST_PATH'] = '' app.config["WEBPACK_LOG_LEVEL"] = "INFO" Webpack(app, assets_url="/", foo="foo.h4sh3d.js") with app.app_context(): rendered = render_template_string('{{ javascript_tag("foo") }}') assert rendered == '<script src="/foo.h4sh3d.js" ></script>'
def test_js_tag_multiple(): app = Flask("test_app") # app.config['WEBPACK_MANIFEST_PATH'] = '' app.config["WEBPACK_LOG_LEVEL"] = "INFO" Webpack(app, assets_url="/", foo="foo.h4sh3d.js", bar="bar.11a6e2.js") with app.app_context(): rendered = render_template_string('{{ javascript_tag("foo", "bar") }}') expected = ('<script src="/foo.h4sh3d.js" ></script>\n' '<script src="/bar.11a6e2.js" ></script>') check_attrib(rendered, expected)
def create_app(config=None): """ Configure app object blueprints and global variables. """ app = configure_app(Flask(__name__), config) # setup webpack for assets webpack = Webpack() webpack.init_app(app) # setup flask-login login_manager.init_app(app) login_manager.view = 'login.user_login' # setup flask blueprints configure_blueprints(app) return app
def test_warn_missing_js_bundle(): app = Flask("test_app") # app.config['WEBPACK_MANIFEST_PATH'] = '' app.config["WEBPACK_LOG_LEVEL"] = "INFO" Webpack(app, assets_url="/", bar="bar.11a6e2.js") with app.app_context(): rendered = render_template_string( '{{ javascript_tag("foo", module=True) }}') expected = ( '<script>console.warn("[flask-webpack] missing script foo")</script>') assert rendered == expected
def test_flat_asset_map(): path = os.path.abspath( os.path.join(__dirname, "complete_flat_asset_map.json")) app = Flask("test_app") app.config["WEBPACK_MANIFEST_PATH"] = path Webpack(app) with app.app_context(): r1 = render_template_string("{{ javascript_tag('foo') }}") r2 = render_template_string("{{ javascript_tag('bar.js') }}") e1 = '<script src="correct/foo.h4sh3d.js" ></script>' e2 = '<script src="correct/completely-different.hashed.js" ></script>' assert r1 == e1 assert r2 == e2
def create_app(): app = Flask(__name__, static_folder='build/public/', static_url_path='/assets') app.config['SECRET_KEY'] = 'sekrit!' app.config['WEBPACK_MANIFEST_PATH'] = detect_webpack_manifest_path('./brigade/build/manifest.json') webpack = Webpack() webpack.init_app(app) if 'SERVER_NAME' in os.environ: app.config['SERVER_NAME'] = os.environ['SERVER_NAME'] if 'SITEMAP_URL_SCHEME' in os.environ: app.config['SITEMAP_URL_SCHEME'] = os.environ['SITEMAP_URL_SCHEME'] app.register_blueprint(brigade) app.register_blueprint(filters) app.register_blueprint(sitemap_blueprint) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 return app
def _create_app(self): app = Flask(__name__) self._load_config(app) self._register_path(app) # use template pug(jade) app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') # use webpack webpack = Webpack() webpack.init_app(app) # routing register_routes(app) # init db init_db(app) toolbar = DebugToolbarExtension() toolbar.init_app(app) return app
def test_nested_asset_map(): path = os.path.abspath( os.path.join(__dirname, "test_app_wp1", "build", "manifest.json")) app = Flask("test_app") app.config["WEBPACK_MANIFEST_PATH"] = path Webpack(app) with app.app_context(): r1 = render_template_string( '{{ asset_url_for("images/dog/no-idea.jpg") }}') r2 = render_template_string('{{ asset_url_for("app_js.js") }}') e1 = ("http://localhost:2992/assets/images/dog/" "no-idea.b9252d5fd8f39ce3523d303144338d7b.jpg") e2 = "http://localhost:2992/assets/app_js.8b7c0de88caa3f366b53.js" assert r1 == e1 assert r2 == e2
def test_style_preprocessor(ext): app = Flask("test_app") # app.config['WEBPACK_MANIFEST_PATH'] = '' app.config["WEBPACK_LOG_LEVEL"] = "INFO" Webpack(app, assets_url="/", **{"foo{}".format(ext): "foo.h4sh3d.css"}) with app.app_context(): rendered = render_template_string( "{{ stylesheet_tag(" '"foo", crossorigin="anonymous", type="text/css"' ") }}") expected = ('<link rel="stylesheet"' ' href="/foo.h4sh3d.css"' ' crossorigin="anonymous"' ' type="text/css">') check_attrib(rendered, expected)
def create_app(package_name=__name__, static_folder='../front/static', template_folder='../front/templates', **config_overrides): app = Flask(package_name, static_url_path='/assets', static_folder=static_folder, template_folder=template_folder) app.config.from_object(config) # Apply overrides app.config.update(config_overrides) # Initialize the database and declarative Base class db.init_app(app) Migrate(app, db) app.db = db # Setup security app.user_db = SQLAlchemyUserDatastore(db, User, Role) Security(app, app.user_db) # SocketIO socketio.init_app(app) app.socketio = socketio # Other extensions Webpack(app) # Create the database tables. # Flask-SQLAlchemy needs to know which # app context to create the tables in. with app.app_context(): db.configure_mappers() db.create_all() # Register blueprints app.register_blueprint(bp) if not app.debug: Sentry(app, dsn=config.SENTRY_DSN) return app
def test_style_tag_multiple_kvp(): app = Flask("test_app") # app.config['WEBPACK_MANIFEST_PATH'] = '' app.config["WEBPACK_LOG_LEVEL"] = "INFO" Webpack(app, assets_url="/", foo="foo.h4sh3d.css", bar="bar.11a6e2.css") with app.app_context(): rendered = render_template_string( "{{ stylesheet_tag(" '"foo", "bar", crossorigin="anonymous", type="text/css"' ") }}") expected = ('<link rel="stylesheet"' ' href="/foo.h4sh3d.css"' ' crossorigin="anonymous"' ' type="text/css">\n' '<link rel="stylesheet"' ' href="/bar.11a6e2.css"' ' crossorigin="anonymous"' ' type="text/css">') check_attrib(rendered, expected)
def test_chunked_asset_map_deduped(): path = os.path.abspath( os.path.join(__dirname, "flat_chunked_asset_map.json")) app = Flask("test_app") app.config["WEBPACK_MANIFEST_PATH"] = path app.config["WEBPACK_ASSETS_URL"] = "correct/" Webpack(app) with app.app_context(): # r1, r2 are equivalent: both test that the vendor chunk is deduped r1 = render_template_string("{{ javascript_tag('foo', 'bar') }}") r2 = render_template_string( "{{ javascript_tag('foo') }}\n{{ javascript_tag('bar') }}") # still, you should be able to duplicate chunks if you need. r3 = render_template_string( "{{ javascript_tag('vendor~jquery', unique=False) }}" "{{ javascript_tag('vendor~jquery', unique=False) }}") vendor = '<script src="correct/vendor~jquery.ch0nk3d.js" ></script>' foo = '<script src="correct/foo.h4sh3d.js" ></script>' bar = '<script src="correct/completely-different.hashed.js" ></script>' assert r1 == r2 assert r1 == "\n".join((vendor, foo, bar)) assert r3 == vendor + vendor
def test_chunked_asset_map(): path = os.path.abspath( os.path.join(__dirname, "flat_chunked_asset_map.json")) app = Flask("test_app") app.config["WEBPACK_MANIFEST_PATH"] = path app.config["WEBPACK_ASSETS_URL"] = "correct/" Webpack(app) with app.app_context(): r1 = render_template_string( '{{ javascript_tag("vendor~jquery", defer=True) }}') r2 = render_template_string( "{{ javascript_tag('foo', attrs={'defer': True}) }}") r3 = render_template_string( # TODO: /// "{{ javascript_tag('bar.js', attrs={'async': True}) }}") e1 = '<script src="correct/vendor~jquery.ch0nk3d.js" defer></script>' e2 = e1 + '\n<script src="correct/foo.h4sh3d.js" defer></script>' e3 = ( e1.replace("defer", "async") + '\n<script src="correct/completely-different.hashed.js" async></script>' ) assert r1 == e1 assert r2 == e2 assert r3 == e3
"""Extensions module. Each extension is initialized in the app factory located in app.py.""" from flask_caching import Cache from flask_debugtoolbar import DebugToolbarExtension from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_webpack import Webpack from flask_wtf.csrf import CSRFProtect csrf_protect = CSRFProtect() # pylint: disable=invalid-name db = SQLAlchemy() # pylint: disable=invalid-name migrate = Migrate() # pylint: disable=invalid-name cache = Cache() # pylint: disable=invalid-name debug_toolbar = DebugToolbarExtension() # pylint: disable=invalid-name webpack = Webpack() # pylint: disable=invalid-name
import pandas as pd import mimetypes from redis import Redis from flask import Flask, render_template, request, session from flask_socketio import SocketIO, emit, send from flask_webpack import Webpack from flask_bootstrap import Bootstrap # from flask_migrate import Migrate # from flask_sqlalchemy import SQLAlchemy from sqlalchemy import create_engine from py import main, app, socketio, redis from py.app_controller import SceneBuilder as sb from threading import Timer, Lock webpack = Webpack() app = Flask(__name__) params = {'DEBUG': True, 'WEBPACK_MANIFEST_PATH': './build/manifest.json'} app.config.update(params) socket_ = SocketIO(app, async_mode=None) webpack.init_app(app) mimetypes.add_type('application/javascript', '.mjs') thread = None # thread_lock = Lock() # socketio = SocketIO(app, async_mode=None) # redis = Redis(host='redis', port=6379)
from sys import platform from os import environ, path from logging import getLogger, Logger from logging.config import dictConfig from flask import Flask, logging from flask_sqlalchemy import SQLAlchemy from sqlalchemy.schema import MetaData from flask_migrate import Migrate from flask_jwt_extended import JWTManager from flask_bcrypt import Bcrypt from flask_webpack import Webpack from flask_cors import CORS, cross_origin WEBPACK = Webpack() # type: Webpack # Setup Config APP = Flask(__name__, instance_relative_config=True) # type: Flask APP.config['MODE'] = environ['MODE'].upper() if APP.config['MODE'] == 'PRODUCTION': APP.config.from_object( 'total_tolles_ferleihsystem.config.ProductionConfig') elif APP.config['MODE'] == 'DEBUG': APP.config.from_object('total_tolles_ferleihsystem.config.DebugConfig') elif APP.config['MODE'] == 'TEST': APP.config.from_object('total_tolles_ferleihsystem.config.TestingConfig') APP.config.from_pyfile('/etc/total-tolles-ferleihsystem.conf', silent=True) APP.config.from_pyfile('total-tolles-ferleihsystem.conf', silent=True) if ('CONFIG_FILE' in environ):
from flask import Flask, request, send_from_directory from flask_babel import Babel from flask_session import Session from flask_webpack import Webpack from converters.DateConverter import DateConverter app = Flask(__name__, static_folder=None) app.config.from_object('pvlogweb.config') app.config.from_envvar('PVLOGWEB_SETTINGS', silent=True) babel = Babel(app) session = Session(app) webpack = Webpack(app) app.url_map.converters['date_converter'] = DateConverter import errrorhandlers from admin.views import admin app.register_blueprint(admin, url_prefix='/admin') from public.views import public app.register_blueprint(public) @babel.localeselector def get_locale(): return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
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.response_class = JsonifyDictResponse 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.errorhandler(Unauthorized)(jsonify_with_code(HTTPStatus.UNAUTHORIZED)) app.errorhandler(Forbidden)(jsonify_with_code(HTTPStatus.FORBIDDEN)) app.errorhandler(NotFound)(jsonify_with_code(HTTPStatus.NOT_FOUND)) app.errorhandler(InternalServerError)(jsonify_with_code(HTTPStatus.INTERNAL_SERVER_ERROR)) @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
from os import environ, path from logging import Formatter from logging.handlers import RotatingFileHandler from flask import Flask, logging from flask_sqlalchemy import SQLAlchemy from sqlalchemy.schema import MetaData from flask_migrate import Migrate from flask_jwt_extended import JWTManager from flask_bcrypt import Bcrypt from flask_webpack import Webpack from flask_cors import CORS, cross_origin webpack = Webpack() # type: Webpack # Setup Config app = Flask(__name__, instance_relative_config=True) # type: Flask app.config['MODE'] = environ['MODE'].upper() if app.config['MODE'] == 'PRODUCTION': app.config.from_object('muse_for_music.config.ProductionConfig') elif app.config['MODE'] == 'DEBUG': app.config.from_object('muse_for_music.config.DebugConfig') elif app.config['MODE'] == 'TEST': app.config.from_object('muse_for_music.config.TestingConfig') app.config.from_pyfile('/etc/muse_for_music.conf', silent=True) app.config.from_pyfile('muse_for_music.conf', silent=True) # TODO use nevironment variables for env_var in ('SQLALCHEMY_DATABASE_URI', 'JWT_SECRET_KEY', 'LOG_PATH',
import os from flask_webpack import Webpack # configuration DATABASE = '/tmp/dubhacks_collector.db' DEBUG = True SECRET_KEY = 'development key' USERNAME = '******' PASSWORD = '******' # create our little application :) app = Flask(__name__) app.config.from_object(__name__) # app.secret_key = 'some key for session' webpack = Webpack() webpack.init_app(app) def connect_db(): return sqlite3.connect(app.config['DATABASE']) def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() def root_dir(): # pragma: no cover print os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "app", "src")) return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "app", "src"))
"""Extensions module. Each extension is initialized in the app factory located in app.py.""" from flask_caching import Cache from flask_debugtoolbar import DebugToolbarExtension from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_webpack import Webpack from flask_wtf.csrf import CSRFProtect from flask_security import Security csrf_protect = CSRFProtect() db = SQLAlchemy() migrate = Migrate() cache = Cache() debug_toolbar = DebugToolbarExtension() webpack = Webpack() security = Security()
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