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

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

    {
        "code": 1,
        "errorMessage": "The requested URL was not found on the server.  If you entered the URL manually please [...] ",
        "errorType": "404: Not Found"
    }

    More here: http://flask.pocoo.org/snippets/83/ (ad-hoc by pincopallino93)
    """

    def make_json_error(ex):
        response = jsonify(errorMessage=str(ex.description) if hasattr(ex, 'description') else str(ex), code=1,
                           errorType=str(ex))
        response.status_code = 200  # (ex.code if isinstance(ex, HTTPException) else 500)

        return response

    app = Flask(import_name, **kwargs)

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

    return app
Beispiel #2
0
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
Beispiel #3
0
    def create_app(environment=None):
        """
        Create an app instance
        """
        app = Flask('core')

        # Allow CORS for all domains on all routes
        CORS(app)

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

        app.config.from_object('core.api.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.items():
            app.error_handler_spec[None][code] = make_json_error

        from core.api.views.endpoints import api
        app.register_module(api)

        API.app = app
def create_app(environment=None):
    app = Flask('veritrans')
    app.url_map.converters['ObjectId'] = BSONObjectIdConverter

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

    app.config.from_object('core.api.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.items():
        app.error_handler_spec[None][code] = make_json_error

    from core.api.views.endpoints import api
    app.register_module(api)

    return app
Beispiel #5
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
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
Beispiel #7
0
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" }

    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
Beispiel #9
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
Beispiel #10
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 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
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
Beispiel #12
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
Beispiel #13
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
Beispiel #14
0
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
Beispiel #15
0
def make_json_app(import_name, **kwargs):
    def make_json_error(ex):
        response = jsonify(success=False, error=str(ex))
        response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
        return response

    app = Flask(import_name, **kwargs)
    CORS(app)

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

    return app
Beispiel #16
0
def make_json_app(*args, **kwargs):
    """JSONify all error responses"""
    def make_json_error(ex):
        response = jsonify(error=str(ex))
        response.status_code = (ex.code if isinstance(ex, HTTPException)
                                else 500)
        return response

    app = Flask(*args, **kwargs)
    for code in default_exceptions:
        app.error_handler_spec[None][code] = make_json_error

    return app
Beispiel #17
0
def medea_app(import_name, **kwargs):
    def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
        traceback.print_exc()
        return response

    app = Flask(import_name, **kwargs)
    for code in default_exceptions.keys():
        app.error_handler_spec[None][code] = make_json_error

    CORS(app)
    return app
Beispiel #18
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
Beispiel #19
0
def 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" }
    """
    app = Flask(import_name, **kwargs)

    for code in default_exceptions.keys():
        app.error_handler_spec[None][code] = error

    return app
Beispiel #20
0
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
Beispiel #21
0
def create_app(config):
    """Creates a default application."""
    app = Flask(__name__)
    app.config.from_pyfile(config)

    from peanuts.lib.database import db
    db.init_app(app)

    from peanuts import views
    views.register(app, route_base='/api')

    with app.app_context():
        from peanuts.models.app import Application
        from peanuts.lib.auth import no_apps_need

        db.create_all()

        @app.before_first_request
        def check_admin(*args, **kargs):
            """Checks that there is an admin application.  If not, creates it.
            """
            if no_apps_need():
                # Unless overridden by a direct database operation, the first
                #   app to be accessed should be admin.
                admin_app = Application(
                    token='6752e4b0-8122-4c9a-ad1d-19d703fdfed0',
                    title='Admin',
                    description='The administrative application.',
                    slug='admin',
                    repo_url=app.config['ADMIN_REPO'],
                    config=json.dumps('{}')
                    )
                db.session.add(admin_app)
                db.session.commit()

    from peanuts.lib.session import PeanutsSessionInterface
    app.session_interface = PeanutsSessionInterface()

    from peanuts.lib.err import make_json_error
    for code in default_exceptions.keys():
        app.error_handler_spec[None][code] = make_json_error

    return app
Beispiel #22
0
def makejsonapp(import_name, **kwargs):
    """
    Ensure all internally generated responses (i.e: errors) are output as JSON.
    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
Beispiel #23
0
def create_app(config_name='development'):
    """Flask factory function"""

    # Configure from config.py
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

    # Configure Flask-Admin
    admin = Admin(name='demo', template_mode='bootstrap3')
    from .admin_views import DbView
    admin.add_view(DbView(Group, db.session))
    admin.add_view(DbView(User, db.session))
    admin.init_app(app)

    # Blueprints
    from .api import groups_bp
    app.register_blueprint(groups_bp, url_prefix='/api/groups')

    from .api import users_bp
    app.register_blueprint(users_bp, url_prefix='/api/users')
    #

    @app.before_first_request
    def create_tables():
        db.create_all()

    # Ensure all errors thrown are json
    # 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

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

    return app
def make_json_app():
    """
    Creates a JSON-oriented Flask app.
    All error responses 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(__name__)

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

    return app
Beispiel #25
0
def make_app():
    """
    Entry point for Savanna REST API server
    """
    app = Flask('savanna.api')

    app.config['SQLALCHEMY_DATABASE_URI'] = CONF.sqlalchemy.database_uri
    app.config['SQLALCHEMY_ECHO'] = CONF.sqlalchemy.echo

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

    setup_storage(app)
    setup_defaults()
    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
Beispiel #26
0
def create_app():
    """
        Create application, using Flask. Payloads are in JSON.
        """
    
    app = Flask('pikka_bird_server')
    
    app.debug = (os.environ['LOG_LEVEL'] == 'DEBUG')
    
    for r in [
        'collections',
        'statics']:
        app.register_blueprint(
            getattr(getattr(pikka_bird_server.routes, r), r))
    
    for code in default_exceptions.keys():
        app.error_handler_spec[None][code] = __make_json_error
    
    __setup_logger(app.logger)
    
    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):

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

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

    wrapped_app = Flask(import_name, **kwargs)

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

    return wrapped_app
Beispiel #28
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
Beispiel #29
0
def 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",
        "statuscode": 405
    }
    """
    def make_json_error(ex):
        if not isinstance(ex, ApplicationException):
            appexception = ApplicationException(message=str(ex), statuscode=ex.code)
        else:
            appexception = ex
        json_str = jsonpickle.encode(appexception, unpicklable=False)
        resp = make_response(json_str)
        resp.status_code = appexception.statuscode
        resp.mimetype = "application/json"
        return resp

        response = jsonpickle.encode(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
Beispiel #30
0
# 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)

        with session_scope() as db_session:
            try: