Exemple #1
0
    def test_filter(self):
        """Test blueprint filter."""
        app = Flask(__name__)

        blueprint = Blueprint('test1', __name__, static_folder='static1')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test3', __name__, static_folder='static3')
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root
        app.config['COLLECT_FILTER'] = partial(filter_, ['test3', 'test1'])
        app.config['COLLECT_STORAGE'] = 'flask_collect.storage.test'

        collect = Collect(app)
        test = list(collect.collect(verbose=True))
        self.assertEqual(len(test), 2)
        self.assertTrue('static3' in test[1][1])

        app.config['COLLECT_FILTER'] = partial(filter_, ['test1', 'test3'])
        collect = Collect(app)
        test = list(collect.collect(verbose=True))
        self.assertTrue('static1' in test[1][1])

        rmtree(static_root)
Exemple #2
0
    def test_collect(self):
        app = Flask(__name__)

        blueprint = Blueprint(
            'test1', __name__, static_folder='static1',
            static_url_path='/static/test1')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test2', __name__, static_folder='static2')
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root

        collect = Collect(app)
        collect.collect(verbose=True)

        self.assertTrue(op.exists(op.join(static_root, 'test1', 'test.css')))
        self.assertTrue(op.exists(op.join(static_root, 'js', 'test.js')))
        self.assertTrue(op.exists(op.join(static_root, 'app.css')))

        app.config['COLLECT_STORAGE'] = 'flask_collect.storage.test'
        collect = Collect(app)
        test = collect.collect(verbose=True)
        self.assertEqual(len(test), 3)

        rmtree(static_root)
Exemple #3
0
def setup_app(app):
    """Initialize Menu."""
    def filter_(items):
        """Filter application blueprints."""
        order = [blueprint.name for blueprint in
                 app.extensions['registry']['blueprints']]

        def _key(item):
            if item.name in order:
                return order.index(item.name)
            return -1

        return sorted(items, key=_key)

    app.config.setdefault('COLLECT_FILTER', filter_)
    app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)

    ext = Collect(app)

    # unsetting the static_folder so it's not picked up by collect.
    class FakeApp(object):
        name = "fakeapp"
        has_static_folder = False
        static_folder = None

    ext.app = FakeApp()

    app.cli.add_command(collect)
Exemple #4
0
    def test_collect(self):
        from tempfile import mkdtemp
        from flask import Flask, Blueprint
        from flask_collect import Collect
        from os import path as op

        app = Flask(__name__)

        blueprint = Blueprint(
            'test1', __name__, static_folder='static1',
            static_url_path='/static/test1')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test2', __name__, static_folder='static2')
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root

        collect = Collect(app)
        collect.collect(verbose=True)

        self.assertTrue(op.exists(op.join(static_root, 'test1', 'test.css')))
        self.assertTrue(op.exists(op.join(static_root, 'js', 'test.js')))
        self.assertTrue(op.exists(op.join(static_root, 'app.css')))

        app.config['COLLECT_STORAGE'] = 'flask.ext.collect.storage.test'
        collect = Collect(app)
        test = collect.collect(verbose=True)
        self.assertTrue(len(test), 2)
Exemple #5
0
class InvenioAssets(object):
    """Invenio asset extension."""

    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.env = Environment()
        self.collect = Collect()

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, entry_point_group='invenio_assets.bundles',
                 **kwargs):
        """Initialize application object.

        :param app: An instance of :class:`~flask.Flask`.
        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        self.init_config(app)
        self.env.init_app(app)
        self.collect.init_app(app)

        if entry_point_group:
            self.load_entrypoint(entry_point_group)
        app.extensions['invenio-assets'] = self

    def init_config(self, app):
        """Initialize configuration.

        :param app: An instance of :class:`~flask.Flask`.
        """
        app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')
        app.config.setdefault(
            'COLLECT_FILTER', partial(collect_staticroot_removal, app))

    def load_entrypoint(self, entry_point_group):
        """Load entrypoint.

        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        for ep in pkg_resources.iter_entry_points(entry_point_group):
            self.env.register(ep.name, ep.load())
