Пример #1
0
def create_app(config_path=os.environ.get('FILESERVE_CONFIG_FILE', None)):
    app = Flask(__name__)

    # Load the default config file
    app.config.from_pyfile(os.path.join(base_directory, 'config.cfg'))
    # Then try to load a config file for use in production
    if config_path is not None:
        app.config.from_pyfile(config_path)

    if not app.config.get('SQLALCHEMY_DATABASE_URI', None):
        # Last resort, use SQLite database for development
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{0}'.format(os.path.join(base_directory, 'fileserve.db'))

    if app.config.get('PRODUCTION'):
        app.use_x_sendfile = True
        app.debug = False
    else:
        app.debug = True

    db.init_app(app)
    from . import routes
    routes.init_app(app)
    return app
Пример #2
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from flask import Flask

import config

# Set up the Main Flask app instance
app = Flask(__name__)
app.secret_key = '?9huDM\\H'

if config.get('base', 'accel-redirect') or config.get('base', 'x-sendfile'):
    app.use_x_sendfile = True

if config.get('base', 'debug'):
    app.debug = True
    app.config['SQLALCHEMY_ECHO'] = "debug"

if config.get('base', 'log_file'):
    import logging
    from logging.handlers import TimedRotatingFileHandler
    handler = TimedRotatingFileHandler(config.get('base', 'log_file'),
                                       when='midnight',
                                       encoding='UTF-8')
    handler.setLevel(logging.DEBUG)
    app.logger.addHandler(handler)

app.config['SQLALCHEMY_DATABASE_URI'] = config.get('base', 'database_uri')
Пример #3
0
#!/usr/bin/env python
from flask import Flask, send_from_directory
from flask import render_template, flash, redirect
import os
import json

try:
    from config import ROOT_DIR
except ImportError:
    ROOT_DIR = '/media/'

app = Flask(__name__)
app.debug = True
app.use_x_sendfile = True

#SERVER_NAME = 'localhost'
#SERVER_PORT = 5000


video_list = ['.mp4', '.webm', '.h264']
audio_list = ['.mp3', '.ogg', '.wav']


def get_file_ext(file_list):
    """
    Function to split filename into name and ext
    """
    files = []
    file_dict = {}
    for f in file_list:
        file_dict = {}
Пример #4
0
def create_app(debug=True, enable_profiler=False, profiler_quiet=False, enable_timepro=False):
    """
    :param debug: whether to configure app for debug
    :param enable_profiler: enable flask profiler, causes function to return ProfilerMiddleware rather than Flask object which can be started by run_simple
    :param profiler_quiet: when profiler enabled sets whether profiler output echoed to stdout
    """
    app = Flask("iiab")
    app.url_map.strict_slashes = False
    app.use_x_sendfile = config().getboolean('WEBAPP', 'use_x_sendfile')
    app.secret_key = '1785132b4fd244a2a1ce6ae3f1d978ac'

    # Configuration items
    if debug:
        app.debug = True
        app.config['DEBUG'] = True
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

    base_prefix = config().get('WEBAPP', 'base_prefix')

    blueprints = [
        (top_views.blueprint, base_prefix),
        (search_views.blueprint, base_prefix),
        (gutenberg.gutenberg, base_prefix + "books"),
        (map_views.blueprint, base_prefix + "maps"),
        (video_views.blueprint, base_prefix + "video"),
        (wikipedia_views.blueprint, base_prefix + "wikipedia"),
        (zim_views.blueprint, base_prefix + "zim"),
        (gutenberg_content_views.blueprint, base_prefix + "books"),
        (settings_views.blueprint, base_prefix + "settings"),
    ]
    for blueprint, prefix in blueprints:
        app.register_blueprint(blueprint, url_prefix=prefix)

    gutenberg.set_flask_app(app)
    gutenberg.init_db()

    configure_babel(app)

    # Auto Index the software repository
    autoindex = AutoIndex(app, add_url_rules=False)
    # FIXME: this should be done more elegantly -bcg'13

    @app.route(base_prefix + 'software/<path:path>')
    @app.route(base_prefix + 'software')
    def software_view(path='.'):
        software_dir = config().get_path('SOFTWARE', 'software_dir')
        return autoindex.render_autoindex(path, browse_root=software_dir, endpoint='software_view')

    #print "URL MAP: ", app.url_map

    # Static handling from http://flask.pocoo.org/mailinglist/archive/2011/8/25/static-files-subdomains/#9237e5b3c217b2875c59daaac4c23487
    app.config['STATIC_ROOT'] = config().get_default('WEBAPP', 'static_url_path', None)

    def static(path):
        root = app.config.get('STATIC_ROOT', None)
        if root is None:  # fallback on the normal way
            return url_for('static', filename=path)
        return urlparse.urljoin(root, path)

    @app.context_processor
    def inject_static():
        return dict(static=static)

    if enable_profiler:
        from werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream
        f = open('profiler.log', 'w')
        if profiler_quiet:
            profile_app = ProfilerMiddleware(app, f, profile_dir="/tmp")
        else:
            stream = MergeStream(sys.stdout, f)
            profile_app = ProfilerMiddleware(app, stream, profile_dir="/tmp")
        return profile_app

    if enable_timepro:
        from timepro_flask import TimeProMiddleware, MergeStream
        f = open('timepro.log', 'w')
        if profiler_quiet:
            profile_app = TimeProMiddleware(app, f, profile_dir="/tmp")
        else:
            stream = MergeStream(sys.stdout, f)
            profile_app = TimeProMiddleware(app, stream, profile_dir="/tmp")
        return profile_app


    return app
