コード例 #1
0
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
コード例 #2
0
 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)
コード例 #3
0
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
コード例 #4
0
ファイル: conftest.py プロジェクト: jirikuncar/invenio-github
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)
コード例 #5
0
 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']
コード例 #6
0
    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)
コード例 #7
0
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)
コード例 #8
0
    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)
コード例 #9
0
ファイル: ext.py プロジェクト: mb-wali/invenio-theme
    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)
コード例 #10
0
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)
コード例 #11
0
ファイル: app.py プロジェクト: sharmaudi/catalog-udacity
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
コード例 #12
0
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
コード例 #13
0
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
コード例 #14
0
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
コード例 #15
0
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
コード例 #16
0
ファイル: conftest.py プロジェクト: swordapp/invenio-sword
 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")
コード例 #17
0
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
コード例 #18
0
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
コード例 #19
0
ファイル: conftest.py プロジェクト: topless/invenio-deposit
 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')
コード例 #20
0
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
コード例 #21
0
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
コード例 #22
0
#
# 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()
コード例 #23
0
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
コード例 #24
0
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()
コード例 #25
0
    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)
コード例 #26
0
def create_app(version, run_path):

    global app, token_blacklist, socketio

    app = Flask(__name__, static_url_path="/cvesearch/static",  static_folder="static")
    cors = CORS(app)
    app.config['CORS_HEADERS'] = 'Content-Type'

    app.config["version"] = version
    app.config["run_path"] = run_path
    app.config["APPLICATION_ROOT"] = "/cvesearch"
    
    config = Configuration()

    if config.getWebInterface().lower() == "full":
        app.config["WebInterface"] = False
    else:
        app.config["WebInterface"] = True

    app.config["MONGO_DBNAME"] = config.getMongoDB()
    app.config["SECRET_KEY"] = str(random.getrandbits(256))
    app.config["JWT_SECRET_KEY"] = str(random.getrandbits(256))

    app.config["JWT_ACCESS_TOKEN_EXPIRES"] = ACCESS_EXPIRES
    app.config["JWT_REFRESH_TOKEN_EXPIRES"] = REFRESH_EXPIRES
    app.config["JWT_BLACKLIST_ENABLED"] = True
    app.config["JWT_BLACKLIST_TOKEN_CHECKS"] = ["access", "refresh"]

    token_blacklist = config.getRedisTokenConnection()

    app.config["RESTX_MASK_SWAGGER"] = False

    socketio = SocketIO(app)

    Breadcrumbs(app=app)
    Bootstrap(app)
    jwt = JWTManager(app)

    @jwt.additional_claims_loader
    def add_claims_to_access_token(identity):

        return {"user": identity}

    @jwt.token_in_blocklist_loader
    def check_if_token_is_revoked(decrypted_token):
        jti = decrypted_token["jti"]
        entry = token_blacklist.get(jti)
        if entry == "true":
            return True
        return False

    login_manager.init_app(app)
    login_manager.login_message = "You must be logged in to access this page!!!"
    login_manager.login_view = "auth.login"

    @login_manager.user_loader
    def load_user(id):
        return User.get(id, auth_handler)

    from .home import home as home_blueprint

    app.register_blueprint(home_blueprint)

    from .plugins import plugins as plugins_blueprint

    app.register_blueprint(plugins_blueprint, url_prefix="/cvesearch/plugin")

    if not app.config["WebInterface"]:
        from .auth import auth as auth_blueprint

        app.register_blueprint(auth_blueprint)

        from .admin import admin as admin_blueprint

        app.register_blueprint(admin_blueprint, url_prefix="/cvesearch/admin")

    from .restapi import blueprint as api

    app.register_blueprint(api)

    from .restapidocs import docs as docs_blueprint

    app.register_blueprint(docs_blueprint)

    @app.context_processor
    def version():
        def get_version():
            return app.config["version"]

        return dict(get_version=get_version)

    @app.context_processor
    def db_schema():
        def db_schema():
            sc = SchemaChecker()
            try:
                return sc.validate_schema()
            except DatabaseSchemaError as err:
                return err

        return dict(db_schema=db_schema)

    @app.context_processor
    def WebInterface():
        def get_WebInterface():
            return app.config["WebInterface"]

        return dict(get_WebInterface=get_WebInterface)

    @app.context_processor
    def JSON2HTMLTable():
        # Doublequote, because we have to |safe the content for the tags
        def doublequote(data):
            return urllib.parse.quote_plus(urllib.parse.quote_plus(data))

        def JSON2HTMLTableFilter(data, stack=None):
            _return = ""
            if type(stack) == str:
                stack = [stack]

            if type(data) == list:
                if len(data) == 1:
                    _return += JSON2HTMLTableFilter(data[0], stack)
                else:
                    _return += '<ul class="via4">'
                    for item in data:
                        _return += "<li>%s</li>" % JSON2HTMLTableFilter(item, stack)
                    _return += "</ul>"
            elif type(data) == dict:
                _return += '<table class="invisiTable">'
                for key, val in sorted(data.items()):
                    _return += "<tr><td><b>%s</b></td><td>%s</td></tr>" % (
                        key,
                        JSON2HTMLTableFilter(val, stack + [key]),
                    )
                _return += "</table>"
            elif type(data) == str:
                if stack:
                    _return += (
                        "<a href='/link/"
                        + doublequote(".".join(stack))
                        + "/"
                        + doublequote(data)
                        + "'>"
                    )  # link opening
                    _return += "<i class='fas fa-link' aria-hidden='true'></i> </a>"
                _return += (
                    "<a target='_blank' href='%s'>%s</a>" % (data, data)
                    if isURL(data)
                    else data
                )
            _return += ""
            return _return

        return dict(JSON2HTMLTable=JSON2HTMLTableFilter)

    @app.template_filter("htmlEncode")
    def htmlEncode(string):
        return urllib.parse.quote_plus(string).lower()

    @app.template_filter("htmlDecode")
    def htmlDecode(string):
        return urllib.parse.unquote_plus(string)

    @app.template_filter("sortIntLikeStr")
    def sortIntLikeStr(datalist):
        return sorted(datalist, key=lambda k: int(k))

    @app.errorhandler(404)
    def page_not_found(error):
        return (
            render_template("404.html",),
            404,
        )

    return app, socketio
コード例 #27
0
 def test_init_menu(self):
     Breadcrumbs(self.app)
     assert 'menu' in self.app.extensions
コード例 #28
0
 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')
コード例 #29
0
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():
コード例 #30
0
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