예제 #1
0
    def register_error_handlers(self):
        def prepare_error(message, description, code = None):

            if not code:
                code = 500

            response = jsonify(
                code = code,
                message = message,
                description = description
            )

            response.status_code = code

            return response

        @self.errorhandler(HTTPException)
        def http_error(ex):
            return prepare_error(ex.message, re.sub('<[^<]+?>', '', ex.description), ex.code)

        @self.errorhandler(CollectorException)
        def application_error(ex):
            self.logger.warn("%s: %s [%s]", ex.__class__.__name__, ex.message, ex.description)
            return prepare_error(ex.message, ex.description, ex.code)

        @self.errorhandler(Exception)
        def error(ex):
            return prepare_error(ex.message, None)

        for code in default_exceptions.iterkeys():
            self.error_handler_spec[None][code] = http_error
예제 #2
0
def run_daemon(environment, log_level, config_file):
    create_app(app, log_level, config_file, True)
    app.conf.set("enviro", "run", environment)
    app.logger.info('Environment: %s' % environment)
    
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    
    app.register_blueprint(auth.backend)
    app.register_blueprint(messages.backend)
    
    app.logger.info("Loading applications...")
    applications.get()

    # Load framework blueprints
    app.logger.info("Loading frameworks...")
    register_frameworks(app)

    app.logger.info("Initializing Genesis (if present)...")
    app.register_blueprint(genesis.backend)
    
    tracked_services.initialize()
    app.logger.info("Server is up and ready")
    try:
        app.run(host="0.0.0.0", port=8000)
    except KeyboardInterrupt:
        app.logger.info("Received interrupt")
예제 #3
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(bark.config)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    # Component imports. Must be here to fix cyclical problems
    from auth import bp_auth
    app.register_blueprint(bp_auth)

    from swipes import bp_swipes
    app.register_blueprint(bp_swipes, url_prefix='/swipes')

    from events import bp_events
    app.register_blueprint(bp_events, url_prefix='/events')

    from devices import bp_devices
    app.register_blueprint(bp_devices, url_prefix='/devices')

    from persons import bp_persons
    app.register_blueprint(bp_persons, url_prefix='/persons')

    from groups import bp_groups
    app.register_blueprint(bp_groups, url_prefix='/groups')

    @app.route('/') 
    def hello():
        return "Hello World"
    
    db.init_app(app)

    return app
예제 #4
0
파일: utils.py 프로젝트: CingHu/kuryr
def make_json_app(import_name, **kwargs):
    """Creates a JSON-oriented Flask app.

    All error responses that you don't specifically manage yourself will have
    application/json content type, and will contain JSON that follows the
    libnetwork remote driver protocol.


    { "Err": "405: Method Not Allowed" }


    See:
      - https://github.com/docker/libnetwork/blob/3c8e06bc0580a2a1b2440fe0792fbfcd43a9feca/docs/remote.md#errors  # noqa
    """
    app = Flask(import_name, **kwargs)

    @app.errorhandler(NeutronClientException)
    def make_json_error(ex):
        response = jsonify({"Err": str(ex)})
        response.status_code = (ex.code if isinstance(ex, HTTPException)
                                else ex.status_code
                                if isinstance(ex, NeutronClientException)
                                else 500)
        content_type = 'application/vnd.docker.plugins.v1+json; charset=utf-8'
        response.headers['Content-Type'] = content_type
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #5
0
파일: rssapp.py 프로젝트: sachinsu/rssapp
def make_rest_app(import_name, **kwargs):
	"""
	Creates a JSON-oriented Flask app.

	All error responses that you don't specifically
	manage yourself will have application/json content
	type, and will contain JSON like this (just an example):

	{ "message": "405: Method Not Allowed" }
	"""
	def make_rest_error(ex):
		# app.logger.info("in make rest error")
		# app.logger.info(str(ex))
		if request_wants_json():
			response = jsonify(message=str(ex))
		else:
			response = Response('<message>{}</message>'.format(str(ex)))
			
		response.status_code = (ex.code
									if isinstance(ex, HTTPException)
									else 500)
		return response
		
	app = Flask(import_name, **kwargs)

	for code in default_exceptions.iterkeys():
		app.error_handler_spec[None][code] = make_rest_error

	return app