Exemple #6
0
    def test_link_storage(self):
        """Test file storage."""
        dummy_app = Flask(__name__)

        test_static3 = mkdtemp()
        dummy_bp = Blueprint('dummy', __name__, static_folder='static3')
        dummy_app.register_blueprint(dummy_bp)

        dummy_app.config['COLLECT_STATIC_ROOT'] = test_static3
        dummy_app.config['COLLECT_STORAGE'] = 'flask_collect.storage.file'

        dummy_collect = Collect(dummy_app)
        dummy_collect.collect()

        with open(op.join(test_static3, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: red; }' in file_.read())

        app = Flask(__name__)

        blueprint = Blueprint('test1', __name__, static_folder='static1')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test2', __name__, static_folder='static2')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test3', __name__, static_folder=test_static3)
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root
        app.config['COLLECT_FILTER'] = partial(filter_, ['test3', 'test1'])
        app.config['COLLECT_STORAGE'] = 'flask_collect.storage.link'

        collect = Collect(app)
        collect.collect()

        with open(op.join(static_root, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: red; }' in file_.read())

        with open(op.join(test_static3, 'test.css'), 'w') as file_:
            file_.write('body { color: green; }')

        with open(op.join(static_root, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: green; }' in file_.read())

        # remove custom test.css and re-collect files
        remove(op.join(test_static3, 'test.css'))
        collect.collect()

        with open(op.join(static_root, 'test.css'), 'r') as file_:
            # we get the file content from test1
            self.assertTrue('body { color: blue; }' in file_.read())

        rmtree(test_static3)
        rmtree(static_root)
Exemple #7
0
    def __init__(self, app=None, entrypoint="invenio_assets.bundles", **kwargs):
        """Extension initialization."""
        self.env = Environment()
        self.collect = Collect()
        self.entrypoint = entrypoint

        if app:
            self.init_app(app, **kwargs)
Exemple #8
0
    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.env = Environment()
        self.collect = Collect()

        if app:
            self.init_app(app, **kwargs)
Exemple #9
0
    def test_link_storage_update(self):
        """Test link storage update."""
        app = Flask(__name__)

        blueprint = Blueprint('test1', __name__, static_folder='static1')
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root
        app.config['COLLECT_FILTER'] = partial(filter_, ['test1'])
        app.config['COLLECT_STORAGE'] = 'flask_collect.storage.link'

        collect = Collect(app)
        collect.collect()

        # Make sure a new link has been created pointing to test1
        with open(op.join(static_root, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: blue; }' in file_.read())

        blueprint = Blueprint('test3', __name__, static_folder='static3')
        app.register_blueprint(blueprint)

        app.config['COLLECT_FILTER'] = partial(filter_, ['test3', 'test1'])
        collect = Collect(app)
        collect.collect()

        # Make sure a new link has been created pointing to test3
        with open(op.join(static_root, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: red; }' in file_.read())

        rmtree(static_root)
Exemple #10
0
def init(app) -> None:
    """
    Bundle projects assets.

    :param app: Main application instance
    :type app: flask.Flask
    """
    assets = Environment(app)
    assets.auto_build = app.config.get('ASSETS_AUTO_BUILD', True)
    files_to_watch = []

    if 'COLLECT_STATIC_ROOT' in app.config:
        assets.cache = app.config['COLLECT_STATIC_ROOT']
        collect = Collect()
        collect.init_app(app)
        collect.collect()
        app.static_folder = app.config['COLLECT_STATIC_ROOT']

    for key in ['js', 'css']:
        assets_key = '%s_ASSETS' % key.upper()
        build_files = app.config[assets_key]

        files_to_watch.extend(_get_files_for_settings(app, assets_key))

        bundle = Bundle(*build_files,
                        output=app.config['%s_OUTPUT' % assets_key],
                        filters=app.config['%s_FILTERS' % assets_key]
                        )

        assets.register('%s_all' % key, bundle)

        app.logger.debug('Bundling files: %s%s',
                         os.linesep,
                         os.linesep.join(build_files))

    app.assets = assets
    app._base_files_to_watch = files_to_watch

    app.logger.info('Base assets are collected successfully.')
Exemple #11
0
class InvenioAssets(object):
    """Invenio asset extension."""

    def __init__(self, app=None, entrypoint='invenio_assets.bundles',
                 **kwargs):
        """Extension initialization."""
        self.env = Environment()
        self.collect = Collect()
        self.entrypoint = entrypoint

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, **kwargs):
        """Initialize application object."""
        self.init_config(app)
        self.env.init_app(app)
        self.collect.init_app(app)
        self.init_cli(app.cli)
        if self.entrypoint:
            self.load_entrypoint(self.entrypoint)
        app.extensions['invenio-assets'] = self

    def init_config(self, app):
        """Initialize configuration."""
        app.config.setdefault("REQUIREJS_BASEURL", app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')

    def init_cli(self, cli):
        """Initialize CLI."""
        cli.add_command(assets_cmd)
        cli.add_command(npm)
        cli.add_command(collect)

    def load_entrypoint(self, entrypoint):
        """Load entrypoint."""
        for ep in pkg_resources.iter_entry_points(entrypoint):
            self.env.register(ep.name, ep.load())
Exemple #12
0
    def test_file_storage(self):
        """Test file storage."""
        app = Flask(__name__)

        blueprint = Blueprint('test1', __name__, static_folder='static1')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test3', __name__, static_folder='static3')
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root
        app.config['COLLECT_FILTER'] = partial(filter_, ['test3', 'test1'])
        app.config['COLLECT_STORAGE'] = 'flask_collect.storage.file'

        collect = Collect(app)
        collect.collect()

        with open(op.join(static_root, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: red; }' in file_.read())

        rmtree(static_root)
Exemple #13
0
    def finalize_create(self):
        # connect nav list to contextprosessor
        self.config['apps'] = frozenset(
            [x.name for x in self.blueprints.values()])
        self.context_processor(get_config_processor(self))

        # static stuff for production
        if self.env == PRODUCTION:
            # Add static handlers so url_for works
            for bp in self.blueprints.values():
                self.add_url_rule('/static/<path:filename>',
                                  endpoint='%s.static' % (bp.name, ),
                                  view_func=invalid_request)
            self.add_url_rule('/static/<path:filename>',
                              endpoint='static',
                              view_func=invalid_request)

            # Load collect
            try:
                from flask_collect import Collect
                collect = Collect()
                collect.init_app(self)
            except ImportError:
                pass
Exemple #14
0
    def test_file_storage_update(self):
        """Test file storage."""
        dummy_app = Flask(__name__)

        test_static3 = mkdtemp()
        dummy_bp = Blueprint('dummy', __name__, static_folder='static3')
        dummy_app.register_blueprint(dummy_bp)

        dummy_app.config['COLLECT_STATIC_ROOT'] = test_static3
        dummy_app.config['COLLECT_STORAGE'] = 'flask_collect.storage.file'

        dummy_collect = Collect(dummy_app)
        dummy_collect.collect()

        app = Flask(__name__)

        blueprint = Blueprint('test1', __name__, static_folder='static1')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test3', __name__, static_folder=test_static3)
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root
        app.config['COLLECT_FILTER'] = partial(filter_, ['test1', 'test3'])
        app.config['COLLECT_STORAGE'] = 'flask_collect.storage.file'

        collect = Collect(app)
        collect.collect()

        with open(op.join(static_root, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: blue; }' in file_.read())

        time.sleep(1)
        subprocess.call(['touch', op.join(test_static3, 'test.css')])

        # re-collect files
        collect.collect()

        # check that test3 was not added because it's newer
        with open(op.join(static_root, 'test.css'), 'r') as file_:
            self.assertTrue('body { color: blue; }' in file_.read())

        rmtree(test_static3)
        rmtree(static_root)
Exemple #15
0
def create_app(config, app=None):
    if app is None:
        app = Flask(__name__)
        app.config.from_object(config)

    app.collect = Collect(app)
    db.init_app(app)
    app.db = db

    from .models.auth import User, Role, UserRoles
    app.user_datastore = PeeweeUserDatastore(
        app.db,
        User,
        Role,
        UserRoles,
    )
    app.security = Security(app, app.user_datastore)
    app.jwt = JWTManager(app)
    create_api(app)

    return app
Exemple #16
0
    def __init__(self, root_path, template_folders, **kwargs):
        """
        work with Flask constructor args
        """
        AdminIndexView = kwargs.get('admin_index_view', None)
        try:
            del kwargs['admin_index_view']
        except:
            pass
        """
        app
        """
        Flask.__init__(self, __name__, **kwargs)
        base.app = self
        base.app.root_path = root_path

        self.config.from_envvar('SETTINGS')
        self.secret_key = 'super secret key'
        """
        set custom jinja loader
        """
        tfs = [base.app.jinja_loader]
        for tf in template_folders:
            tfs.append(jinja2.FileSystemLoader(tf))
        loader = jinja2.ChoiceLoader(tfs)
        base.app.jinja_loader = loader
        """
        cors
        """
        CORS(self,
             resources={
                 r"/v2/*": {
                     "origins": "*"
                 },
                 r"/api/*": {
                     "origins": "*"
                 },
                 r"/spec": {
                     "origins": "*"
                 },
             })
        """
        collect
        """
        Collect(base.app)
        """
        sqlalchemy
        """
        base.db = SQLAlchemy(base.app)
        """
        migrate
        """

        Migrate(base.app, base.db)
        """
        DebugToolbar
        """
        if base.app.config.get('DEBUG', False):
            DebugToolbarExtension(base.app)
        """
        admin
        """
        if not AdminIndexView:
            from .admin_index_view import AdminIndexView

        base_url = self.config.get('FLASK_ADMIN_URL', '/admin')
        base.admin = Admin(
            self,
            url=base_url,
            name=self.config.get('APPNAME', 'flask app'),
            template_mode='bootstrap3',
            base_template='admin/base_.html',
            index_view=AdminIndexView(url=base_url),
        )
        """
        swagger
        """
        from .swagger import get_swaggerui_blueprint
        from flask_swagger import swagger

        SWAGGER_URL = self.config.get('SWAGGER_URL', '/api/docs')
        API_URL = '/spec'

        swaggerui_blueprint = get_swaggerui_blueprint(
            SWAGGER_URL,
            API_URL,
            config={  # Swagger UI config overrides
                'app_name': '%s API' % self.config.get('APPNAME', 'flask app'),
            },
            oauth_config={
                'clientId': "swagger",
            }
        )

        self.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

        @self.route("/spec")
        def spec():
            swag = swagger(self)
            swag_from_file = yaml.load(open('./swagger/spec.yaml'))
            swag.update(swag_from_file)
            return jsonify(swag)

        """
        internal blueprint
        """
        base.internal_bp = Blueprint('internal', 'internal_bp')
        """
        oauth
        """
        from flask_oauthlib.provider import OAuth2Provider

        base.oauth = OAuth2Provider(self)
        from . import oauth
        """
        flask login
        """
        from .models import session, User, Role

        user_datastore = SQLAlchemySessionUserDatastore(session, User, Role)
        security = Security(self, user_datastore)
        """
        modules
        """
        from . import views, admins

        self.register_blueprint(base.internal_bp,
                                url_prefix=base.app.config.get(
                                    'CANTEEN_URL_PREFIX', ''))
Exemple #17
0
def create_app(config, app_name, app=None, auth={}, schemas={}):
    if app is None:
        app = Flask(__name__)
        app.config.from_object(config)
    app.models = f'{app_name}.models'

    @app.route('/media/<path:path>')
    def send_media(path):
        fullPath = f"../{app.config['MEDIA_PATH']}/{path}"
        try:
            return send_file(fullPath)
        except FileNotFoundError:
            return 'No such file', 404

    app.sendmail = lambda to, message: sendmail(app.config, to, message)

    app.collect = Collect(app)
    db.init_app(app)
    app.db = db

    user_module = auth.get('user', None)
    if user_module is None:
        from .models.user import User
    else:
        User = import_module(user_module).User

    role_module = auth.get('role', None)
    if role_module is None:
        from .models.role import Role, UserRoles
    else:
        role_module_imported = import_module(role_module)
        Role = role_module_imported.Role
        UserRoles = role_module_imported.UserRoles

    app.user_datastore = PeeweeUserDatastore(
        app.db,
        User,
        Role,
        UserRoles,
    )

    user_module = schemas.get('user', None)
    if user_module is None:

        class UserSchema(freenit.schemas.user.BaseUserSchema):
            pass
    else:
        UserSchema = import_module(user_module).UserSchema
    setattr(freenit.schemas.user, 'UserSchema', UserSchema)
    PageOutSchema(UserSchema, sys.modules['freenit.schemas.user'])

    role_module = schemas.get('role', None)
    if role_module is None:

        class RoleSchema(freenit.schemas.role.BaseRoleSchema):
            pass
    else:
        RoleSchema = import_module(role_module).RoleSchema
    setattr(freenit.schemas.role, 'RoleSchema', RoleSchema)
    PageOutSchema(RoleSchema, sys.modules['freenit.schemas.role'])

    app.security = Security(app, app.user_datastore)
    app.jwt = JWTManager(app)
    create_api(app)
    app.cors = CORS(app, supports_credentials=True)
    cli.register(app)

    return app
Exemple #18
0
 def run(self):
     collect = Collect()
     collect.init_app(application)
     collect.init_script(manager)
     collect.collect(verbose=True)
Exemple #19
0
def create_app(config, app=None):
    class Result(object):
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)

    if app is None:
        app = Flask(__name__)
        app.config.from_object(config)

    app.admin = Admin(
        name='App',
        # base_template='admin_master.html',
        template_mode='bootstrap3',
        index_view=AdminIndexView(
            # template='admin/my_index.html',
        ),
    )
    app.collect = Collect()
    app.db = Peewee(app)
    db.db = app.db
    app.blueprint = Blueprint(
        'app',
        __name__,
        template_folder='templates',
        static_folder='static',
        static_url_path='/static/app',
    )
    app.register_blueprint(app.blueprint)

    from api import api_v0, api
    app.api = api
    app.register_blueprint(api_v0)
    app.register_blueprint(apidoc.apidoc)

    from .models.auth import User, Role, UserRoles
    app.user_datastore = PeeweeUserDatastore(
        app.db,
        User,
        Role,
        UserRoles,
    )
    app.security = Security(app, app.user_datastore)

    app.admin.init_app(app)

    def authenticate(username, password):
        try:
            user = User.get(email=username)
        except User.DoesNotExist:
            return None
        result = Result(
            id=user.id,
            email=user.email,
        )
        if verify_password(password, user.password):
            return result

    def identity(payload):
        try:
            user = User.get(id=payload['identity'])
        except User.DoesNotExist:
            user = None
        return user

    app.jwt = JWT(app, authenticate, identity)

    from .api import auth, gallery, event, user

    return app
Exemple #20
0
from flask_collect import Collect
from main import app


class Config(object):
    # CRITICAL CONFIG VALUE: This tells Flask-Collect where to put our static files!
    # Standard practice is to use a folder named "static" that resides in the top-level of the project directory.
    # You are not bound to this location, however; you may use basically any directory that you wish.
    COLLECT_STATIC_ROOT = os.path.dirname(__file__) + '/static'
    COLLECT_STORAGE = 'flask_collect.storage.file'


# app = create_app(Config)
config = Config
app.config.from_object(config)

manager = Manager(app)
manager.add_command('runserver', Server(host='127.0.0.1', port=5000))

collect = Collect()
collect.init_app(app)


@manager.command
def collect():
    """Collect static from blueprints. Workaround for issue: https://github.com/klen/Flask-Collect/issues/22"""
    return current_app.extensions['collect'].collect()


if __name__ == "__main__":
    manager.run()
Exemple #21
0
from flask_collect import Collect
import stripe

from blueprints.admin.mixins import IndexAdmin

login = LoginManager()
login.login_view = 'user.login'

db = SQLAlchemy()
migrate = Migrate()
bootstrap = Bootstrap()
admin = Admin(name='flask_shop',
              index_view=IndexAdmin(),
              base_template='admin/base_admin.html',
              endpoint='admin')
collect = Collect()


def make_app(config=None):
    app = Flask(__name__)
    app.config.from_pyfile('configs.py')
    stripe.api_key = app.config['STRIPE_SERCRET_KEY']

    db.init_app(app)
    migrate.init_app(app, db)
    bootstrap.init_app(app)
    login.init_app(app)
    admin.init_app(app)
    collect.init_app(app)
    with app.app_context():
        from blueprints.cart.routes import cart
def collect():
    """Collect Static Files"""
    collect = Collect(app)
    collect.collect(verbose=True)
Exemple #23
0
 def run(self):
     collect = Collect()
     collect.init_app(application)
     collect.init_script(manager)
     collect.collect(verbose=True)
Exemple #24
0
class InvenioAssets(object):
    """Invenio asset extension."""

    def __init__(self, app=None, **kwargs):
        r"""Extension initialization.

        :param app: An instance of :class:`~flask.Flask`.
        :param \**kwargs: Keyword arguments are passed to ``init_app`` method.
        """
        self.env = Environment()
        self.collect = Collect()
        self.webpack = FlaskWebpackExt()

        if app:
            self.init_app(app, **kwargs)

    def init_app(self, app, entry_point_group='invenio_assets.bundles',
                 **kwargs):
        """Initialize application object.

        :param app: An instance of :class:`~flask.Flask`.
        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        self.init_config(app)
        self.env.init_app(app)
        self.collect.init_app(app)
        self.webpack.init_app(app)

        if entry_point_group:
            self.load_entrypoint(entry_point_group)

        app.extensions['invenio-assets'] = self

    def init_config(self, app):
        """Initialize configuration.

        :param app: An instance of :class:`~flask.Flask`.
        """
        app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')
        app.config.setdefault(
            'COLLECT_FILTER', partial(collect_staticroot_removal, app))
        app.config.setdefault(
            'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')

    def load_entrypoint(self, entry_point_group):
        """Load entrypoint.

        :param entry_point_group: A name of entry point group used to load
            ``webassets`` bundles.

        .. versionchanged:: 1.0.0b2
           The *entrypoint* has been renamed to *entry_point_group*.
        """
        for ep in pkg_resources.iter_entry_points(entry_point_group):
            self.env.register(ep.name, ep.load())
Exemple #25
0
from __future__ import unicode_literals
from flask_collect import Collect
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from app import app, db

__author__ = 'lexxodus'

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

collect = Collect()
collect.init_app(app)
collect.init_script(manager)

if __name__ == '__main__':
    manager.run()
Exemple #26
0
from flask_cache import Cache
from dealer.contrib.flask import Dealer

from .app import create_app


babel = Babel()
cache = Cache()
db = SQLAlchemy()
dealer = Dealer()
mail = Mail()

manager = Manager(create_app)
manager.add_option("-c", "--config", dest="config", required=False)

collect = Collect()
collect.init_script(manager)


def config_extensions(app):
    " Init application with extensions. "

    cache.init_app(app)
    collect.init_app(app)
    db.init_app(app)
    dealer.init_app(app)
    mail.init_app(app)

    DebugToolbarExtension(app)

    config_babel(app)
Exemple #27
0
def collect():
    """Collect Static Files"""
    collect = Collect(app)
    collect.collect(verbose=True)
Exemple #28
0
class TildaCenter(object):
    """
    Tilda Center APP
    """
    class Result(object):
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)

    admin = Admin(
        name='TildaCenter',
        # base_template='admin_master.html',
        template_mode='bootstrap3',
        index_view=AdminIndexView(
            # template='admin/my_index.html',
        ),
    )
    api = None
    app = None
    blueprint = None
    collect = Collect()
    cors = None
    db = None
    jwt = JWT()
    security = Security()
    user_datastore = None

    def __init__(self, app=None):
        global current_app
        current_app = self
        self.app = app
        if self.app is not None:
            self.init_app(app)

    def init_app(self, app):
        self.app = app
        self.jwt.init_app(app)
        self.blueprint = Blueprint(
            'tilda_center',
            __name__,
            template_folder='templates',
            static_folder='static',
            static_url_path='/static/tilda_center',
        )
        self.app.register_blueprint(self.blueprint)

        from api import api_v0, api
        self.api = api
        self.app.register_blueprint(api_v0)
        self.app.register_blueprint(apidoc.apidoc)
        self.cors = CORS(self.app, resources=self.app.config['CORS_RESOURCES'])

        self.db = Database(self.app)

        self.user_datastore = PeeweeUserDatastore(
            self.db,
            User,
            Role,
            UserRoles,
        )

        self.security.init_app(
            self.app,
            self.user_datastore,
        )

        self.admin.init_app(self.app)

    @jwt.authentication_handler
    def authenticate(username, password):
        try:
            user = User.get(email=username)
        except User.DoesNotExist:
            return None
        result = TildaCenter.Result(
            id=user.id,
            email=user.email,
        )
        if verify_password(password, user.password):
            return result

    @jwt.identity_handler
    def identity(payload):
        try:
            user = User.get(id=payload['identity'])
        except User.DoesNotExist:
            user = None
        return user
import handlers
from config import get_config
from bulls_and_cows import routes as bulls_and_cows_route
from bulls_and_cows import tasks as bulls_and_cows_tasks
from bulls_and_cows.utils import account as bulls_and_cows_utils_account
from swagger import routes as swagger_route
from logger import init_logger
from utils.dramatiq_utils import LazyActor

config = get_config()
init_logger(config.LOGGER_LEVEL)

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

collect = Collect(app)

broker = RabbitmqBroker(
    host=config.RABBITMQ_HOST,
    port=config.RABBITMQ_PORT,
    credentials=PlainCredentials(config.RABBITMQ_USER,
                                 config.RABBITMQ_PASSWORD),
    heartbeat=5,
    connection_attempts=5,
    blocked_connection_timeout=30,
)
broker.add_middleware(handlers.AppContextDramatiqMiddleware(app))
dramatiq.set_broker(broker)
LazyActor.init_all_actors()

# DB session config
from flask_script import Manager
from flask_collect import Collect
from flask_migrate import Migrate, MigrateCommand

from tvseries import create_app
from tvseries.ext import db
from tvseries.config import DevelopmentConfig

app = create_app(config=DevelopmentConfig)
manager = Manager(app)

# migrate command
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

# collect command
collect = Collect()
collect.init_app(app)


@manager.command
def collect():
    """Collect static from blueprints."""
    return app.extensions['collect'].collect()

if __name__ == "__main__":
    manager.run()
Exemple #31
0
import os
import sys

from webfest.base.factory import create_app

from flask_collect import Collect
from flask_script import Manager, Server, Shell, prompt_choices
from flask_script.commands import ShowUrls, Clean
from flask_assets import ManageAssets

env = os.environ.get('webfest_ENV', 'dev')
instance_path = ""
if env == "Heroku":
    instance_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                 "webfest", "base", "instance")

app = create_app(instance_path=instance_path, env=env)

manager = Manager(app=app)
manager.add_command("show-urls", ShowUrls())
manager.add_command("clean", Clean())
manager.add_command("shell", Shell())
manager.add_command("assets", ManageAssets())

collect = Collect()
collect.init_app(app)
collect.init_script(manager)

if __name__ == "__main__":
    manager.run()
Exemple #32
0
class OneLove(object):
    class Result(object):
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)

    api = None
    app = None
    blueprint = None
    collect = Collect()
    db = MongoEngine()
    jwt = JWT()
    mail = Mail()
    security = Security()
    socketio = None
    toolbar = None
    user_datastore = None

    def __init__(self, app=None):
        if app is not None:
            if app.config['DEBUG']:
                self.cors = CORS()
            self.init_app(app)

    def init_app(self, app):
        global current_app
        current_app = self
        self.app = app
        if app.config['DEBUG']:
            self.cors.init_app(
                self.app,
                resources={r'/api/*': {
                    'origins': '*'
                }},
            )

        from api import api_v0, api
        self.api = api

        self.blueprint = Blueprint(
            'onelove',
            __name__,
            template_folder='templates',
            static_folder='static',
            static_url_path='/static/onelove',
        )
        self.app.register_blueprint(self.blueprint)

        self.app.register_blueprint(api_v0, url_prefix='/api/v0')
        self.app.register_blueprint(apidoc.apidoc)

        self.mail.init_app(self.app)

        self.db.init_app(self.app)

        self.user_datastore = MongoEngineUserDatastore(
            self.db,
            User,
            Role,
        )
        self.security.init_app(
            self.app,
            self.user_datastore,
        )

        self.jwt.init_app(self.app)
        self.collect.init_app(self.app)

        if self.app.config.get('DEBUG_TB_PANELS', False):
            from flask_debugtoolbar import DebugToolbarExtension
            from flask_debug_api import DebugAPIExtension
            self.toolbar = DebugToolbarExtension(self.app)
            self.toolbar = DebugAPIExtension(self.app)

        self.socketio = SocketIO(self.app, logger=True)
        self.app.onelove = self

    @jwt.authentication_handler
    def authenticate(username, password):
        try:
            user = User.objects.get(email=username)
        except User.DoesNotExist:
            return None
        result = OneLove.Result(
            id=str(user.id),
            email=user.email,
            first_name=user.first_name,
            last_name=user.last_name,
        )
        if verify_password(password, user.password):
            return result

    @jwt.identity_handler
    def identity(payload):
        try:
            user = User.objects.get(id=payload['identity'])
        except User.DoesNotExist:
            user = None
        return user