Пример #5
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    app.use_x_sendfile = False
    return app
Пример #6
0
from flask import Flask, g
from flask import render_template
from flask import send_from_directory, url_for, jsonify
from flask import request, Response
from werkzeug.contrib.cache import SimpleCache

from . import sgf_utils
from .cloudygo import CloudyGo

app = Flask(__name__)
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

# Requires Apache support see:
# https://stackoverflow.com/a/27303164/459714
app.use_x_sendfile = True and not app.debug

cache = SimpleCache()

LOCAL_DATA_DIR = os.path.join(app.instance_path, 'data')
LOCAL_EVAL_DIR = os.path.join(app.instance_path, 'eval')
DATABASE_PATH = os.path.join(app.instance_path, 'clouds.db')

RANDOMIZE_GAMES = True
MAX_GAMES_ON_PAGE = 100

CONVERTED_SUFFIX = "_converted.txt.gz"

#### DB STUFF ####

Пример #7
0
            path_info = environ['PATH_INFO']
            if path_info.startswith(script_name):
                environ['PATH_INFO'] = path_info[len(script_name):]
        scheme = environ.get('HTTP_X_SCHEME', '')
        if scheme:
            environ['wsgi.url_scheme'] = scheme
        return self.app(environ, start_response)


app = Flask(__name__, **config)
app.secret_key = os.urandom(20)
app.permanent_session_lifetime = timedelta(days=1)
app.config.from_pyfile("config.py")
app.prefix = "/times/"
app.wsgi_app = ReservePoxied(app.wsgi_app)
app.use_x_sendfile = not app.config['DEBUG']
if not app.debug:
    app.logger.setLevel(logging.INFO)
    app.logger.addHandler(logging.StreamHandler())
    app.logger.info("Start Times Web Server Logging")


class CustomJsonEncoder(JSONEncoder):

    def default(self, obj):
        try:
            if isinstance(obj, datetime):
                return obj.isoformat() + "+0800"
            iterable = iter(obj)
        except TypeError:
            pass