def make_json_app(import_name, **kwargs):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }
    """
    def make_json_error(ex):
        pprint.pprint(ex)
        pprint.pprint(ex.code)
        #response = jsonify(message=str(ex))
        response = jsonify(ex)
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException)
                                else 500)
        return response

    app = Flask(import_name, **kwargs)
    #app.debug = True
    app.secret_key = id_generator(24)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #7
0
def make_json_app(import_name):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }
    """
    def make_json_error(ex):
        message = str(ex)
        status = ''
        code = 500
        if isinstance(ex, HTTPException):
            code = ex.code
        else:
            code = 500

        if code in [401, 403, 405, 415]:
            status = 'fail'
            response = jsonify(status=status, data=None)
        else:
            status = 'error'
            response = jsonify(status=status, data=None,  message=message)
        response.status_code = code
        return response

    app = Flask(import_name)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    return app
예제 #8
0
def make_json_app(import_name, **kwargs):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }
    """
    def make_json_error(ex):
        response = flask.jsonify(Message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException)
                                else 500)
        return response

    app = flask.Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    # Add logging
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    app.logger.addHandler(handler)

    return app
def make_json_app(import_name, **kwargs):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }

    http://flask.pocoo.org/snippets/83/
    """
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException)
                                else 500)
        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #10
0
파일: __init__.py 프로젝트: brab/flask-api
def create_app(environment=None):
    '''
    Create an app instance
    '''
    app = Flask('backend')
    app.url_map.converters['ObjectId'] = BSONObjectIdConverter

    # Config app for environment
    if not environment:
        environment = os.environ.get('BACKEND_ENVIRONMENT', 'Local')

    app.config.from_object('backend.backend.settings.%s' % environment)

    # convert exceptions to JSON
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                if isinstance(ex, HTTPException)
                else 500)
        return response
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error


    from backend.backend.views.api import api
    app.register_module(api)

    # initialize modules
    admin.init_app(app)
    db.init_app(app)
    login_manager.setup_app(app)
    mail.init_app(app)

    return app
예제 #11
0
def json_flask_app(import_name, **kwargs):
    def make_json_error(ex):
        response = jsonify(message=str(ex), code=ex.code if isinstance(ex, HTTPException) else 500)
        return response
    app = Flask(import_name, **kwargs)
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    return app
예제 #12
0
def install_errorhandler(app):
    def errorhandler(error):
        if not isinstance(error, exceptions.HTTPException):
            error = getattr(exceptions, error.__class__.__name__)()
        return error.get_response(request.environ)

    for code in default_exceptions.iterkeys():
        app.register_error_handler(code, errorhandler)
예제 #13
0
파일: util.py 프로젝트: jmknyc06/OpenDCRE
def setup_json_errors(app):
    """ Setup JSON error responses for the given Flask application.

    Args:
        app (Flask): A Flask application instance.
    """
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = _make_json_error
예제 #14
0
def setup_json_errors(app):
    """ Setup JSON error responses for the given Flask application.

    Args:
        app (flask.Flask): A Flask application instance.
    """
    for code in default_exceptions.iterkeys():
        app.register_error_handler(code, _make_json_error)
예제 #15
0
    def __init__(self, name):
        Flask.__init__(self, name)

        status_view = CephStatusView.as_view('status')
        self.add_url_rule('/', view_func=status_view)

        # add custom error handler
        for code in default_exceptions.iterkeys():
            self.error_handler_spec[None][code] = self.make_json_error
예제 #16
0
def make_json_app():
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #17
0
def create_app(option):
    app = Flask(__name__)
    config = config_factory.get(option)
    app.config.from_object(config)
    from common import create_jinja_filters, random_pwd

    create_jinja_filters(app)
    from webapp.api import api
    from webapp.client import client
    from webapp.media import media

    app.register_blueprint(client)
    app.register_blueprint(api, url_prefix=Constants.API_V1_URL_PREFIX)
    app.register_blueprint(media, url_prefix=Constants.MEDIA_URL_PREFIX)

    csrf.init_app(app)
    compress.init_app(app)
    gravatar.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    admin.init_app(app)
    mail.init_app(app)
    from models import User, Role
    from webapp.forms import ExtendedRegisterForm

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore, register_form=ExtendedRegisterForm)
    with app.app_context():
        api_manager.init_app(app, flask_sqlalchemy_db=db)

        @app.before_request
        def before_request():
            g.constants = Constants
            g.config = app.config
            g.mode = app.config.get('MODE')

        @app.after_request
        def redirect_if_next(response_class):
            payload = request.args if request.method == 'GET' else request.form
            if 'api_next' in payload:
                if not response_class.status_code == 200:
                    flash(response_class.data)
                    return redirect(request.referrer)
                return redirect(payload.get('api_next'))
            return response_class

    patch_request_class(app, Constants.MAX_FILE_SIZE)

    from webapp.common import make_json_error

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    configure_uploads(app, (user_images, ))

    return app
