Exemplo n.º 1
0
def create_app(config_object, env):
    '''An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/

    :param config_object: The configuration object to use.
    :param env: A string, the current environment. Either "dev" or "prod"
    '''
    app = Flask(__name__)
    app.config.from_object(config_object)
    app.config['ENV'] = env
    # Initialize SQLAlchemy
    db.init_app(app)
    # Register bcrypt
    bcrypt.init_app(app)
    # Register asset bundles
    assets_env.init_app(app)
    assets_loader = PythonLoader(assets)
    for name, bundle in assets_loader.load_bundles().iteritems():
        assets_env.register(name, bundle)
    # Register blueprints
    from flask_boilerplate.modules import public, member
    app.register_blueprint(public.blueprint)
    app.register_blueprint(member.blueprint)

    return app
Exemplo n.º 2
0
 def test_path(self):
     """[bug] Regression test: Python loader does not leave
     sys.path messed up.
     """
     old_path = sys.path[:]
     loader = PythonLoader('sys')
     assert sys.path == old_path
Exemplo n.º 3
0
    def test_load_bundles(self):
        import types
        module = types.ModuleType('test')
        module.foo = Bundle('bar')

        loader = PythonLoader(module)
        bundles = loader.load_bundles()
        assert len(bundles) == 1
        assert list(bundles.values())[0].contents[0] == 'bar'
Exemplo n.º 4
0
 def _setup_assets_env(self, ns, log):
     env = self.env
     if env is None:
         assert not (ns.module and ns.config)
         if ns.module:
             env = PythonLoader(ns.module).load_environment()
         if ns.config:
             env = YAMLLoader(ns.config).load_environment()
     return env
Exemplo n.º 5
0
    def load_bundles(self, module):
        """
        Load predefined bundles from a YAML file.

        See bundles.yaml for an example.
        """

        # Load bundles from YAML file
        loader = PythonLoader(module)
        bundles = loader.load_bundles()

        # Register the bundles with the environment
        self.register(bundles)
Exemplo n.º 6
0
    def test_load_environment_with_prefix(self):
        import types
        module = types.ModuleType("testing")
        module2 = types.ModuleType("testing2")
        module.environment = Environment() # default name
        module2.assets = Environment()
        sys.modules["testing"] = module
        sys.modules["testing2"] = module2

        loader = PythonLoader("testing")
        env = loader.load_environment()
        assert env == module.environment

        loader2 = PythonLoader("testing:environment")
        assert loader2.environment == "environment"
        env2 = loader2.load_environment()
        assert env2 == module.environment

        loader3 = PythonLoader("testing2:assets")
        assert loader3.environment == "assets"
        env3 = loader3.load_environment()
        assert env3 == module2.assets
Exemplo n.º 7
0
def create_app(object_name):
    app = Flask(__name__)

    app.config.from_object(object_name)
    cache.init_app(app)
    debug_toolbar.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    assets_env.init_app(app)
    assets_loader = PythonLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    app.register_blueprint(main)
    return app
Exemplo n.º 8
0
def includeme(config):
    config.include('pyramid_webassets')

    config.add_static_view('css', 'h:css')
    config.add_static_view('js', 'h:js')
    config.add_static_view('lib', 'h:lib')
    config.add_static_view('images', 'h:images')

    loader = PythonLoader(config.registry.settings.get('h.assets', __name__))
    bundles = loader.load_bundles()
    for name in bundles:
        config.add_webasset(name, bundles[name])

    from deform.field import Field
    resource_registry = WebassetsResourceRegistry(config.get_webassets_env())
    Field.set_default_resource_registry(resource_registry)
    config.registry.resources = resource_registry
Exemplo n.º 9
0
def main(argv, env=None):
    """Generic version of the command line utilities, not specific to
    any framework.

    TODO: Support -c option to load from YAML config file
    """
    parser = OptionParser(usage="usage: %%prog [options] [%s]" %
                          (" | ".join(CommandLineEnvironment.Commands)))
    parser.add_option("-v",
                      dest="verbose",
                      action="store_true",
                      help="be verbose")
    parser.add_option("-q", action="store_true", dest="quiet", help="be quiet")
    if env is None:
        parser.add_option("-m",
                          "--module",
                          dest="module",
                          help="read environment from a Python module")
    (options, args) = parser.parse_args(argv)

    if len(args) != 1:
        parser.print_help()
        return 1

    # Setup logging
    log = logging.getLogger('webassets')
    log.setLevel(logging.DEBUG if options.verbose else (
        logging.WARNING if options.quiet else logging.INFO))
    log.addHandler(logging.StreamHandler())

    # Load the bundles we shall work with
    if env is None and options.module:
        env = PythonLoader(options.module).load_environment()

    if env is None:
        print "Error: No environment given or found. Maybe use -m?"
        return 1

    # Run the selected command
    cmd = CommandLineEnvironment(env, log)
    try:
        return cmd.invoke(args[0])
    except CommandError, e:
        print e
        return 1