Пример #8
0
def create_app(debug=False, local=False, use_profiler=True):

    #from marvin.api import theapi as api
    from marvin.api.cube import CubeView
    from marvin.api.maps import MapsView
    from marvin.api.modelcube import ModelCubeView
    from marvin.api.plate import PlateView
    from marvin.api.rss import RSSView
    from marvin.api.spaxel import SpaxelView
    from marvin.api.query import QueryView
    from marvin.api.general import GeneralRequestsView
    from marvin.web.controllers.index import index
    from marvin.web.controllers.galaxy import galaxy
    from marvin.web.controllers.search import search
    from marvin.web.controllers.plate import plate
    from marvin.web.controllers.images import images
    from marvin.web.controllers.users import users

    # ----------------------------------
    # Create App
    marvin_base = os.environ.get('MARVIN_BASE', 'marvin2')
    app = Flask(__name__, static_url_path='/{0}/static'.format(marvin_base))
    api = Blueprint("api", __name__, url_prefix='/{0}/api'.format(marvin_base))
    app.debug = debug
    jsg.JSGLUE_JS_PATH = '/{0}/jsglue.js'.format(marvin_base)
    jsglue = jsg.JSGlue(app)

    # Add Marvin Logger
    app.logger.addHandler(log)

    # Setup the profile configuration
    app.config["flask_profiler"] = {
        "enabled": True,
        "storage": {
            "engine": "sqlite",
            "FILE": os.path.join(os.environ['MARVIN_DIR'],
                                 'flask_profiler.sql')
        },
        'endpointRoot': '{0}/profiler'.format(marvin_base),
        "basicAuth": {
            "enabled": False
        }
    }

    # ----------------------------------
    # Initialize logging + Sentry + UWSGI config for Production Marvin
    if app.debug is False:

        # ----------------------------------------------------------
        # Set up getsentry.com logging - only use when in production
        dsn = os.environ.get('SENTRY_DSN', None)
        app.config['SENTRY_DSN'] = dsn
        sentry = Sentry(app, logging=True, level=logging.ERROR)

        # --------------------------------------
        # Configuration when running under uWSGI
        try:
            import uwsgi
            app.use_x_sendfile = True
        except ImportError:
            pass
    else:
        sentry = None
        config.use_sentry = False
        config.add_github_message = False

    # Change the implementation of "decimal" to a C-based version (much! faster)
    #
    # This is producing this error [ Illegal value: Decimal('3621.59598486') ]on some of the remote API tests with getSpectrum
    # Turning this off for now
    #
    # try:
    #    import cdecimal
    #    sys.modules["decimal"] = cdecimal
    # except ImportError:
    #    pass  # no available

    # Find which connection to make
    connection = getDbMachine()
    local = (connection == 'local') or local

    # ----------------------------------
    # Set some environment variables
    config._inapp = True
    os.environ['SAS_REDUX'] = 'sas/mangawork/manga/spectro/redux'
    os.environ['SAS_ANALYSIS'] = 'sas/mangawork/manga/spectro/analysis'
    os.environ['SAS_SANDBOX'] = 'sas/mangawork/manga/sandbox'
    release = os.environ.get('MARVIN_RELEASE', 'mangawork')
    os.environ[
        'SAS_PREFIX'] = 'marvin2' if release == 'mangawork' else 'dr13/marvin'
    url_prefix = '/marvin2' if local else '/{0}'.format(marvin_base)

    # ----------------------------------
    # Load the appropriate Flask configuration file for debug or production
    if app.debug:
        if local:
            server_config_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), 'configuration',
                'localhost.cfg')
        elif connection == 'utah':
            server_config_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), 'configuration',
                'utah.cfg')
        else:
            server_config_file = None
            app.logger.debug(
                "Trying to run in debug mode, but not running on a development machine that has database access."
            )
            # sys.exit(1)
    else:
        try:
            import uwsgi
            server_config_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), 'configuration',
                uwsgi.opt['flask-config-file'])
        except ImportError:
            app.logger.debug(
                "Trying to run in production mode, but not running under uWSGI. You might try running again with the '--debug' flag."
            )
            sys.exit(1)

    if server_config_file:
        app.logger.info('Loading config file: {0}'.format(server_config_file))
        app.config.from_pyfile(server_config_file)

    # ----------------------------------
    # Initialize feature flags
    feature_flags = FeatureFlag(app)
    # configFeatures(debug=app.debug)

    # Update any config parameters
    app.config["UPLOAD_FOLDER"] = os.environ.get("MARVIN_DATA_DIR", None)
    app.config["LIB_PATH"] = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), 'lib')

    # Add lib directory as a new static path
    @app.route('/{0}/lib/<path:filename>'.format(marvin_base))
    def lib(filename):
        return send_from_directory(app.config["LIB_PATH"], filename)

    # Register update global session
    @app.before_request
    def global_update():
        ''' updates the global session / config '''
        updateGlobalSession()
        # send_request()

    # ----------------
    # Error Handling
    # ----------------

    def _is_api(request):
        ''' Checks if the error comes from the api '''
        return request.blueprint == 'api' or 'api' in request.url

    @app.errorhandler(404)
    def page_not_found(error):
        name = 'Page Not Found'
        if _is_api(request):
            return make_error_json(error, name, 404)
        else:
            return make_error_page(app, name, 404, sentry=sentry)

    @app.errorhandler(500)
    def internal_server_error(error):
        name = 'Internal Server Error'
        if _is_api(request):
            return make_error_json(error, name, 500)
        else:
            return make_error_page(app, name, 500, sentry=sentry)

    @app.errorhandler(400)
    def bad_request(error):
        name = 'Bad Request'
        if _is_api(request):
            return make_error_json(error, name, 400)
        else:
            return make_error_page(app, name, 400, sentry=sentry)

    @app.errorhandler(405)
    def method_not_allowed(error):
        name = 'Method Not Allowed'
        if _is_api(request):
            return make_error_json(error, name, 405)
        else:
            return make_error_page(app, name, 405, sentry=sentry)

    @app.errorhandler(422)
    def handle_unprocessable_entity(error):
        name = 'Unprocessable Entity'
        data = getattr(error, 'data')
        if data:
            # Get validations from the ValidationError object
            messages = data['messages']
        else:
            messages = ['Invalid request']

        if _is_api(request):
            return make_error_json(error, name, 422)
        else:
            return make_error_page(app,
                                   name,
                                   422,
                                   sentry=sentry,
                                   data=messages)

    # These should be moved into the api module but they need the api blueprint to be registered on
    # I had these in the api.__init__ with the api blueprint defined there as theapi
    # which was imported here, see line 39
    # This should all be moved into the Brain and abstracted since it is
    # general useful standardized stuff (what?)

    @api.errorhandler(422)
    def handle_unprocessable_entity(err):
        # webargs attaches additional metadata to the `data` attribute
        data = getattr(err, 'data')
        if data:
            # Get validations from the ValidationError object
            messages = data['messages']
        else:
            messages = ['Invalid request']
        return jsonify({
            'validation_errors': messages,
        }), 422

    # ----------------------------------
    # Registration
    config.use_sentry = False
    #
    # API route registration
    CubeView.register(api)
    MapsView.register(api)
    ModelCubeView.register(api)
    PlateView.register(api)
    RSSView.register(api)
    SpaxelView.register(api)
    GeneralRequestsView.register(api)
    QueryView.register(api)
    app.register_blueprint(api)

    # Web route registration
    app.register_blueprint(index, url_prefix=url_prefix)
    app.register_blueprint(galaxy, url_prefix=url_prefix)
    app.register_blueprint(search, url_prefix=url_prefix)
    app.register_blueprint(plate, url_prefix=url_prefix)
    app.register_blueprint(images, url_prefix=url_prefix)
    app.register_blueprint(users, url_prefix=url_prefix)

    # Register all custom Jinja filters in the file.
    app.register_blueprint(jinjablue)

    # Register error handlers
    app.register_blueprint(web)

    # Initialize the Flask-Profiler ; see results at localhost:portnumber/flask-profiler
    if use_profiler:
        try:
            flask_profiler.init_app(app)
        except Exception as e:
            pass

    return app