예제 #18
0
def configure_flask_exception_handler(app):
    """
    Set the exception handler for the default flask exceptions
    to return the expected json response.
    :param app:The flask app instance
    :return:
    """

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #19
0
def make_json_app():
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException)
                                else 500)
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #20
0
파일: app.py 프로젝트: Crapworks/terrastate
    def __init__(self, name):
        Flask.__init__(self, name)

        dhc_view = StateView.as_view('status')
        self.add_url_rule('/', defaults={'env': None}, view_func=dhc_view)
        self.add_url_rule('/<env>', view_func=dhc_view)

        # add custom error handler
        for code in default_exceptions.iterkeys():
            self.register_error_handler(code, self.make_json_error)
예제 #21
0
파일: app.py 프로젝트: jonshern/terratools
    def __init__(self, name):
        Flask.__init__(self, name)

        dhc_view = StateView.as_view('status')
        self.add_url_rule('/', defaults={'env': None}, view_func=dhc_view)
        self.add_url_rule('/<env>', view_func=dhc_view)

        # add custom error handler
        for code in default_exceptions.iterkeys():
            self.register_error_handler(code, self.make_json_error)
예제 #22
0
def create_app(settings="realize.settings"):
    app = Flask(__name__, template_folder='templates')
    app.config.from_object(settings)
    db.app = app
    db.init_app(app)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #23
0
def create_app(settings="realize.settings"):
    app = Flask(__name__, template_folder='templates')
    app.config.from_object(settings)
    db.app = app
    db.init_app(app)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #24
0
    def __init__(self, name):
        template_folder = os.path.join(os.path.dirname(__file__), 'templates')
        Flask.__init__(self, name, template_folder=template_folder)

        status_view = CephStatusView.as_view('status')
        self.add_url_rule('/', view_func=status_view)

        # add custom error handler
        for code in default_exceptions.iterkeys():
            self.error_handler_spec[None][code] = self.make_json_error
예제 #25
0
파일: restutils.py 프로젝트: s-y/chukchi
def setup_json_handlers(app):
    def make_json_error(ex):
        code = ex.code if isinstance(ex, HTTPException) else 500
        response = jsonify(message=str(ex), error=code)
        response.status_code = code
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #26
0
    def __init__(self, name):
        template_folder = os.path.join(os.path.dirname(__file__), 'templates')
        static_folder = os.path.join(os.path.dirname(__file__), 'static')
        Flask.__init__(self, name, template_folder=template_folder, static_folder=static_folder)

        status_view = CephStatusView.as_view('status')
        self.add_url_rule('/', view_func=status_view)

        # add custom error handler
        for code in default_exceptions.iterkeys():
            self.error_handler_spec[None][code] = self.make_json_error
예제 #27
0
파일: core.py 프로젝트: Space-Cadets/Oberon
def create_json_app(config):
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(config)
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    db.init_app(app)
    with app.app_context():
        db.create_all()
    app.app_context().push()
    return app
예제 #28
0
파일: util.py 프로젝트: Tronic/piratehr
def init_error_responses(app):
	"""Make error responses use JSON."""
	from werkzeug.exceptions import default_exceptions
	from werkzeug.exceptions import HTTPException
	make_json_error = lambda ex: json_response(dict(description=str(ex)), ex.code)
	for code in default_exceptions.iterkeys():
		if code != 500: app.errorhandler(code)(make_json_error)
	# Use HTTP Basic auth (json object in password field)
	app.errorhandler(401)(lambda ex: json_response(
		dict(description='Authenticate with HTTP Basic json:{auth object}'), 401,
		#headers={'WWW-Authenticate': 'Basic realm="JSON auth required"'}
	))
예제 #29
0
def use_pretty_default_error_handlers(app):
    """Set default error handlers to use lib.make_error.

    With thanks to http://flask.pocoo.org/snippets/15/

    """
    def make_json_error(ex):
        status_code = ex.code if isinstance(ex, HTTPException) else 500
        return make_error('', status_code)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #30
