コード例 #1
0
ファイル: app.py プロジェクト: smith-j-travis/ForumCodeName
def configure_packages(app):
    debug_toolbar = DebugToolbarExtension()
    themes = Themes()

    debug_toolbar.init_app(app)
    themes.init_themes(app, app_identifier="forumcodename")
    db.init_app(app)
コード例 #2
0
ファイル: util.py プロジェクト: sharan1/love
def get_test_app():

    def test_loader(app):
        return load_themes_from(os.path.join(os.path.dirname(__file__), '../themes/'))

    Themes(main.app, app_identifier='yelplove', loaders=[test_loader])

    return TestApp(main.app)
コード例 #3
0
def create_app():
    #APP init
    app = Flask(__name__)
    app.config.from_object('config.DevelopmentConfig')
    #THEMES init
    Themes(app, app_identifier='app')
    #MAIL init
    from flask_mail import Mail
    mail = Mail(app)
    #DATABASE init
    from models import db
    db.init_app(app)
    #MIGRATIONS init
    migrate = Migrate(app, db)
    with app.app_context():
        #User init
        from flask_user import SQLAlchemyAdapter, UserManager
        from users import User
        db_adapter = SQLAlchemyAdapter(db, User)
        user_manager = UserManager(db_adapter, app)
        #db finalization
        db.create_all()
    #API - is for IOT, or mobile
    from models import DummyObject, DummyFile
    manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)
    manager.create_api(DummyObject)
    manager.create_api(DummyFile)
    #ADMIN - is for basic crud for trained users
    from admin import admin
    admin.init_app(app)
    #MEMBER VIEWS
    from member import MemberView
    MemberView.register(app)
    #upload example
    from flask_admin.contrib.fileadmin import FileAdmin
    path = os.path.join(os.path.dirname(__file__), app.config['UPLOAD_FOLDER'])
    admin.add_view(FileAdmin(path, '/uploads/', name='Uploads'))
    #sqlmodel example
    from flask_admin.contrib.sqla import ModelView
    admin.add_view(ModelView(DummyObject, db.session))
    #DASHBOARD - is for customer login pages
    #I'll have to make that custom
    return app, migrate
コード例 #4
0
ファイル: main.py プロジェクト: ryuichi1208/scraping-py
# -*- coding: utf-8 -*-
# flake8: noqa
from flask import Flask
from flask_themes2 import Themes

import config
from util.auth import is_admin
from util.converter import RegexConverter
from util.csrf import generate_csrf_token


app = Flask(__name__.split('.')[0])
app.secret_key = config.SECRET_KEY
app.url_map.converters['regex'] = RegexConverter
app.jinja_env.globals['config'] = config
app.jinja_env.globals['csrf_token'] = generate_csrf_token
app.jinja_env.globals['is_admin'] = is_admin

Themes(app, app_identifier='yelplove')

# if debug property is present, let's use it
try:
    app.debug = config.DEBUG
    except AttributeError:
        app.debug = False

	import views
コード例 #5
0
ファイル: __init__.py プロジェクト: qateam123/eq
def create_app():
    application = Flask(__name__, static_url_path='/s', static_folder='../static')
    headers = {'Content-Type': 'application/json',
               'Cache-Control': 'no-cache, no-store, must-revalidate',
               'Pragma': 'no-cache',
               'Strict-Transport-Security': 'max-age=31536000; includeSubdomains',
               'X-Frame-Options': 'DENY',
               'X-Xss-Protection': '1; mode=block',
               'X-Content-Type-Options': 'nosniff'}

    restrict_content_length(application)

    setup_secure_cookies(application)

    setup_babel(application)

    @application.after_request
    def apply_caching(response):  # pylint: disable=unused-variable
        for k, v in SECURE_HEADERS.items():
            response.headers[k] = v

        return response

    @application.context_processor
    def override_url_for():  # pylint: disable=unused-variable
        return dict(url_for=versioned_url_for)

    application.wsgi_app = AWSReverseProxied(application.wsgi_app)

    Markdown(application, extensions=['gfm'])

    add_blueprints(application)

    configure_logging(application)

    login_manager.init_app(application)

    if settings.EQ_ENABLE_CACHE:
        cache.init_app(application, config={'CACHE_TYPE': 'simple'})
    else:
        cache.init_app(application)  # Doesnt cache

    if settings.EQ_DEV_MODE:
        add_health_check(application, headers)
        start_dev_mode(application)

    # always add safe health check
    add_safe_health_check(application)

    if settings.EQ_PROFILING:
        setup_profiling(application)

    if settings.EQ_UA_ID:
        setup_analytics(application)

    # Add theme manager
    application.config['THEME_PATHS'] = os.path.dirname(os.path.abspath(__file__))
    Themes(application, app_identifier="surveyrunner")

    @application.teardown_appcontext
    def shutdown_session(exception=None):  # pylint: disable=unused-variable,unused-argument
        db_session.remove()

    return application
