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.ext.collect.storage.test' collect = Collect(app) test = collect.collect(verbose=True) self.assertEqual(len(test), 3) rmtree(static_root)
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.ext.collect.storage.test' collect = Collect(app) test = list(collect.collect(verbose=True)) self.assertEqual(len(test), 3) 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)
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)
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.ext.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)
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.ext.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.ext.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)
def create_app(config, app=None): if app is None: app = Flask(__name__) app.config.from_object(config) @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: sm(app.config, to, message) app.collect = Collect(app) db.init_app(app) app.db = db from .models.user import User from .models.role import 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) app.cors = CORS(app, supports_credentials=True) cli.register(app) return app
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.collect = Collect(app) db.init_app(app) app.db = db app.blueprint = Blueprint( 'app', __name__, template_folder='templates', static_folder='static', static_url_path='/static/app', ) app.register_blueprint(app.blueprint) 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
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.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
def __init__(self, app=None, **kwargs): """Extension initialization.""" self.env = Environment() self.collect = Collect() if app: self.init_app(app, **kwargs)
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.ext.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.ext.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)
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__(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, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. .. versionchanged:: 1.0.0b2 The *entrypoint* has been renamed to *entry_point_group*. """ self.init_config(app) self.collect = Collect(app) self.webpack = FlaskWebpackExt(app) app.extensions['invenio-assets'] = self
def create_app(config={}, testing=False): app = flask.Flask(__name__, instance_relative_config=True) app.config.update(DEFAULT_CONFIG) if testing: app.testing = True app.config.from_pyfile('test_settings.py', silent=True) else: app.config.from_pyfile('settings.py') app.config.update(config) assets_env.init_app(app) db.init_app(app) app.register_blueprint(layout) app.register_blueprint(summary) app.register_blueprint(report) app.register_blueprint(progress) if not app.testing: app.register_blueprint(auth) app.register_blueprint(comments) app.register_blueprint(common) app.register_blueprint(wiki) app.register_blueprint(maps) app.register_blueprint(factsheet) login_manager.init_app(app) login_manager.login_view = 'login' Mail().init_app(app) collect = Collect() collect.init_app(app) app.add_template_global(inject_static_file) return (app, collect) @app.route('/temp.html') def temp(): return flask.render_template('temp.html') url_prefix = app.config.get('URL_PREFIX') if url_prefix: app.wsgi_app = create_url_prefix_middleware(app.wsgi_app, url_prefix) if app.config.get('SENTRY_DSN'): from raven.contrib.flask import Sentry Sentry(app) if app.config.get('AUTH_LOG_FILE'): configure_auth_log_hander(app.config.get('AUTH_LOG_FILE')) return app
def create_app(test_config=None): from . import db from . import importer from . import view # this is Dockerfile dependent now... app = Flask(__name__, instance_path='/home/web/instance') instance_path = Path(app.instance_path) db_config = { 'name': os.getenv('DATABASE'), 'engine': 'playhouse.pool.PostgresqlDatabase', 'user': os.getenv('POSTGRES_USER'), 'password': os.getenv('POSTGRES_PASSWORD'), 'host': os.getenv('DATABASE_HOST'), } app.config.from_mapping( DATABASE=db_config, SECRET_KEY=os.getenv('SECRET_KEY'), COLLECT_STATIC_ROOT=str(instance_path / 'static'), ) if test_config: app.config.from_mapping(test_config) app.register_blueprint(view.app_blueprint) api = Api(app, '/api/v1') api.add_resource(view.WorksList, "/works") api.add_resource(view.WorksDetail, "/works/<string:iswc>") db.db_wrapper.init_app(app) db.db_wrapper.database.close() db.init_app(app) importer.init_app(app) collect = Collect() collect.init_app(app) return app
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
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.ext.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)
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
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
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()
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
def run(self): collect = Collect() collect.init_app(application) collect.init_script(manager) collect.collect(verbose=True)
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', ''))
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
def collect(): """Collect Static Files""" collect = Collect(app) collect.collect(verbose=True)
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
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