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 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_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 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 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 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 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) return app
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 _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_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
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())
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',
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):
"""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
"""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