コード例 #6
0
def create_app():  # noqa: C901  pylint: disable=too-complex
    application = Flask(__name__,
                        static_url_path='/s',
                        static_folder='../static')
    application.config.from_object(settings)

    if application.config['EQ_APPLICATION_VERSION']:
        logger.info('starting eq survey runner',
                    version=application.config['EQ_APPLICATION_VERSION'])

    if application.config['EQ_NEW_RELIC_ENABLED']:
        setup_newrelic()

    application.eq = {}
    if application.config['EQ_RABBITMQ_ENABLED']:
        application.eq['submitter'] = RabbitMQSubmitter(
            application.config['EQ_RABBITMQ_URL'],
            application.config['EQ_RABBITMQ_URL_SECONDARY'],
        )

    else:
        application.eq['submitter'] = LogSubmitter()

    application.eq['encrypter'] = Encrypter(
        application.config['EQ_SUBMISSION_SR_PRIVATE_SIGNING_KEY'],
        application.config['EQ_SUBMISSION_SR_PRIVATE_SIGNING_KEY_PASSWORD'],
        application.config['EQ_SUBMISSION_SDX_PUBLIC_KEY'],
    )

    application.eq['database'] = Database(
        application.config['EQ_SERVER_SIDE_STORAGE_DATABASE_URL'],
        application.
        config['EQ_SERVER_SIDE_STORAGE_DATABASE_SETUP_RETRY_COUNT'],
        application.
        config['EQ_SERVER_SIDE_STORAGE_DATABASE_SETUP_RETRY_DELAY_SECONDS'],
    )

    application.eq['session_storage'] = SessionStorage(
        application.eq['database'], )

    setup_secure_cookies(application)

    setup_babel(application)

    application.wsgi_app = AWSReverseProxied(application.wsgi_app)

    add_blueprints(application)

    configure_flask_logging(application)

    login_manager.init_app(application)

    add_safe_health_check(application)

    if application.config['EQ_DEV_MODE']:
        start_dev_mode(application)

    if application.config['EQ_ENABLE_CACHE']:
        cache.init_app(application, config={'CACHE_TYPE': 'simple'})
    else:
        cache.init_app(application)  # Doesnt cache

    # Add theme manager
    application.config['THEME_PATHS'] = os.path.dirname(
        os.path.abspath(__file__))
    Themes(application, app_identifier="surveyrunner")

    @application.before_request
    def before_request():  # pylint: disable=unused-variable
        request_id = str(uuid4())
        logger.new(request_id=request_id)

    @application.after_request
    def apply_caching(response):  # pylint: disable=unused-variable
        for k, v in SECURE_HEADERS.items():
            response.headers[k] = v

        return response

    @application.context_processor
    def override_url_for():  # pylint: disable=unused-variable
        return dict(url_for=versioned_url_for)

    @application.teardown_appcontext
    def shutdown_session(exception=None):  # pylint: disable=unused-variable,unused-argument
        application.eq['database'].remove()

    return application
コード例 #7
0
# Login
login_manager = LoginManager()

# Mail
mail = Mail()

# Caching
cache = Cache()

# Redis
redis_store = Redis()

# Debugtoolbar
debugtoolbar = DebugToolbarExtension()

# Migrations
migrate = Migrate()

# Themes
themes = Themes()

# PluginManager
plugin_manager = PluginManager()

# Babel
babel = Babel()