Exemplo n.º 10
0
def includeme(config):
    config.include('pyramid_webassets')

    env = config.get_webassets_env()
    kw = {}
    if env.url_expire is not False:
        # Cache for one year (so-called "far future" Expires)
        kw['cache_max_age'] = 31536000
    config.add_static_view(env.url, env.directory, **kw)

    loader = PythonLoader(config.registry.settings.get('h.assets', __name__))
    bundles = loader.load_bundles()
    for name in bundles:
        log.info('name: ' + str(name))
        config.add_webasset(name, bundles[name])

    from deform.field import Field
    resource_registry = WebassetsResourceRegistry(config.get_webassets_env())
    Field.set_default_resource_registry(resource_registry)
    config.registry.resources = resource_registry
Exemplo n.º 11
0
    def run_with_argv(self, argv):
        try:
            ns = self.parser.parse_args(argv)
        except SystemExit:
            # We do not want the main() function to exit the program.
            # See run() instead.
            return 1

        # Setup logging
        if self.log:
            log = self.log
        else:
            log = logging.getLogger('webassets')
            log.setLevel(logging.DEBUG if ns.verbose else (
                logging.WARNING if ns.quiet else logging.INFO))
            log.addHandler(logging.StreamHandler())

        # Load the bundles we shall work with
        env = self.env
        if env is None:
            assert not (ns.module and ns.config)
            if ns.module:
                env = PythonLoader(ns.module).load_environment()
            if ns.config:
                env = YAMLLoader(ns.config).load_environment()

        if env is None:
            raise CommandError(
                "Error: No environment given or found. Maybe use -m?")

        # Prepare a dict of arguments cleaned of values that are not
        # command-specific, and which the command method would not accept.
        args = vars(ns).copy()
        for name in ('verbose', 'quiet', 'module', 'config', 'command'):
            if name in args:
                del args[name]

        # Run the selected command
        cmd = CommandLineEnvironment(env, log)
        return cmd.invoke(ns.command, args)
Exemplo n.º 12
0
 def from_module(self, path):
     """Register bundles from a Python module"""
     bundles = PythonLoader(path).load_bundles()
     for name in bundles:
         self.register(name, bundles[name])
Exemplo n.º 13
0
def add_webassets(config):
    loader = PythonLoader(__name__)
    bundles = loader.load_bundles()
    for name in bundles:
        config.add_webasset(name, bundles[name])
Exemplo n.º 14
0
# load config
app.config.update(
    DEBUG=debug,
    SHOW_GA=show_ga,
    SECRET_KEY=os.environ.get('SECRET_KEY', ''),
    # GOOGLE_LOGIN_CLIENT_ID=os.environ.get('GOOGLE_LOGIN_CLIENT_ID', ''),
    # GOOGLE_LOGIN_CLIENT_SECRET=os.environ.get('GOOGLE_LOGIN_CLIENT_SECRET', ''),
    # GOOGLE_LOGIN_REDIRECT_URI=os.environ.get('GOOGLE_LOGIN_REDIRECT_URI', ''),
    SQLALCHEMY_TRACK_MODIFICATIONS=True,
    SQLALCHEMY_DATABASE_URI=os.environ.get(
        'SQLALCHEMY_DATABASE_URI', 'postgres://*****:*****@localhost/beer'),
)

db = SQLAlchemy(app)

# setup assetbundle

assets = Environment(app)
assets.debug = False  # app.debug # (debug=True f***s up jsx)

bundles = PythonLoader('web.assetbundles').load_bundles()
for name, bundle in bundles.iteritems():
    assets.register(name, bundle)

# add various views
from web import views
from web import api

app.db_session = db.session
Exemplo n.º 15
0
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy
from webassets.loaders import PythonLoader

import project.asset_bundles

app = Flask(__name__)
app.config.from_object('project.config')

db = SQLAlchemy(app)
migrate = Migrate(app, db)

import routes
# from models import *

assets = Environment(app)
assets.versions = "hash:32"
assets.auto_build = app.config["SERVER_ENV"] == 'development'
assets.debug = False
bundles = PythonLoader(project.asset_bundles).load_bundles()
for name, bundle in bundles.iteritems():
    assets.register(name, bundle)

manager = Manager(app)
manager.add_command('db', MigrateCommand)
manager.add_command('assets', ManageAssets)

if __name__ == '__main__':
    manager.run()