0
파일: app.py 프로젝트: feltnerm/swatidj
def init_errorhandlers(app):
    """ Set default error pages (404, 505, etc.). """

    def make_json_error(error):
        response = jsonify(message=str(error))
        response.status_code = (error.code
                                if isinstance(error, HTTPException)
                                else 500)
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #31
0
def jsonApp(app):
    """Converts all flask errors to JSON"""
    def make_json_error(error):
        response = jsonify(data={}, errors=[{'message': str(error)}])
        response.status_code = (error.code
                                if isinstance(error, HTTPException) else 500)
        return response

    for code in default_exceptions.iterkeys():
        if code != 500 and code != 405 and code != 400:
            app.register_error_handler(code, make_json_error)
    return app
예제 #32
0
def use_pretty_default_error_handlers(app):
    """Set default error handlers to use lib.make_error.

    With thanks to http://flask.pocoo.org/snippets/15/

    """
    def make_json_error(ex):
        status_code = ex.code if isinstance(ex, HTTPException) else 500
        return make_error('', status_code)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #33
0
def create_app(config):
    app = Flask(__name__)
    app.template_folder = join(dirname(__file__), 'templates')
    app.static_folder = join(dirname(__file__), 'static')

    for code in default_exceptions.iterkeys():
        app.register_error_handler(code, make_json_error)

    app.config['USER_CONFIG'] = Config(config)
    app.register_blueprint(X509ResourceV1.as_blueprint(), url_prefix='/v1/x509')
    app.register_blueprint(KeyResourceV1.as_blueprint(), url_prefix='/v1/key')

    return app
예제 #34
0
def create_app():

    app = Flask(__name__)
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI

    app.secret_key = settings.SESSION_SECRET_KEY

    db.app = app
    db.init_app(app)

    return app
예제 #35
0
def configure_error_handlers(app):
    """Generic error-handling logic."""

    # Following snippet adapted from: http://flask.pocoo.org/snippets/83/
    def make_json_error(exc):
        message = exc.description
        error(message)
        response = jsonify(message=message)
        response.status_code = (exc.code
                                if isinstance(exc, HTTPException) else 500)
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #36
0
파일: app.py 프로젝트: srt32/rodeo
def configure_error_handlers(app):
    """Generic error-handling logic."""
    # Following snippet adapted from: http://flask.pocoo.org/snippets/83/
    def make_json_error(exc):
        message = exc.description
        error(message)
        response = jsonify(message=message)
        response.status_code = (exc.code
                                if isinstance(exc, HTTPException)
                                else 500)
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #37
0
def build_json_app(name, **kwargs):
    """ 
    Creates a json api flask app. From http://flask.pocoo.org/snippets/83/
    """
    def make_json_error(ex):
        response = jsonify(message = str(ex))
        response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
        return response

    app = Flask(name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #38
0
파일: util.py 프로젝트: usvi/piratehr
def init_error_responses(app):
    """Make error responses use JSON."""
    from werkzeug.exceptions import default_exceptions
    from werkzeug.exceptions import HTTPException
    make_json_error = lambda ex: json_response(dict(description=str(ex)), ex.
                                               code)
    for code in default_exceptions.iterkeys():
        if code != 500: app.errorhandler(code)(make_json_error)
    # Use HTTP Basic auth (json object in password field)
    app.errorhandler(401)(
        lambda ex: json_response(
            dict(description='Authenticate with HTTP Basic json:{auth object}'
                 ),
            401,
            #headers={'WWW-Authenticate': 'Basic realm="JSON auth required"'}
        ))
예제 #39
0
파일: api.py 프로젝트: ryanolson/CloudApp
def Blueprint(name, **kwargs):
    from flask import Blueprint
    from werkzeug.exceptions import default_exceptions
    from cloudapp.authentication.decorators import load_user
    error_if_exists = kwargs.pop('subdomain', None)
    if error_if_exists:
       raise RuntimeError("[cloudapp_api] Blueprint: subdomain is not an allowed keyword")
    bp = Blueprint(name, __name__, subdomain="api", **kwargs)
    bp.before_request(load_user)
    bp.before_request(_process_request_json)
    for code in default_exceptions.iterkeys():
        if code >= 500: continue
        @bp.errorhandler(code)
        def errorhandler(code):
            return _json_errorhandler(code)
    return bp
예제 #40
0
def record_auth(setup_state):
    # Runs when the Blueprint binds to the main application
    app = setup_state.app

    def default_json_error(ex):
        """ Exception -> flask JSON responder """
        app.logger.error(
            "Uncaught error thrown by Flask/Werkzeug: {0}".format(ex))
        response = flask_jsonify(message=str(ex), type='api_error')
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    # Patch all error handlers in werkzeug
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = default_json_error
예제 #41
0
파일: main.py 프로젝트: Frostman/savanna
def make_app():
    """App builder (wsgi)

    Entry point for Savanna REST API server
    """
    app = Flask('savanna.api')

    @app.route('/', methods=['GET'])
    def version_list():
        return render({
            "versions": [
                {"id": "v0.2", "status": "CURRENT"}
            ]
        })

    app.register_blueprint(api_v02.rest, url_prefix='/v0.2')

    setup_storage(app)
    setup_scheduler(app)

    def make_json_error(ex):
        status_code = (ex.code
                       if isinstance(ex, HTTPException)
                       else 500)
        description = (ex.description
                       if isinstance(ex, HTTPException)
                       else str(ex))
        return render({'error': status_code, 'error_message': description},
                      status=status_code)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    app.wsgi_app = auth_valid(app.config)(app.wsgi_app)

    app.wsgi_app = auth_token(
        app.config,
        auth_host=CONF.os_auth_host,
        auth_port=CONF.os_auth_port,
        auth_protocol=CONF.os_auth_protocol,
        admin_user=CONF.os_admin_username,
        admin_password=CONF.os_admin_password,
        admin_tenant=CONF.os_admin_tenant_name
    )(app.wsgi_app)

    return app
예제 #42
0
def configure_app(app):
    """Retrieve App Configuration."""
    app.config.from_object('sql_json_bridge.default_config')
    try:
        app.config.from_envvar('SQL_JSON_BRIDGE_CONFIG')
    except:
        pass

    app.config["DATABASES"] = load_database_configs(
        app.config["DATABASE_CONFIG_LOCATION"])

    if app.config["LEGACY_SUPPORT"]:
        from sql_json_bridge.legacy.views import legacy
        DEFAULT_BLUEPRINTS.append(legacy)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #43
0
def record_auth(setup_state):
    # Runs when the Blueprint binds to the main application
    app = setup_state.app

    def default_json_error(ex):
        """ Exception -> flask JSON responder """
        app.logger.error("Uncaught error thrown by Flask/Werkzeug: {0}"
                         .format(ex))
        response = flask_jsonify(message=str(ex), type='api_error')
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException)
                                else 500)
        return response

    # Patch all error handlers in werkzeug
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = default_json_error
예제 #44
0
def make_json_app(import_name, **kwargs):
    """
    { "message": "405: Method Not Allowed" }
    """
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.errorhandler(HTTPException)(make_json_error)
        # app.error_handler_spec[None][code] = make_json_error

    return app