# CSRF
csrf = CsrfProtect()
コード例 #8
0
def create_app(setting_overrides=None):  # noqa: C901  pylint: disable=too-complex
    application = Flask(__name__,
                        static_url_path='/s',
                        static_folder='../static')
    application.config.from_object(settings)

    application.eq = {}

    with open(application.config['EQ_SECRETS_FILE']) as secrets_file:
        secrets = yaml.safe_load(secrets_file)

    with open(application.config['EQ_KEYS_FILE']) as keys_file:
        keys = yaml.safe_load(keys_file)

    validate_required_secrets(secrets)
    validate_required_keys(keys, KEY_PURPOSE_SUBMISSION)
    application.eq['secret_store'] = SecretStore(secrets)
    application.eq['key_store'] = KeyStore(keys)

    if setting_overrides:
        application.config.update(setting_overrides)

    if application.config['EQ_APPLICATION_VERSION']:
        logger.info('starting eq survey runner',
                    version=application.config['EQ_APPLICATION_VERSION'])

    if application.config['EQ_NEW_RELIC_ENABLED']:
        setup_newrelic()

    setup_database(application)

    setup_dynamodb(application)

    if application.config['EQ_RABBITMQ_ENABLED']:
        application.eq['submitter'] = RabbitMQSubmitter(
            host=application.config['EQ_RABBITMQ_HOST'],
            secondary_host=application.config['EQ_RABBITMQ_HOST_SECONDARY'],
            port=application.config['EQ_RABBITMQ_PORT'],
            username=application.eq['secret_store'].get_secret_by_name(
                'EQ_RABBITMQ_USERNAME'),
            password=application.eq['secret_store'].get_secret_by_name(
                'EQ_RABBITMQ_PASSWORD'),
        )

    else:
        application.eq['submitter'] = LogSubmitter()

    application.eq['id_generator'] = UserIDGenerator(
        application.config['EQ_SERVER_SIDE_STORAGE_USER_ID_ITERATIONS'],
        application.eq['secret_store'].get_secret_by_name(
            'EQ_SERVER_SIDE_STORAGE_USER_ID_SALT'),
        application.eq['secret_store'].get_secret_by_name(
            'EQ_SERVER_SIDE_STORAGE_USER_IK_SALT'),
    )

    setup_secure_cookies(application)

    setup_secure_headers(application)

    setup_babel(application)

    application.wsgi_app = AWSReverseProxied(application.wsgi_app)

    add_blueprints(application)

    configure_flask_logging(application)

    login_manager.init_app(application)

    add_safe_health_check(application)

    if application.config['EQ_DEV_MODE']:
        start_dev_mode(application)

    if application.config['EQ_ENABLE_CACHE']:
        cache.init_app(application, config={'CACHE_TYPE': 'simple'})
    else:
        # no cache and silence warning
        cache.init_app(application, config={'CACHE_NO_NULL_WARNING': True})

    # Switch off flask default autoescaping as content is html encoded
    # during schema/metadata/summary context (and navigition) generation
    application.jinja_env.autoescape = False

    # Add theme manager
    application.config['THEME_PATHS'] = os.path.dirname(
        os.path.abspath(__file__))
    Themes(application, app_identifier='surveyrunner')

    @application.before_request
    def before_request():  # pylint: disable=unused-variable

        # While True the session lives for permanent_session_lifetime seconds
        # Needed to be able to set the client-side cookie expiration
        cookie_session.permanent = True

        request_id = str(uuid4())
        logger.new(request_id=request_id)

    @application.after_request
    def apply_caching(response):  # pylint: disable=unused-variable
        for k, v in CACHE_HEADERS.items():
            response.headers[k] = v

        return response

    @application.context_processor
    def override_url_for():  # pylint: disable=unused-variable
        return dict(url_for=versioned_url_for)

    return application
コード例 #9
0
ファイル: __init__.py プロジェクト: xsllqs/JimV-C
__author__ = 'James Iter'
__date__ = '2017/3/31'
__contact__ = '*****@*****.**'
__copyright__ = '(c) 2017 by James Iter.'

app.config = dict(app.config, **app_config)
app.jinja_env.add_extension('jinja2.ext.i18n')
app.jinja_env.add_extension('jinja2.ext.do')
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
app.jinja_env.auto_reload = app.config['DEBUG']

# 替换为Flask-Session
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(
    seconds=app_config['PERMANENT_SESSION_LIFETIME'])
Session(app)
Themes(app, app_identifier="JimV-C")
themes_list = packaged_themes_loader(app)


def instantiation_ws_vnc(listen_port, target_host, target_port):
    # 用于 Web noVNC 代理
    ws = WebSocketProxy(listen_host="0.0.0.0",
                        listen_port=listen_port,
                        target_host=target_host,
                        target_port=target_port,
                        run_once=True,
                        daemon=True,
                        idle_timeout=10)
    ws.start_server()

コード例 #10
0
ファイル: application.py プロジェクト: alanshi/rpress
def configure_theme(app):
    """"""
    Themes(app, app_identifier='rpress')
    return