Пример #9
0
# License for the specific language governing permissions and limitations
# under the License.

from __future__ import with_statement

import logging
import os
import sys

from werkzeug.wsgi import DispatcherMiddleware
from flask import Flask

from airbrush.main import app as airbrush

interpreter = os.path.expanduser("~/local/bin/python")
if sys.executable != interpreter:
    os.execl(interpreter, interpreter, *sys.argv)

app = Flask(__name__)
app.use_x_sendfile = False

handler = logging.FileHandler("error.log")
handler.setLevel(logging.WARNING)
app.logger.addHandler(handler)

app = DispatcherMiddleware(app, {
    "/h": airbrush,
})

application = app
Пример #10
0
def create_app(debug=True,
               enable_profiler=False,
               profiler_quiet=False,
               enable_timepro=False):
    """
    :param debug: whether to configure app for debug
    :param enable_profiler: enable flask profiler, causes function to return ProfilerMiddleware rather than Flask object which can be started by run_simple
    :param profiler_quiet: when profiler enabled sets whether profiler output echoed to stdout
    """
    app = Flask("iiab")
    app.url_map.strict_slashes = False
    app.use_x_sendfile = config().getboolean('WEBAPP', 'use_x_sendfile')
    app.secret_key = '1785132b4fd244a2a1ce6ae3f1d978ac'

    # Configuration items
    if debug:
        app.debug = True
        app.config['DEBUG'] = True
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

    base_prefix = config().get('WEBAPP', 'base_prefix')

    blueprints = [
        (top_views.blueprint, base_prefix),
        (search_views.blueprint, base_prefix),
        (gutenberg.gutenberg, base_prefix + "books"),
        (map_views.blueprint, base_prefix + "maps"),
        (video_views.blueprint, base_prefix + "video"),
        (wikipedia_views.blueprint, base_prefix + "wikipedia"),
        (zim_views.blueprint, base_prefix + "zim"),
        (gutenberg_content_views.blueprint, base_prefix + "books"),
        (settings_views.blueprint, base_prefix + "settings"),
    ]
    for blueprint, prefix in blueprints:
        app.register_blueprint(blueprint, url_prefix=prefix)

    gutenberg.set_flask_app(app)
    gutenberg.init_db()

    configure_babel(app)

    # Auto Index the software repository
    autoindex = AutoIndex(app, add_url_rules=False)
    # FIXME: this should be done more elegantly -bcg'13

    @app.route(base_prefix + 'software/<path:path>')
    @app.route(base_prefix + 'software')
    def software_view(path='.'):
        software_dir = config().get_path('SOFTWARE', 'software_dir')
        return autoindex.render_autoindex(path,
                                          browse_root=software_dir,
                                          endpoint='software_view')

    #print "URL MAP: ", app.url_map

    # Static handling from http://flask.pocoo.org/mailinglist/archive/2011/8/25/static-files-subdomains/#9237e5b3c217b2875c59daaac4c23487
    app.config['STATIC_ROOT'] = config().get_default('WEBAPP',
                                                     'static_url_path', None)

    def static(path):
        root = app.config.get('STATIC_ROOT', None)
        if root is None:  # fallback on the normal way
            return url_for('static', filename=path)
        return urlparse.urljoin(root, path)

    @app.context_processor
    def inject_static():
        return dict(static=static)

    if enable_profiler:
        from werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream
        f = open('profiler.log', 'w')
        if profiler_quiet:
            profile_app = ProfilerMiddleware(app, f, profile_dir="/tmp")
        else:
            stream = MergeStream(sys.stdout, f)
            profile_app = ProfilerMiddleware(app, stream, profile_dir="/tmp")
        return profile_app

    if enable_timepro:
        from timepro_flask import TimeProMiddleware, MergeStream
        f = open('timepro.log', 'w')
        if profiler_quiet:
            profile_app = TimeProMiddleware(app, f, profile_dir="/tmp")
        else:
            stream = MergeStream(sys.stdout, f)
            profile_app = TimeProMiddleware(app, stream, profile_dir="/tmp")
        return profile_app

    return app