예제 #45
0
    def register_error_handlers(self):
        from werkzeug.exceptions import default_exceptions
        from werkzeug.exceptions import HTTPException
        # http://flask.pocoo.org/snippets/83/
        def make_json_error(ex):
            if hasattr(ex, 'to_json'):
                response = jsonify(ex.to_json())
            else:
                response = jsonify(message=str(ex))
            if hasattr(ex, 'status_code'):
                response.status_code = ex.status_code
            else:
                response.status_code = (ex.code
                                        if isinstance(ex, HTTPException)
                                        else 500)
            return response

        for code in default_exceptions.iterkeys():
            self.app.error_handler_spec[None][code] = make_json_error
예제 #46
0
파일: app.py 프로젝트: devxoul/schoool
def install_errorhandler(app):
    def errorhandler(err):
        accept = request.headers.get('Accept', '')

        if 'application/json' in accept:
            data = {
                'status': err.code,
                'name': err.name,
                'description': err.description
            }
            res = json.dumps(data)
            return Response(res, mimetype='application/json', status=err.code)

        html = "<h1>{0}: {1}</h1><p>{2}</p>".format(err.code, err.name,
                                                    err.description)
        return Response(html, status=err.code)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = errorhandler
예제 #47
0
def make_json_app(import_name, **kwargs):
    """
    handle exceptions as json outputs
    """
    from werkzeug.exceptions import default_exceptions
    from werkzeug.exceptions import HTTPException

    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #48
0
def JSONApp(import_name, **kwargs):
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        h = response.headers

        h['Access-Control-Allow-Origin'] = '*'
        h['Access-Control-Max-Age'] = str(21600)
        h['Access-Control-Allow-Headers'] = 'CONTENT-TYPE'

        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #49