コード例 #11
0
def create_app(setting_overrides=None):  # noqa: C901  pylint: disable=too-complex,too-many-statements
    application = Flask(__name__, static_url_path='/s', static_folder='../static')
    application.config.from_object(settings)

    application.eq = {}

    with open(application.config['EQ_SECRETS_FILE']) as secrets_file:
        secrets = yaml.safe_load(secrets_file)

    with open(application.config['EQ_KEYS_FILE']) as keys_file:
        keys = yaml.safe_load(keys_file)

    validate_required_secrets(secrets)
    validate_required_keys(keys, KEY_PURPOSE_SUBMISSION)
    application.eq['secret_store'] = SecretStore(secrets)
    application.eq['key_store'] = KeyStore(keys)

    if setting_overrides:
        application.config.update(setting_overrides)

    if application.config['EQ_APPLICATION_VERSION']:
        logger.info('starting eq survey runner', version=application.config['EQ_APPLICATION_VERSION'])

    if application.config['EQ_NEW_RELIC_ENABLED']:
        setup_newrelic()

    setup_database(application)

    setup_dynamodb(application)

    setup_s3(application)

    setup_bigtable(application)

    setup_gcs(application)

    setup_redis(application)

    setup_gc_datastore(application)

    if application.config['EQ_SUBMITTER'] == 'rabbitmq':
        application.eq['submitter'] = RabbitMQSubmitter(
            host=application.config['EQ_RABBITMQ_HOST'],
            secondary_host=application.config['EQ_RABBITMQ_HOST_SECONDARY'],
            port=application.config['EQ_RABBITMQ_PORT'],
            username=application.eq['secret_store'].get_secret_by_name('EQ_RABBITMQ_USERNAME'),
            password=application.eq['secret_store'].get_secret_by_name('EQ_RABBITMQ_PASSWORD'),
        )
    elif application.config['EQ_SUBMITTER'] == 'pubsub':
        application.eq['submitter'] = PubSubSubmitter(
            project_id=application.config['EQ_PUBSUB_PROJECT_ID'],
            topic=application.config['EQ_PUBSUB_TOPIC'],
        )
    elif application.config['EQ_SUBMITTER'] == 'gcs':
        application.eq['submitter'] = GCSSubmitter(
            bucket_name=application.config['EQ_GCS_SUBMISSION_BUCKET_ID'],
        )
    else:
        application.eq['submitter'] = LogSubmitter()

    application.eq['id_generator'] = UserIDGenerator(
        application.config['EQ_SERVER_SIDE_STORAGE_USER_ID_ITERATIONS'],
        application.eq['secret_store'].get_secret_by_name('EQ_SERVER_SIDE_STORAGE_USER_ID_SALT'),
        application.eq['secret_store'].get_secret_by_name('EQ_SERVER_SIDE_STORAGE_USER_IK_SALT'),
    )

    setup_secure_cookies(application)

    setup_secure_headers(application)

    setup_babel(application)

    application.wsgi_app = AWSReverseProxied(application.wsgi_app)

    add_blueprints(application)

    configure_flask_logging(application)

    login_manager.init_app(application)

    add_safe_health_check(application)

    if application.config['EQ_DEV_MODE']:
        start_dev_mode(application)

    # Switch off flask default autoescaping as content is html encoded
    # during schema/metadata/summary context (and navigition) generation
    application.jinja_env.autoescape = False

    # Add theme manager
    application.config['THEME_PATHS'] = os.path.dirname(os.path.abspath(__file__))
    Themes(application, app_identifier='surveyrunner')

    # pylint: disable=maybe-no-member
    application.jinja_env.globals['theme'] = flask_theme_cache.get_global_theme_template()

    @application.before_request
    def before_request():  # pylint: disable=unused-variable
        request_id = str(uuid4())
        logger.new(request_id=request_id)

    @application.after_request
    def apply_caching(response):  # pylint: disable=unused-variable
        for k, v in CACHE_HEADERS.items():
            response.headers[k] = v

        return response

    @application.context_processor
    def override_url_for():  # pylint: disable=unused-variable
        return dict(url_for=versioned_url_for)

    return application
コード例 #12
0
ファイル: __init__.py プロジェクト: sharma66mahesh/digi_cert
from flask_themes2 import (Themes)
from pymongo import MongoClient
from simplekv.fs import FilesystemStore
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
from flask import Flask, request, redirect, url_for

BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
UPLOAD_FOLDER = BASE_DIR + "\cert_viewer\static\img"
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'json'])