Exemplo n.º 16
0
app.config.update(
    DEBUG=os.environ.get('DEBUG', False),
    SECRET_KEY=os.environ.get('SECRET_KEY', ''),
    GOOGLE_LOGIN_CLIENT_ID=os.environ.get('GOOGLE_LOGIN_CLIENT_ID', ''),
    GOOGLE_LOGIN_CLIENT_SECRET=os.environ.get('GOOGLE_LOGIN_CLIENT_SECRET',
                                              ''),
    GOOGLE_LOGIN_REDIRECT_URI=os.environ.get('GOOGLE_LOGIN_REDIRECT_URI', ''),
    SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', ''),
)

db = SQLAlchemy(app)

# setup assetbundle
assets = Environment(app)
assets.debug = True if app.debug == 'True' else False
bundles = PythonLoader('newbeercellar.assetbundles').load_bundles()
for name, bundle in bundles.iteritems():
    assets.register(name, bundle)

# setup login stuff
login_manager = LoginManager()
login_manager.init_app(app)
googlelogin = GoogleLogin(app, login_manager)

# add various views
from newbeercellar import login
from newbeercellar import views
from newbeercellar import api

app.db_session = db.session
Exemplo n.º 17
0
app = Flask(__name__)
app.config.from_pyfile('settings/common.py')

if os.getenv('FLASK_CONFIG'):
    app.config.from_envvar('FLASK_CONFIG')

if app.debug:
    logging.getLogger().setLevel(logging.DEBUG)

db = SQLAlchemy(app)

mail = Mail(app)

# static assets
assets = PythonLoader('app.assetconfig').load_environment()
bundles = PythonLoader('app.assetconfig').load_bundles()

for bundle_name, bundle in bundles.items():
    assets.register(bundle_name, bundle)


@app.context_processor
def debug_context():
    "Notifies templates that they're in debug mode"
    return dict(debug=app.debug)


@app.context_processor
def ga_context():
    "Notifies templates that they're in debug mode"
Exemplo n.º 18
0
 def from_module(self, path):
     """Register bundles from a Python module"""
     bundles = PythonLoader(path).load_bundles()
     [self.register(name, bundle) for name, bundle in bundles.iteritems()]
Exemplo n.º 19
0
parser.add_argument('--reference-output',
                    dest='reference_output',
                    default='infcloud/index.html',
                    help='The html file to output')
parser.add_argument('command',
                    metavar='command',
                    default='build',
                    help='build, watch or clean')
args = parser.parse_args()

# Setup a logger
log = logging.getLogger('webassets')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.__dict__[args.loglevel])

loader = PythonLoader('webassets_config')
assets_env = loader.load_environment()
assets_env.debug = args.debug

cmdenv = CommandLineEnvironment(assets_env, log)
cmdenv.build()

if args.debug:
    print("The following files are produced by assets pipeline:")
    print(assets_env['js'].urls())
    print(assets_env['css'].urls())

if args.command != 'build':
    cmdenv.invoke(args.command, {})

if args.reference:
Exemplo n.º 20
0
def add_webassets(config):
    config.include('pyramid_webassets')
    loader = PythonLoader(__name__)
    bundles = loader.load_bundles()
    for name in bundles:
        config.add_webasset(name, bundles[name])
Exemplo n.º 21
0
import flask_assets
from flask import Flask, render_template
from flask_socketio import SocketIO
from webassets.loaders import PythonLoader

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins=[])

assets = flask_assets.Environment()
assets.init_app(app)
assets_loader = PythonLoader('freeraincloud.assets')
for name, bundle in assets_loader.load_bundles().items():
    assets.register(name, bundle)


@app.route("/")
def index():
    return render_template('index.html')


if __name__ == "__main__":
    app.run()
Exemplo n.º 22
0
CsrfProtect(app)

mongo = PyMongo(app)

login_manager = LoginManager()
login_manager.init_app(app)

eve_db = sqlalchemy.create_engine(app.config['EVE_STATIC_DUMP'])

oauth = OAuth(app)
hr_oauth = oauth.remote_app(
    'j4hr2',
    app_key='J4OAUTH'
)

rQueue = Queue(connection=redis.StrictRedis(app.config['REDIS']))

api_oauth = requests.Session()
api_oauth.headers.update({
    'x-oauth-key': app.config['J4OAUTH']['consumer_key'],
    'x-oauth-secret': app.config['J4OAUTH']['consumer_secret']})


# Register asset bundles
assets_env = Environment()
assets_env.init_app(app)
assets_loader = PythonLoader(assets)
for name, bundle in assets_loader.load_bundles().iteritems():
    assets_env.register(name, bundle)