def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs)
class INSPIRETheme(object): """Invenio theme extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs) self.setup_app(app) def init_app(self, app, assets=None, **kwargs): """Initialize application object.""" self.init_config(app.config) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_app(app) app.register_blueprint(blueprint) # Configure Jinja2 environment. app.jinja_env.add_extension('jinja2.ext.do') app.jinja_env.lstrip_blocks = True app.jinja_env.trim_blocks = True # Register errors handlers. app.register_error_handler(401, unauthorized) app.register_error_handler(403, insufficient_permissions) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) user_logged_in.connect(load_user_collections, app) # Save reference to self on object app.extensions['inspire-theme'] = self def init_config(self, config): """Initialize configuration.""" # Set JS bundles to exclude for purpose of avoiding double jQuery etc. # when other modules are building their JS bundles. config.setdefault("THEME_BASE_BUNDLES_EXCLUDE_JS", [js]) config.setdefault("BASE_TEMPLATE", "inspirehep_theme/page.html") def setup_app(self, app): """Initialize Gravatar extension.""" gravatar = Gravatar(app, size=app.config.get('GRAVATAR_SIZE', 100), rating=app.config.get('GRAVATAR_RATING', 'g'), default=app.config.get( 'GRAVATAR_DEFAULT', 'retro'), force_default=False, force_lower=False) del gravatar return app
class INSPIRETheme(object): """Invenio theme extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs) self.setup_app(app) def init_app(self, app, assets=None, **kwargs): """Initialize application object.""" self.init_config(app.config) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_app(app) app.register_blueprint(blueprint) # Configure Jinja2 environment. app.jinja_env.add_extension('jinja2.ext.do') app.jinja_env.lstrip_blocks = True app.jinja_env.trim_blocks = True # Register errors handlers. app.register_error_handler(401, unauthorized) app.register_error_handler(403, insufficient_permissions) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) user_logged_in.connect(load_user_collections, app) # Save reference to self on object app.extensions['inspire-theme'] = self def init_config(self, config): """Initialize configuration.""" # Set JS bundles to exclude for purpose of avoiding double jQuery etc. # when other modules are building their JS bundles. config.setdefault("THEME_BASE_BUNDLES_EXCLUDE_JS", [js]) config.setdefault("BASE_TEMPLATE", "inspirehep_theme/page.html") def setup_app(self, app): """Initialize Gravatar extension.""" gravatar = Gravatar(app, size=app.config.get('GRAVATAR_SIZE', 100), rating=app.config.get('GRAVATAR_RATING', 'g'), default=app.config.get('GRAVATAR_DEFAULT', 'retro'), force_default=False, force_lower=False) del gravatar return app
def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() self.weblinks = self.init_weblinks_dictionary() if app: self.init_app(app, **kwargs) self.setup_app(app)
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.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs)
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( # HTTPretty doesn't play well with Redis. # See gabrielfalcao/HTTPretty#110 CACHE_TYPE='simple', CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', GITHUB_SHIELDSIO_BASE_URL='http://example.org/badge/', GITHUB_APP_CREDENTIALS=dict( consumer_key='changeme', consumer_secret='changeme', ), LOGIN_DISABLED=False, OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE='simple', OAUTHCLIENT_REMOTE_APPS=dict( github=REMOTE_APP, ), SECRET_KEY='test_key', SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], TESTING=True, WTF_CSRF_ENABLED=False, ) app.url_map.converters['pid'] = PIDConverter FlaskCLI(app) celeryext = FlaskCeleryExt(app) celeryext.celery.flask_app = app # Make sure both apps are the same! Babel(app) Mail(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioAccounts(app) app.register_blueprint(accounts_blueprint) InvenioOAuthClient(app) app.register_blueprint(oauthclient_blueprint) InvenioOAuth2Server(app) app.register_blueprint(server_blueprint) app.register_blueprint(settings_blueprint) InvenioPIDStore(app) InvenioRecordsREST(app) InvenioDepositREST(app) InvenioWebhooks(app) app.register_blueprint(webhooks_blueprint) InvenioGitHub(app) with app.app_context(): yield app shutil.rmtree(instance_path)
def create_app(): app = Flask(__name__) app.config.from_pyfile('config.py') # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db.init_app(app) migrate = Migrate(app, db) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'user.login' app.register_blueprint(user_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(cont_blueprint) Breadcrumbs(app=app) @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) @app.route('/') @register_breadcrumb(app, '.', 'Главная') def index(): if session is None: session["city"] = "no" page_title = "Диск-гольф Россия" return render_template('index.html', page_title=page_title) return app
def app(request): """Flask application fixture.""" app = Flask('testapp') app.config.update( TESTING=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SERVER_NAME='localhost', ) Babel(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioCollections(app) InvenioRecords(app) app.register_blueprint(blueprint) with app.app_context(): if str(db.engine.url) != 'sqlite://' and \ not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() def teardown(): with app.app_context(): if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) request.addfinalizer(teardown) with app.app_context(): db.create_all() return app
def test_create_menu_first(self): from flask_menu import Menu menu = Menu(self.app) entry = self.app.extensions['menu'] # it must reuse existing menu extension. Breadcrumbs(self.app, init_menu=False) assert entry == self.app.extensions['menu']
def init_app(app): app.config.update( DB_VERSIONING=True, LOGIN_DISABLED=False, MAIL_SUPPRESS_SEND=True, OAUTH2_CACHE_TYPE='simple', OAUTHLIB_INSECURE_TRANSPORT=True, SECRET_KEY='CHANGE_ME', SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO', SECURITY_PASSWORD_SCHEMES=['plaintext'], SQLALCHEMY_DATABASE_URI=os.getenv( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///' + os.path.join(instance_path, 'test.db')), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, WTF_CSRF_ENABLED=False, ) Babel(app) Mail(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioOAuth2Server(app)
def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs)
def app(): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app_ = Flask(__name__, instance_path=instance_path) app_.config.update( CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', JSONSCHEMAS_URL_SCHEME='http', SECRET_KEY='CHANGE_ME', SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_ECHO=False, TESTING=True, WTF_CSRF_ENABLED=False, DEPOSIT_SEARCH_API='/api/search', SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE='simple', ) app_.url_map.converters['pid'] = PIDConverter FlaskCLI(app_) Babel(app_) FlaskCeleryExt(app_) InvenioDB(app_) Breadcrumbs(app_) InvenioAccounts(app_) InvenioAccess(app_) app_.register_blueprint(accounts_blueprint) InvenioAssets(app_) InvenioJSONSchemas(app_) InvenioSearch(app_) InvenioRecords(app_) app_.url_map.converters['pid'] = PIDConverter InvenioRecordsREST(app_) InvenioPIDStore(app_) InvenioIndexer(app_) InvenioDeposit(app_) InvenioSearchUI(app_) InvenioRecordsUI(app_) InvenioFilesREST(app_) OAuth2Provider(app_) InvenioOAuth2Server(app_) InvenioOAuth2ServerREST(app_) app_.register_blueprint(oauth2server_settings_blueprint) InvenioDepositREST(app_) with app_.app_context(): yield app_ shutil.rmtree(instance_path)
def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() self.weblinks = self.init_weblinks_dictionary() if app: self.init_app(app, **kwargs) self.setup_app(app)
class InvenioTheme(object): """Invenio theme extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs) def init_app(self, app, assets=None, **kwargs): """Initialize application object.""" self.init_config(app.config) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_app(app) # Register blueprint in order to register template and static folder. blueprint = Blueprint( 'invenio_theme', __name__, template_folder='templates', static_folder='static', ) app.register_blueprint(blueprint) # Save reference to self on object app.extensions['invenio-theme'] = self def init_config(self, config): """Initialize configuration.""" config.setdefault("THEME_SITENAME", _("Invenio")) config.setdefault("THEME_GOOGLE_SITE_VERIFICATION", []) config.setdefault('BASE_TEMPLATE', 'invenio_theme/page.html') config.setdefault( 'THEME_BASE_TEMPLATE', config['BASE_TEMPLATE']) config.setdefault( 'THEME_ERROR_TEMPLATE', 'invenio_theme/error.html')
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.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs)
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app_ = Flask(__name__, instance_path=instance_path) app_.config.update( SQLALCHEMY_DATABASE_URI=os.getenv( 'SQLALCHEMY_DATABASE_URI', 'postgresql+psycopg2://localhost/circulation_test'), OAUTH2SERVER_CLIENT_ID_SALT_LEN=40, OAUTH2SERVER_CLIENT_SECRET_SALT_LEN=60, OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN=60, SECRET_KEY='changeme', SERVER_NAME='localhost:5000', REPLACE_REFS=False, TESTING=True, CIRCULATION_ACTION_LOAN_URL=( '/hooks/receivers/circulation_loan/events/'), CIRCULATION_ACTION_REQUEST_URL=( '/hooks/receivers/circulation_request/events/'), CIRCULATION_ACTION_RETURN_URL=( '/hooks/receivers/circulation_return/events/'), ) app_.url_map.converters['pid'] = PIDConverter Babel(app_) Menu(app_) Breadcrumbs(app_) InvenioAccounts(app_) InvenioAssets(app_) InvenioDB(app_) InvenioIndexer(app_) InvenioJSONSchemas(app_) InvenioPIDStore(app_) InvenioRecords(app_) InvenioRecordsREST(app_) InvenioWebhooks(app_) InvenioOAuth2Server(app_) InvenioCirculation(app_) InvenioCirculationREST(app_) InvenioSearch(app_) app_.register_blueprint(server_blueprint) app_.register_blueprint(settings_blueprint) app_.register_blueprint(webhooks_blueprint) app_.register_blueprint(circulation_blueprint) with app_.app_context(): yield app_ shutil.rmtree(instance_path)
def extensions(app): """ Register 0 or more extensions (mutates the app passed in). :param app: Flask application instance :return: None """ debug_toolbar.init_app(app) csrf.init_app(app) db.init_app(app) login_manager.init_app(app) Breadcrumbs(app=app) return None
def app(request): """Flask application fixture.""" app = Flask('testapp') app.config.update( ACCOUNTS_JWT_ENABLE=False, BROKER_TRANSPORT='redis', CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', CELERY_TRACK_STARTED=True, LOGIN_DISABLED=False, OAUTH2_CACHE_TYPE='simple', OAUTHLIB_INSECURE_TRANSPORT=True, SECRET_KEY='test_key', SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), TESTING=True, WTF_CSRF_ENABLED=False, ) celeryext = FlaskCeleryExt(app) celeryext.celery.flask_app = app # Make sure both apps are the same! Babel(app) Mail(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioAccounts(app) app.register_blueprint(accounts_blueprint) InvenioOAuth2Server(app) InvenioOAuth2ServerREST(app) app.register_blueprint(server_blueprint) app.register_blueprint(settings_blueprint) InvenioWebhooks(app) app.register_blueprint(blueprint) with app.app_context(): if not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() def teardown(): with app.app_context(): drop_database(str(db.engine.url)) request.addfinalizer(teardown) return app
def app(base_app): """Flask full application fixture.""" Breadcrumbs(base_app) InvenioDB(base_app) InvenioAccess(base_app) InvenioAccounts(base_app) InvenioFilesREST(base_app) InvenioOAuth2Server(base_app) InvenioOAuth2ServerREST(base_app) InvenioREST(base_app) InvenioSIPStore(base_app) base_app.register_blueprint(server_blueprint) base_app.register_blueprint(blueprint) with base_app.app_context(): yield base_app
def create_app(): app = Flask(__name__) Breadcrumbs(app=app) load_dotenv() app.config['API_URL'] = os.getenv('API_URL') csrf = CSRFProtect(app) app.config["SECRET_KEY"] = os.getenv('SECRET_KEY') login_manager.init_app(app) from main.routes import main, unverified_seism, user, verified_seism, login, sensor, home app.register_blueprint(routes.login.log) app.register_blueprint(routes.main.main) app.register_blueprint(routes.unverified_seism.unverified_seism) app.register_blueprint(routes.verified_seism.verified_seism) app.register_blueprint(routes.sensor.sensor) app.register_blueprint(routes.user.user) app.register_blueprint(routes.home.home) return app
def app(instance_path, static_folder): """Flask application fixture.""" app = Flask( 'testapp', instance_path=instance_path, static_folder=static_folder, ) app.config.from_object(config) app.config.update( TESTING=True, BASE_TEMPLATE='cernopendata_pages/base.html', ) Babel(app) Menu(app) Breadcrumbs(app) app.register_blueprint(blueprint) return app
def init_app(app_): app_.config.update( CELERY_ALWAYS_EAGER=False, CELERY_CACHE_BACKEND="memory", CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND="cache", JSONSCHEMAS_URL_SCHEME="http", SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO", SQLALCHEMY_DATABASE_URI=os.environ.get("SQLALCHEMY_DATABASE_URI", "sqlite:///test.db"), SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_ECHO=False, TESTING=True, WTF_CSRF_ENABLED=False, DEPOSIT_SEARCH_API="/api/search", SECURITY_PASSWORD_HASH="plaintext", SECURITY_PASSWORD_SCHEMES=["plaintext"], SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], THEME_SITENAME="Test Site", OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE="simple", ACCOUNTS_JWT_ENABLE=False, # This allows access to files across all of invenio-files-rest FILES_REST_PERMISSION_FACTORY=lambda *a, **kw: type( "Allow", (object, ), {"can": lambda self: True})(), FILES_REST_MULTIPART_CHUNKSIZE_MIN=10, ) Babel(app_) FlaskCeleryExt(app_) Breadcrumbs(app_) OAuth2Provider(app_) InvenioDB(app_) InvenioAccounts(app_) InvenioAccess(app_) InvenioIndexer(app_) InvenioJSONSchemas(app_) InvenioOAuth2Server(app_) InvenioPIDStore(app_) InvenioRecords(app_) search = InvenioSearch(app_) search.register_mappings("deposits", "invenio_deposit.mappings")
def create_app(): app = Flask(__name__) load_dotenv() # Configs app.config["API_URL"] = os.getenv("API_URL") app.config["JWT_ACCESS_TOKEN_EXPIRES"] = 10 csrf = CSRFProtect(app) app.config["SECRET_KEY"] = os.getenv("SECRET_KEY") Breadcrumbs(app=app) login_manager.init_app(app) # Registrar los Blueprints from main.routes import main, verified_seism, unverified_seism, user, sensor app.register_blueprint(routes.main.main) app.register_blueprint(routes.verified_seism.verified_seism) app.register_blueprint(routes.unverified_seism.unverified_seism) app.register_blueprint(routes.user.user) app.register_blueprint(routes.sensor.sensor) return app
def app(request): """ Flask application fixture. :param request: Request. :return: App object. """ instance_path = tempfile.mkdtemp() app = Flask('weko_groups_app', instance_path=instance_path) app.config.update( LOGIN_DISABLED=False, MAIL_SUPPRESS_SEND=True, SECRET_KEY='1qertgyujk345678ijk', SQLALCHEMY_DATABASE_URI='sqlite:///weko_groups.db', SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, WTF_CSRF_ENABLED=False, ) Babel(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioAccounts(app) WekoGroups(app) with app.app_context(): if str(db.engine.url) != 'sqlite://' and \ not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() def teardown(): with app.app_context(): if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) shutil.rmtree(instance_path) request.addfinalizer(teardown) return app
def init_app(app_): app_.config.update( CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', JSONSCHEMAS_URL_SCHEME='http', SECRET_KEY='CHANGE_ME', SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO', SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_ECHO=False, TESTING=True, WTF_CSRF_ENABLED=False, DEPOSIT_SEARCH_API='/api/search', SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE='simple', ACCOUNTS_JWT_ENABLE=False, ) Babel(app_) FlaskCeleryExt(app_) Breadcrumbs(app_) OAuth2Provider(app_) InvenioDB(app_) InvenioAccounts(app_) InvenioAccess(app_) InvenioIndexer(app_) InvenioJSONSchemas(app_) InvenioOAuth2Server(app_) InvenioFilesREST(app_) InvenioPIDStore(app_) InvenioRecords(app_) search = InvenioSearch(app_) search.register_mappings('deposits', 'invenio_deposit.mappings')
def app(request): """Flask application fixture.""" app = Flask('testapp') app.config.update( TESTING=True, LOGIN_DISABLED=False, SECRET_KEY='test_key', SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), WTF_CSRF_ENABLED=False, OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE='simple', SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], ) FlaskCLI(app) Babel(app) Mail(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioAccounts(app) app.register_blueprint(accounts_blueprint) InvenioOAuth2Server(app) app.register_blueprint(server_blueprint) app.register_blueprint(settings_blueprint) with app.app_context(): db.create_all() def teardown(): with app.app_context(): db.drop_all() request.addfinalizer(teardown) return app
def create_app(use_eventlet=True): app = Flask(__name__) envvars = [ 'SECRET_KEY', 'FLASK_ENV', 'SQLALCHEMY_DATABASE_URI', 'SQLALCHEMY_TRACK_MODIFICATIONS', 'CELERY_RESULT_BACKEND', 'CELERY_BROKER_URL' ] for envvar in envvars: app.config[envvar] = os.getenv(envvar) db.init_app(app) migrate = Migrate(app, db) Breadcrumbs(app) configure_celery(app) if use_eventlet: socketio.init_app(app, **socketio_opts) else: socketio.init_app(app, async_mode='threading', **socketio_opts) app.register_blueprint(bp) return app
# # You should have received a copy of the GNU Affero General Public License # along with WebPsi. If not, see <https://www.gnu.org/licenses/>. from flask import Flask from flask_breadcrumbs import Breadcrumbs, default_breadcrumb_root from flask_sockets import Sockets from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler from webpsi.views import home, classic_reg, singlebit_pk app = Flask(__name__) sockets = Sockets(app) Breadcrumbs(app) default_breadcrumb_root(home.blueprint, '.') app.register_blueprint(home.blueprint) app.register_blueprint(classic_reg.blueprint, url_prefix='/classic_reg') sockets.register_blueprint(classic_reg.ws_blueprint, url_prefix='/classic_reg') app.register_blueprint(singlebit_pk.blueprint, url_prefix='/singlebit_pk') sockets.register_blueprint(singlebit_pk.ws_blueprint, url_prefix='/singlebit_pk') server = pywsgi.WSGIServer(('0.0.0.0', 58700), application=app, handler_class=WebSocketHandler) server.serve_forever()
def create_app(environment='development'): from config import config from .views import main_blueprint from .auth.views import auth_blueprint from .settings.views import settings_blueprint from .links.views import links_blueprint from .auth.models import User, AnonymousUser # Setup configuration dictConfig({ 'version': 1, 'formatters': { 'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', } }, 'handlers': { 'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' } }, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] } }) # Instantiate app. app = Flask(__name__) with app.app_context(): from .filters import humanize_number # noqa # Compile the SASS dirname = ('app/static/sass', 'app/static/css') sass.compile(dirname=dirname, output_style='compressed') # Initialise the breadcrumb system. Breadcrumbs(app=app) # Set app config. env = os.environ.get('FLASK_ENV', environment) app.config.from_object(config[env]) config[env].configure(app) # Set up extensions. db.init_app(app) login_manager.init_app(app) # Register blueprints. app.register_blueprint(links_blueprint) app.register_blueprint(auth_blueprint) app.register_blueprint(settings_blueprint) app.register_blueprint(main_blueprint) # Set up flask login. @login_manager.user_loader def get_user(id): return User.query.get(int(id)) login_manager.login_view = 'auth.login' login_manager.login_message_category = 'info' login_manager.anonymous_user = AnonymousUser # Error handlers. @app.errorhandler(HTTPException) def handle_http_error(exc): return render_template('error.html', error=exc), exc.code return app
from flask_breadcrumbs import Breadcrumbs from flask_login import LoginManager from flask_mail import Mail from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from sparkpost import SparkPost db = SQLAlchemy() login_manager = LoginManager() migrate = Migrate() mail = Mail() sparkpost = SparkPost() breadcrumbs = Breadcrumbs()
class InvenioTheme(object): """Invenio theme 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.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs) def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ self.init_config(app.config) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_app(app) # Register blueprint in order to register template and static folder. blueprint = Blueprint( 'invenio_theme', __name__, template_folder='templates', static_folder='static', ) app.register_blueprint(blueprint) # Initialize breadcrumbs. item = self.menu.submenu('breadcrumbs') item.register(app.config['THEME_BREADCRUMB_ROOT_ENDPOINT'], _('Home')) # Register errors handlers. app.register_error_handler(401, unauthorized) app.register_error_handler(403, insufficient_permissions) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) # Save reference to self on object app.extensions['invenio-theme'] = self def init_config(self, config): """Initialize configuration. :param config: A dict like object where default values should be set. """ config.setdefault('SASS_BIN', 'node-sass') config.setdefault('THEME_SITENAME', 'Invenio') config.setdefault('THEME_LOGO', 'images/invenio-color.svg') config.setdefault('THEME_LOGO_ADMIN', 'images/invenio-white.svg') config.setdefault('REQUIREJS_CONFIG', 'js/build.js') config.setdefault('THEME_GOOGLE_SITE_VERIFICATION', []) config.setdefault('BASE_TEMPLATE', 'invenio_theme/page.html') config.setdefault( 'COVER_TEMPLATE', 'invenio_theme/page_cover.html') config.setdefault( 'SETTINGS_TEMPLATE', 'invenio_theme/page_settings.html') config.setdefault( 'HEADER_TEMPLATE', 'invenio_theme/header.html') config.setdefault( 'THEME_BASE_TEMPLATE', config['BASE_TEMPLATE']) config.setdefault( 'THEME_COVER_TEMPLATE', config['COVER_TEMPLATE']) config.setdefault( 'THEME_SETTINGS_TEMPLATE', config['SETTINGS_TEMPLATE']) config.setdefault( 'THEME_ERROR_TEMPLATE', 'invenio_theme/error.html') config.setdefault( 'THEME_401_TEMPLATE', 'invenio_theme/401.html') config.setdefault( 'THEME_403_TEMPLATE', 'invenio_theme/403.html') config.setdefault( 'THEME_404_TEMPLATE', 'invenio_theme/404.html') config.setdefault( 'THEME_500_TEMPLATE', 'invenio_theme/500.html') config.setdefault('THEME_SEARCHBAR', True) config.setdefault('THEME_SEARCH_ENDPOINT', '/search') config.setdefault('THEME_BREADCRUMB_ROOT_ENDPOINT', '') # Integration with Invenio-Admin: config.setdefault( 'ADMIN_BASE_TEMPLATE', 'invenio_theme/admin.html')
def setUp(self): """Prepares breadcrumbs tree. Example:: test |-- level2 | |-- level3 | |-- level3B foo (*blueprint*) |-- bar """ if sys.version_info == (3, 4, 0, 'final', 0) or \ sys.version_info == (3, 4, 1, 'final', 0): from unittest import SkipTest raise SkipTest('Python 3.4.[01] detected') super(TestBreadcrumbs, self).setUp() self.breadcrumbs = Breadcrumbs(self.app, init_menu=True) @self.app.route('/test') @register_breadcrumb(self.app, '.', 'Test') def test(): return 'test' @self.app.route('/level2') @register_breadcrumb(self.app, '.level2', 'Level 2') def level2(): return 'level2' @self.app.route('/level3') @register_breadcrumb(self.app, '.level2.level3', 'Level 3') def level3(): return 'level3' @self.app.route('/level3B') @register_breadcrumb(self.app, 'breadcrumbs.level2.level3B', 'Level 3B') def level3B(): return render_template_string(breadcrumbs_tpl) @self.app.route('/missing') def missing(): return 'missing' self.foo = Blueprint('foo', 'foo', url_prefix='/foo') @self.foo.route('/') @register_breadcrumb(self.foo, '.bar', 'Bar') def bar(): return 'bar' @self.foo.route('/baz') @register_breadcrumb(self.foo, '.baz', 'Baz') def baz(): return render_template_string(breadcrumbs_tpl) @self.foo.route('/missing') def missing2(): return 'missing2' self.app.register_blueprint(self.foo)
class INSPIRETheme(object): """Invenio theme extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() self.weblinks = self.init_weblinks_dictionary() if app: self.init_app(app, **kwargs) self.setup_app(app) def init_app(self, app, assets=None, **kwargs): """Initialize application object.""" self.init_config(app.config) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_app(app) app.register_blueprint(blueprint) # Add Jinja2 extensions. app.jinja_env.add_extension('jinja2.ext.do') # Register errors handlers. app.register_error_handler(401, unauthorized) app.register_error_handler(403, insufficient_permissions) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) # Save reference to self on object app.extensions['inspire-theme'] = self def init_config(self, config): """Initialize configuration.""" from .bundles import js # Set JS bundles to exclude for purpose of avoiding double jQuery etc. # when other modules are building their JS bundles. config.setdefault("THEME_BASE_BUNDLES_EXCLUDE_JS", [js]) config.setdefault("BASE_TEMPLATE", "inspirehep_theme/page.html") def setup_app(self, app): """Initialize Gravatar extension.""" from flask_gravatar import Gravatar gravatar = Gravatar(app, size=app.config.get('GRAVATAR_SIZE', 100), rating=app.config.get('GRAVATAR_RATING', 'g'), default=app.config.get( 'GRAVATAR_DEFAULT', 'retro'), force_default=False, force_lower=False) del gravatar return app def init_weblinks_dictionary(self): """Initialize the dictionary for HEP detailed record external links.""" weblinks_dictionary = {} with open(resource_filename('inspirehep', 'kbs/weblinks.kb'), 'r') as kb_file: for line in kb_file: (key, val) = line.split('---') weblinks_dictionary[key] = val return weblinks_dictionary
def test_init_menu(self): Breadcrumbs(self.app) assert 'menu' in self.app.extensions
def test_simple_app(self): Breadcrumbs(self.app, init_menu=True) with self.app.test_client() as c: c.get('/test') self.assertEqual(current_path, 'breadcrumbs') self.assertEqual(current_breadcrumbs[-1].url, '/test')
from flask_weasyprint import HTML, render_pdf from io import TextIOWrapper, BytesIO import base64 import csv import feedparser import json import io import matplotlib.pyplot as plt import numpy import pandas import random import seaborn breadcrumbs = Breadcrumbs(app) login_manager = LoginManager(app) @login_manager.user_loader def load_user(id): if id is not None: return User.query.get(id) return None @login_manager.unauthorized_handler def unauthorized(): flash("Please Log In to Continue") return redirect(url_for('login')) @app.route("/", methods = ["GET", "POST"]) def home():
from urllib.parse import urlparse from datetime import datetime, timedelta from functools import wraps from flask import Flask, render_template, Response, request, redirect, url_for from threading import Thread from flask_breadcrumbs import Breadcrumbs, register_breadcrumb from aws_iot_helpers import AwSIoT, AwSIoTThing from http import HTTPStatus import boto3 import logging application = Flask(__name__) application.debug = True # Initialize Flask-Breadcrumbs Breadcrumbs(app=application) LOG_TABLE_NAME = os.environ['LOG_TABLE_NAME'] TELEMETRY_TABLE_NAME = os.environ['TELEMETRY_TABLE_NAME'] def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if 'x-ms-token-aad-refresh-token' not in request.headers: pass #return redirect(url_for('setup')) return f(*args, **kwargs) return decorated_function
class InvenioTheme(object): """Invenio theme extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs) def init_app(self, app, assets=None, **kwargs): """Initialize application object.""" self.init_config(app.config) # Initialize extensions self.menu_ext.init_app(app) self.menu = app.extensions['menu'] self.breadcrumbs.init_app(app) # Register blueprint in order to register template and static folder. blueprint = Blueprint( 'invenio_theme', __name__, template_folder='templates', static_folder='static', ) app.register_blueprint(blueprint) # Register errors handlers. app.register_error_handler(401, unauthorized) app.register_error_handler(403, insufficient_permissions) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_error) # Save reference to self on object app.extensions['invenio-theme'] = self def init_config(self, config): """Initialize configuration.""" config.setdefault('SASS_BIN', 'node-sass') config.setdefault("THEME_SITENAME", _("Invenio")) config.setdefault("THEME_LOGO", "images/invenio-color.svg") config.setdefault("REQUIREJS_CONFIG", 'js/build.js') config.setdefault("THEME_GOOGLE_SITE_VERIFICATION", []) config.setdefault('BASE_TEMPLATE', 'invenio_theme/page.html') config.setdefault( 'COVER_TEMPLATE', 'invenio_theme/page_cover.html') config.setdefault( 'SETTINGS_TEMPLATE', 'invenio_theme/page_settings.html') config.setdefault( 'THEME_BASE_TEMPLATE', config['BASE_TEMPLATE']) config.setdefault( 'THEME_COVER_TEMPLATE', config['COVER_TEMPLATE']) config.setdefault( 'THEME_SETTINGS_TEMPLATE', config['SETTINGS_TEMPLATE']) config.setdefault( 'THEME_ERROR_TEMPLATE', 'invenio_theme/error.html') config.setdefault( 'THEME_401_TEMPLATE', 'invenio_theme/401.html') config.setdefault( 'THEME_403_TEMPLATE', 'invenio_theme/403.html') config.setdefault( 'THEME_404_TEMPLATE', 'invenio_theme/404.html') config.setdefault( 'THEME_500_TEMPLATE', 'invenio_theme/500.html')