login_manager = LoginManager()

app = Flask(__name__)
Themes(app, app_identifier='cert_viewer')
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/profile'
db = SQLAlchemy(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
login_manager.init_app(app)
migrate = Migrate(app, db)
logging.config.fileConfig(os.path.join(BASE_DIR, 'logging.conf'))
log = logging.getLogger(__name__)
from cert_viewer import alchemy

mongo_connection = None
cert_store = None
intro_store = None

from cert_core.cert_store.certificate_store import CertificateStore, V1AwareCertificateStore
コード例 #13
0
ファイル: app.py プロジェクト: damahou/sagewui
def create_app(notebook, startup_token=None, debug=False):
    """
    This is the main method to create a running notebook. This is
    called from the process spawned in run.py
    """
    # Create app
    app = Flask(__name__)
    app.startup_token = startup_token

    app.config.update({
        'SESSION_COOKIE_HTTPONLY': False,
        'PROPAGATE_EXCEPTIONS': debug,
        'DEBUG': debug,
        'SECRET_KEY': os.urandom(24),
        })

    dynamic_javascript = DynamicJs(debug=debug)

    @app.before_request
    def set_notebook_object():
        g.notebook = notebook
        g.dynamic_javascript = dynamic_javascript

    # Handles all uncaught exceptions if not debug activated
    @app.errorhandler(500)
    def log_exception(error):
        return message_template(
            gettext('''500: Internal server error.'''),
            username=getattr(g, 'username', UAT_GUEST)), 500

    # Template globals
    app.add_template_global(url_for)
    # Template filters
    app.add_template_filter(css_escape)
    app.add_template_filter(number_of_rows)
    app.add_template_filter(convert_time_to_string)
    app.add_template_filter(prettify_time_ago)
    app.add_template_filter(join_max)
    app.add_template_filter(max)
    app.add_template_filter(lambda x: repr(str(x)), name='repr_str')

    # Default template context
    @app.context_processor
    def default_template_context():
        return {'sitename': gettext('Sage Notebook'),
                'sage_version': SAGE_VERSION,
                'MATHJAX': MATHJAX,
                'JEDITABLE_TINYMCE': JEDITABLE_TINYMCE,
                'conf': notebook.conf}

    # Register the Blueprints
    app.register_blueprint(admin)
    app.register_blueprint(authentication)
    app.register_blueprint(base)
    app.register_blueprint(doc, url_prefix='/doc')
    app.register_blueprint(static_paths)
    app.register_blueprint(worksheet)
    app.register_blueprint(worksheet_listing)

    # # Extensions
    # Babel
    babel = Babel(app, default_locale='en_US')

    # Check if saved default language exists. If not fallback to default
    @app.before_first_request
    def check_default_lang():
        def_lang = notebook.conf['default_language']
        trans_ids = [str(trans) for trans in babel.list_translations()]
        if def_lang not in trans_ids:
            notebook.conf['default_language'] = None

    # register callback function for locale selection
    # this function must be modified to add per user language support
    @babel.localeselector
    def get_locale():
        return g.notebook.conf['default_language']

    # Themes
    app.config['THEME_PATHS'] = THEME_PATHS
    app.config['DEFAULT_THEME'] = DEFAULT_THEME
    Themes(app, app_identifier='sagewui', loaders=[theme_paths_loader])
    name = notebook.conf['theme']
    if name not in app.theme_manager.themes:
        notebook.conf['theme'] = app.config['DEFAULT_THEME']

    # autoindex v0.3 doesnt seem to work with modules
    # routing with app directly does the trick
    # TODO: Check to see if autoindex 0.4 works with modules
    idx = AutoIndex(app, browse_root=SRC_PATH, add_url_rules=False)

    @app.route('/src/')
    @app.route('/src/<path:path>')
    @guest_or_login_required
    def autoindex(path='.'):
        filename = os.path.join(SRC_PATH, path)
        if os.path.isfile(filename):
            with open(filename, 'rb') as f:
                src = f.read().decode('utf-8', 'ignore')
            if (os.path.splitext(filename)[1] in
                    ['.py', '.c', '.cc', '.h', '.hh', '.pyx', '.pxd']):
                return render_template(
                    'html/source_code.html',
                    src_filename=path, src=src, username=g.username)
            return src
        return idx.render_autoindex(path)

    return app
コード例 #14
0
def configure(app):
    themes = Themes()
    themes.init_themes(app, app_identifier='nanoctf')