0
def get_admin_app(name):
    #FIXME : this actually gets ALL config values, not just db values
    db_config = td_config.get_db_config()
    #secret_config,public_config = td_config.get_configs()
    db_info = DbInfo(db_config)
    db_url = db_util.generate_db_url(name, db_info)
    if not database_exists(db_url):
        return None
    app = get_generic_app(name)
    db_handle = db_util.create_db_handle(db_url, app)
    app.tables = ImportedTables(db_handle)
    app.register_blueprint(admin_login_blueprint)
    app.register_blueprint(admin_manage_blueprint)
    LoginManager().init_app(app)
    auth.generate_user_loader(app)
    auth.generate_identity_loaded(app)
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    return app
예제 #50
0
def make_json_app(import_name, **kwargs):
    """
    Creates a JSON-oriented Flask app.
    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):
    { "message": "405: Method Not Allowed" }
    """
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.register_error_handler(code, make_json_error)

    return app
예제 #51
0
def make_json_app(app, **kwargs):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }
    """
    def make_json_error(ex):
        status_code = ex.code if isinstance(ex, HTTPException) else 500
        response = jsonify(message=str(ex), status_code=status_code)
        response.status_code = status_code
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #52
0
    def __configure(self):
        for code in default_exceptions.iterkeys():
            self.error_handler_spec[None][code] = RemoteDslrApiError.handle

        config = Settings().get_config
        self.address = config["server"]["address"]
        self.port = int(config["server"]["port"])
        self.debug = config["server"]["port"] in ['True', 'true']
        use_ssl = config["server"]["ssl"] in ['True', 'true']
        auto_announce = config["general"]["auto_announce"] in ['True', 'true']
        if auto_announce:
            AutoAnnounce(self.port, use_ssl)

        self.options = {'use_reloader': False, 'threaded': True}

        if use_ssl:
            abs_path = path.dirname(path.abspath(__file__)) + "/../"
            cert_file = abs_path + config["server"]["ssl_crt"]
            key_file = abs_path + config["server"]["ssl_key"]
            ssl_context = (cert_file, key_file)
            self.options['ssl_context'] = ssl_context
예제 #53
0
def make_json_app(import_name, **kwargs):
    """
    handle exceptions as json outputs
    """
    from werkzeug.exceptions import default_exceptions
    from werkzeug.exceptions import HTTPException

    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.headers[
            'Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #54
0
def make_json_app(app):
    """
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { "message": "405: Method Not Allowed" }
    """
    def make_json_error(ex):
        response = jsonify(message=str(ex),
                           traceback='not available with DEBUG off'
                           if not app.debug else traceback.format_exc())
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #55
0
def make_json_app(import_name, **kwargs):
    '''
    Creates a JSON-oriented Flask app.

    All error responses that you don't specifically
    manage yourself will have application/json content
    type, and will contain JSON like this (just an example):

    { 'message': '500: Internal Server Error' }
    '''
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code
                                if isinstance(ex, HTTPException) else 500)
        return response

    app = Flask(import_name, **kwargs)

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    return app
예제 #56
0
def setup_default_handlers(app):
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
예제 #57
0
 def _register_error_handler(self):
     for code in default_exceptions.iterkeys():
         self.error_handler_spec[None][code] = self._error_handler
예제 #58
0
def setup_default_handlers(app):
    for code in default_exceptions.iterkeys():
        app.register_error_handler(code, make_json_error)
예제 #59
0
파일: srv.py 프로젝트: toke/sync-engine
# Handle both /endpoint and /endpoint/ without redirecting.
# Note that we need to set this *before* registering the blueprint.
app.url_map.strict_slashes = False


def default_json_error(ex):
    """ Exception -> flask JSON responder """
    logger = get_logger()
    logger.error('Uncaught error thrown by Flask/Werkzeug', exc_info=ex)
    response = jsonify(message=str(ex), type='api_error')
    response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
    return response


# Patch all error handlers in werkzeug
for code in default_exceptions.iterkeys():
    app.error_handler_spec[None][code] = default_json_error


@app.before_request
def auth():
    """ Check for account ID on all non-root URLS """
    if request.path in ('/accounts', '/accounts/', '/', '/n', '/n/') \
                       or request.path.startswith('/w/'):
        return

    if request.path.startswith('/n/'):
        ns_parts = filter(None, request.path.split('/'))
        namespace_public_id = ns_parts[1]
        valid_public_id(namespace_public_id)