def create_app(app_name, config_obj, api_prefix='/api/v1'): """ Generates and configures the main application.""" # Launching application app = Flask(app_name) # So the engine would recognize the root package with app.app_context(): # Load Configuration app.config.from_object(config_obj) # Loading assets assets = Environment(app) assets.from_yaml('assets.yaml') app.assets = assets # Initializing bcrypt password encryption bcrypt = Bcrypt(app) app.bcrypt = bcrypt # Initializing Database db = SQLAlchemy(app) app.db = db # Initializing login manager login_manager = LoginManager() login_manager.login_view = app.config.get('LOGIN_VIEW', '.login') login_manager.session_protection = 'strong' login_manager.init_app(app) app.login_manager = login_manager # Initializing principal manager app.principal = Principal(app) # Initializing Alembic alembic = Alembic() alembic.init_app(app) app.alembic = alembic api = Api(app, prefix=api_prefix) app.api = api # include an api_registry to the application app.api_registry = [ ] # a simple list holding the values to be registered return app
class TestEnv: def setup(self): self.app = Flask(__name__) self.env = Environment(self.app) self.env.debug = True self.env.register('test', 'file1', 'file2') def test_tag_available(self): """Jinja tag has been made available. """ t = self.app.jinja_env.from_string( '{% assets "test" %}{{ASSET_URL}};{% endassets %}') assert t.render() == '/static/file1;/static/file2;' def test_from_yaml(self): """YAML configuration gets loaded """ f = open('test.yaml', 'w') f.write(""" yamltest: contents: - yamlfile1 - yamlfile2 """) f.close() self.env.from_yaml('test.yaml') t = self.app.jinja_env.from_string( '{% assets "yamltest" %}{{ASSET_URL}};{% endassets %}') assert t.render() == '/static/yamlfile1;/static/yamlfile2;' os.remove('test.yaml') def test_from_python_module(self): """Python configuration module gets loaded """ import types module = types.ModuleType('test') module.pytest = Bundle('pyfile1', 'pyfile2') self.env.from_module(module) t = self.app.jinja_env.from_string( '{% assets "pytest" %}{{ASSET_URL}};{% endassets %}') assert t.render() == '/static/pyfile1;/static/pyfile2;'
class TestEnv: def setup(self): self.app = Flask(__name__) self.env = Environment(self.app) self.env.debug = True self.env.register('test', 'file1', 'file2') def test_tag_available(self): """Jinja tag has been made available. """ t = self.app.jinja_env.from_string('{% assets "test" %}{{ASSET_URL}};{% endassets %}') assert t.render() == '/static/file1;/static/file2;' def test_from_yaml(self): """YAML configuration gets loaded """ f = open('test.yaml', 'w') f.write(""" yamltest: contents: - yamlfile1 - yamlfile2 """) f.close() self.env.from_yaml('test.yaml') t = self.app.jinja_env.from_string('{% assets "yamltest" %}{{ASSET_URL}};{% endassets %}') assert t.render() == '/static/yamlfile1;/static/yamlfile2;' os.remove('test.yaml') def test_from_python_module(self): """Python configuration module gets loaded """ import types module = types.ModuleType('test') module.pytest = Bundle('pyfile1', 'pyfile2') self.env.from_module(module) t = self.app.jinja_env.from_string('{% assets "pytest" %}{{ASSET_URL}};{% endassets %}') assert t.render() == '/static/pyfile1;/static/pyfile2;'
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) pagedown.init_app(app) assets = Environment(app) assets.from_yaml(os.path.join(appdir, 'assets.yaml')) assets.init_app(app) from main import main as main_blueprint app.register_blueprint(main_blueprint) from auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
manager = Manager(app) manager.add_command("db", MigrateCommand) # add commands to manage chart cache from whiskyton.managers.charts import ChartsCommand manager.add_command("charts", ChartsCommand) # add command to save analytics data via FTP from whiskyton.managers.anaytics import AnalyticsCommand manager.add_command("analytics", AnalyticsCommand) # enable gzip compression Compress(app) # scss assets = Environment(app) assets.load_path = [app.config["BASEDIR"].child("whiskyton")] assets.from_yaml(app.config["BASEDIR"].child("whiskyton", "assets.yaml")) # log errors log_handler = StreamHandler() app.logger.setLevel(logging.DEBUG) app.logger.addHandler(log_handler) # register blueprints from whiskyton.blueprints.site import site from whiskyton.blueprints.files import files app.register_blueprint(site) app.register_blueprint(files)
app.debug = True # Setup Bcrypt app.config["BCRYPT_LOG_ROUNDS"] = config.bcryptLogRounds bcrypt = Bcrypt(app) # Setup flask assets assets = Environment(app) # Set the Flask Assets debug mode # Note that the bundling is _only_ performed when flask assets is _not_ in debug mode. # Thus, we want it to follow the global debug setting unless we explicit set it otherwise. # For more information, particularly on debugging, see the web app `README.md`. Further details # are included in the web app utilities module where the filter is defined. app.config["ASSETS_DEBUG"] = serverParameters["flaskAssetsDebug"] if not serverParameters["flaskAssetsDebug"] is None else serverParameters["debug"] # Load bundles from configuration file assets.from_yaml(pkg_resources.resource_filename("overwatch.webApp", "flaskAssets.yaml")) # Setup CSRF protection via flask-wtf csrf = CSRFProtect(app) # Setup custom error handling to use the error template. @app.errorhandler(CSRFError) def handleCSRFError(error): """ Handle CSRF error. Takes advantage of the property of the ``CSRFError`` class which will return a string description when called with ``str()``. Note: The only requests that could fail due to a CSRF token issue are those made with AJAX, so it is reasonable to return an AJAX formatted response.
def create_app(config=None): """ config should be a python file """ from pathlib import Path from flask import (Flask, current_app, g, session, url_for, render_template) from flask_sqlalchemy import SQLAlchemy from flask_security import (Security, SQLAlchemyUserDatastore) from flask_wtf.csrf import CsrfProtect from flask_assets import (Environment, Bundle) from .app_setup import (init_db, setup_dirs) from .core import (db, load_blueprints, setup_logger) from .lib.template_filters import ( fmt_datetime, none_as_str, next_page_url, prev_page_url, get_page_url, get_images) from .models.user import (User, Role, user_datastore) from .Admin import (index, series, images, texts, contact) from .Public import (index, contact, texts) from .Security import user app = Flask(__name__.split('.')[0], instance_relative_config=True) app.config.from_object('config') app.config.from_pyfile('config.py') if config is not None: app.config.from_pyfile(config) setup_logger(app) app.logger.info('Started with config from: {}'.format(config)) else: setup_logger(app) app.logger.info('Started App') # Flask.sqlalchemy db.init_app(app) load_blueprints(app) # make sure db tables and required directories exist before_first_request_funcs = [setup_dirs(app), init_db(app)] #Security csrf = CsrfProtect() csrf.init_app(app) security = Security() security.init_app(app, user_datastore, register_blueprint=False) # Assets assets = Environment(app=app) assets.from_yaml('assets.yml') # template filters app.add_template_filter(fmt_datetime) app.add_template_filter(none_as_str) app.add_template_filter(next_page_url) app.add_template_filter(prev_page_url) app.add_template_filter(get_page_url) app.add_template_filter(get_images) return app
from flask_assets import Environment ASSETS = Environment() ASSETS.from_yaml('assets.yml')
def init_app(app): assets = Environment(app) assets.from_yaml(path.join(config.PROJECT_PATH, 'resources', 'assets.yaml'))
def create_app(app_name, config_obj, with_api=True): """ Generates and configures the main shop application. All additional """ # Launching application app = Flask(app_name) # So the engine would recognize the root package # Load Configuration app.config.from_object(config_obj) # Initializing Database db = SQLAlchemy(app) app.db = db # migrate = Migrate(app, db) alembic = Alembic() alembic.init_app(app) app.alembic = alembic # Loading assets assets = Environment(app) assets.from_yaml('assets.yaml') app.assets = assets # Initialize Mail app.mail = Mail(app) # Initializing login manager login_manager = LoginManager() login_manager.login_view = app.config.get('LOGIN_VIEW', '.login') # login_manager.login_message = 'You need to be logged in to access this page' login_manager.session_protection = 'strong' login_manager.setup_app(app) app.login_manager = login_manager # Initializing principal manager app.principal = Principal(app) # Initializing bcrypt password encryption bcrypt = Bcrypt(app) app.bcrypt = bcrypt app.cloudinary = cloudinary app.cloudinary_upload = cloudinary_upload photos = UploadSet('photos', IMAGES) archives = UploadSet('archives', ARCHIVES) configure_uploads(app, (photos, archives)) patch_request_class(app, 16 * 1024 * 1024) # Patches to 16MB file uploads max. app.photos = photos app.archives = archives moment = Moment(app) app.moment = moment # Redis store for session management # The process running Flask needs write access to this directory: # store = RedisStore(redis.StrictRedis()) # # this will replace the app'cs session handling # KVSessionExtension(store, app) # # configure sentry # if not app.config.get("DEBUG", False): # sentry = Sentry(app) # app.sentry = sentry # Integrate Elasticsearch # es_config = app.config.get("ES_CONFIG", []) # app.es = Elasticsearch(es_config) # Caching app.cache = Cache(app) # Initializing the restful API if with_api: api = Api(app, prefix='/v1') app.api = api # Initialize Logging if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler( "/var/log/kx/%s.log" % app.config.get("LOGFILE_NAME", app_name), maxBytes=500 * 1024) file_handler.setLevel(logging.INFO) from logging import Formatter file_handler.setFormatter( Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) app.logger.addHandler(file_handler) # include an api_registry to the application app.api_registry = [] # a simple list holding the values to be registered return app
>>> assets.cache = False >>> assets.manifest = False - To debug, you still need to delete and touch the relevant files in between each change. Usually, that means: - Deleting the file in the gen/ folder - Removing the static/.webassets folder if it exists - Update or otherwise touch the file of interest - Each Asset won't be built until first access of the particular file. Access the associated urls of the asset to force it to built immediately (will still only be built if needed or forced by following the debug procedure above). >>> print(assets["polymerBundle"].urls()) """ # Load bunldes from configuration file assets.from_yaml(os.path.join(os.path.dirname(__file__), "flaskAssets.yaml")) # Setup login manager loginManager = LoginManager() loginManager.init_app(app) # Tells the manager where to redirect when login is required. loginManager.login_view = "login" ################################################### @loginManager.user_loader def load_user(user): """ Used to remember the user so that they don't need to login again each time they visit the site. """ return auth.User.getUser(user, db)
from flask import current_app from flask_assets import Environment from flask_sqlalchemy import SQLAlchemy from .cache import Cache from .gzip import Gzip assets_env = Environment() cache = Cache() db = SQLAlchemy() gzip = Gzip() def get_queue(): try: from flask import _app_ctx_stack as stack except ImportError: from flask import _request_ctx_stack as stack ctx = stack.top if ctx is not None: if not hasattr(ctx, 'queue'): import rq rq.connections.use_connection( current_app.extensions['cache'][cache]._client) ctx.queue = rq.Queue() return ctx.queue assets_env.from_yaml(join(dirname(__file__), 'static/assets.yaml'))
import os from flask import Flask, escape, render_template, request from flask_assets import Environment, Bundle from webassets.loaders import YAMLLoader app = Flask(__name__) assets = Environment(app) assets.from_yaml(os.path.dirname(__file__) + "/assets.yml") @app.route('/') def index(): name = request.args.get("name", "World") return render_template('pages/index.html', name=name)