Beispiel #1
0
def create_app():
    """Create Flask app using the factory."""
    app = Flask(__name__)

    # Configuration
    app.config.from_object('claimstore.config')

    # Blueprints
    from claimstore.restful import blueprint as restful_bp
    from claimstore.views import blueprint as views_bp
    app.register_blueprint(restful_bp)
    app.register_blueprint(views_bp)

    # Database
    db.init_app(app)

    # Register exceptions
    app.register_error_handler(RestApiException, handle_restful_exceptions)

    @app.errorhandler(404)
    def not_found(error):
        if 'application/json' in request.headers['Content-Type']:
            return jsonify({
                'status': 'error',
                'message': 'Resource not found.'}), 404
        return render_template('404.html'), 404

    return app
Beispiel #2
0
def create_app(config_name):
    app = Flask(__name__)

    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)
    cache.init_app(app)
    mail.init_app(app)
    celery.conf.update(app.config)

    # flask-login init
    login_manager.init_app(app)
    login_manager.unauthorized_handler(lambda: exception(Unauthorized()))

    # blueprint
    from app.controllers.user import users_endpoint
    app.register_blueprint(users_endpoint)
    from app.controllers.channel import channels_endpoint
    app.register_blueprint(channels_endpoint)
    from app.controllers.admin import admin_endpoint
    app.register_blueprint(admin_endpoint)

    # error handler
    app.register_error_handler(APIException, lambda e: exception(e))

    app.register_error_handler(404, lambda e: render_template('404.html'))
    app.register_error_handler(500, lambda e: render_template('500.html'))

    return app
Beispiel #3
0
def get_app(config):
    app = Flask(__name__)

    app.config.from_object(config)
    mail.init_app(app)
    RQ(app)
    csrf = CsrfProtect(app)
    csrf.exempt(api_1_0_blueprint)

    stream_handler = logging.StreamHandler()
    app.logger.setLevel(logging.DEBUG)
    app.logger.addHandler(stream_handler)

    db.init_app(app)
    Migrate(app, db)
    bootstrap = Bootstrap(app)
    security = Security(app, user_datastore)
    user_registered.connect(user_registered_sighandler)

    app.register_blueprint(ratings_blueprint)
    app.register_blueprint(api_1_0_blueprint, url_prefix="/api/v1")
    app.register_blueprint(verify_blueprint, url_prefix="/v")
    app.register_blueprint(tournament_blueprint, url_prefix="/tournament")
    app.register_error_handler(500, email_exception)

    return app
Beispiel #4
0
def create_app():
    """Flask application factory

    :rtype: Flask
    """

    config = os.environ.setdefault(
        'NIDHOGG_SETTINGS_MODULE',
        'nidhogg.settings.base'
    )
    application = Flask(__name__)
    application.config.from_object(config)

    from nidhogg.common.database import db

    db.init_app(application)

    application.add_url_rule(
        '/auth/<method>',
        view_func=YggdrasilView.as_view('generic'),
    )
    application.add_url_rule(
        '/auth/legacy/<method>',
        view_func=LegacyView.as_view('legacy'),
    )
    application.add_url_rule(
        '/api/<method>',
        view_func=ApiView.as_view('api'),
    )
    application.register_error_handler(NidhoggError, NidhoggError.handler)

    return application
Beispiel #5
0
def create_app():
    app = Flask(__name__)

    # config
    if os.getenv('DEV') == 'yes':
        app.config.from_object('config.DevelopmentConfig')
        app.logger.info("Config: Development")
    elif os.getenv('TEST') == 'yes':
        app.config.from_object('config.TestConfig')
        app.logger.info("Config: Test")
    else:
        app.config.from_object('config.ProductionConfig')
        app.logger.info("Config: Production")

    db.init_app(app)

    ## register views
    from views import weight_pages
    app.register_blueprint(weight_pages)

    @app.context_processor
    def context_processor():
        """Add variables to context
        """
        if hasattr(current_user, '_user'):
            curuser = current_user._user
        else:
            # if user is not logged in
            curuser = ""

        return {'today': datetime.date.today,
                'user':curuser,
                }

    app.register_error_handler(401, error401)
    app.register_error_handler(404, error404)
    app.register_error_handler(500, error500)

    app.jinja_env.filters['year'] = format_year

    # flask-login
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = ".login"
    
    @login_manager.user_loader
    def load_user(user):
        from models import User
        u1 = User.query.get(user)
        if u1:
            return DbUser(user)
        else:
            return None

    return app
Beispiel #6
0
class ModApi:
    def __init__(self):
        self.app = Flask(__name__)
        self.load_modules()

        for code in HTTP_STATUS_CODES:
            self.app.register_error_handler(code, handle_error)

        @self.app.route('/robots.txt')
        def static_from_root():
            return send_from_directory(app.static_folder, request.path[1:])

        @self.app.route('/favicon.ico')
        def favicon():
            return send_from_directory(app.root_path, 'favicon.ico',
                    mimetype='image/vnd.microsoft.icon')

        @self.app.route('/')
        @require_secret
        def index():
            notifier = notify.boxcar.BoxcarNotifier()
            notifier.quick_send('Modapi running.')
            return jsonify({'status': 'ok'})

        def shutdown_server():
            func = request.environ.get('werkzeug.server.shutdown')
            if func is None:
                raise RuntimeError('Not running with the Werkzeug Server')
            func()

        @self.app.route('/shutdown')
        @require_secret
        def shutdown():
            shutdown_server()
            return 'Server shutting down...'

    def load_modules(self):
        for p in modularity.get_modules(config.MODULES_DIR):
            c = import_module(p + '.config')
            mc = c.config
            k = config.MOD_CONFIG_ROUTES_MOD_KEY
            rmod = mc[k] if k in mc else config.MOD_CONFIG_ROUTES_MOD_DEFAULT
            m = import_module(p + '.' + rmod)
            k = config.MOD_CONFIG_MOD_VAR_KEY
            mvar = mc[k] if k in mc else config.MOD_CONFIG_MOD_VAR_DEFAULT
            mod = getattr(m, mvar)
            inject(m, mc)
            k = config.MOD_CONFIG_URL_PREFIX_KEY
            pre = mc[k] if k in mc else None
            self.app.register_blueprint(mod, url_prefix=pre)
Beispiel #7
0
class Server:

    JSON_HEADER = {"Content-Type": "application/json"}

    def __init__(self, ctl_port):
        self.web_app = Flask(__name__)
        self.ctl_port = ctl_port
        self.web_app.add_url_rule("/", "index", self.index, methods=["GET", "POST"])
        self.web_app.add_url_rule("/register", "register", self.register, methods=["POST"])
        self.web_app.add_url_rule("/deregister", "deregister", self.deregister, methods=["DELETE"])
        self.web_app.add_url_rule("/update", "update", self.update, methods=["POST"])
        self.web_app.add_url_rule("/transfer", "transfer", self.transfer, methods=["POST"])
        self.web_app.add_url_rule("/file/<sha>", "find_file", self.find_file, methods=["GET"])
        self.web_app.add_url_rule("/heartbeat", "heartbeat", self.heartbeat, methods=["POST"])
        self.web_app.register_error_handler(405, self.bad_method)
        self.db = db.Database()

    def run(self):
        self.web_app.run(host="0.0.0.0", port=self.ctl_port)

    def bad_method(self, error=None):
        return '{"status":"ERROR_METHOD_NOT_ALLOWED"}', 405, Server.JSON_HEADER

    def bad_request(self, error=None, msg=""):
        return '{"status":"ERROR_BAD_REQUEST","msg":"' + msg + '"}', 400, Server.JSON_HEADER

    def forbidden(self, error=None):
        return '{"status":"ERROR_FORBIDDEN"}', 403, Server.JSON_HEADER

    def success(self):
        return '{"status":"OK"}', 200, Server.JSON_HEADER

    def index(self):
        if request.method == "POST":
            return '{"json":"test_post"}', 200, Server.JSON_HEADER
        else:
            return '{"json":"test_get"}', 200, Server.JSON_HEADER

    def register(self):
        json_dict = request.get_json()
        try:
            client = Client(json_dict)
            if self.db.add_client(client):
                return self.success()
            else:
                return self.bad_request(msg="Client Exist")
        except Exception, e:
            print(traceback.print_exc())
            return self.bad_request(msg="JSON Error")
Beispiel #8
0
def create_app(config_override: Mapping = None) -> Flask:
    """Create the flask app for the debug server.

    Parameters:
        config_override:
            Dict containing custom configuration to apply after loading the
            normal config. Useful for testing.
    """
    config_override = {} if config_override is None else config_override
    # TODO: Rename app, no longer used only for debugging
    app = Flask('stuffrdebugserver',
                instance_relative_config=True,
                static_url_path='',
                template_folder='static')
    app.config.from_object('config.default')
    app.config.from_envvar('STUFFR_SETTINGS')
    app.config.from_mapping(config_override)
    app.json_encoder = StuffrJSONEncoder
    logger.set_logger(app.logger)

    db.init_app(app)
    security = Security(app, user_store, confirm_register_form=StuffrRegisterForm)
    security.unauthorized_handler(api_unauthenticated_handler)
    Mail(app)

    # In debug mode Swagger documentation is served at root
    if not app.config['DEBUG']:
        def api_root_view():
            """Provide a link to API documentation if root accessed."""
            return error_response(
                'TODO: Link to documentation here', HTTPStatus.NOT_FOUND)
        blueprint_api.add_url_rule('/', 'apiindex', api_root_view)

    app.register_blueprint(blueprint_simple, url_prefix='/simple')
    app.register_blueprint(blueprint_api, url_prefix='/api')

    def default404(e):
        """Default handler for 404."""
        # TODO: Conditional JSON/HTML response (for simple mode)
        return error_response(e.description, HTTPStatus.NOT_FOUND)
    app.register_error_handler(HTTPStatus.NOT_FOUND, default404)

    # TODO: Make friendlier error message (40x or 50x?)
    app.add_url_rule('/', 'index', lambda: "You probably shouldn't be here")

    return app
Beispiel #9
0
class RestProvider(APIProvider):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.app = Flask("iris-rest")

        # Make sure we have config
        if 'rest' not in self.daemon.config.providers:
            raise Exception("No config for RestProvider (need config.providers.rest)")

        self.config = self.daemon.config.providers['rest']

        # Grab config vars
        self.host = self.config.get("host", "0.0.0.0")
        self.port = self.config.get("port", "8080")
        self.auth = self.config.get("auth")

        # Meta Registers
        self.app.register_error_handler(APIBase, self.handle_response)
        self.app.before_request(self.before_request)

        self.app.add_url_rule('/', 'index', self.route_index)

        # Controllers
        self.app.register_blueprint(ShardController(self).bp)
        self.app.register_blueprint(EntryController(self).bp)

    def before_request(self):
        if self.auth and request.headers.get("IRIS_AUTH") != self.auth:
            raise APIError("Invalid Credentials", 1000)

    def handle_response(self, obj):
        return jsonify(obj.data)

    def run(self):
        super().run()
        self.app.run(host=self.host, port=self.port)

    def route_index(self):
        raise APIResponse({
            "stats": {
                "uptime": float("{0:.4f}".format(time.time() - self.daemon.start_time)),
            },
            "version": __VERSION__
        })
Beispiel #10
0
def create_app(config_object=None):
    app = Flask(__name__)

    app.config.from_object('config.default')
    if config_object:
        app.config.from_object(config_object)

    app.add_url_rule('/', view_func=views.get_apps, methods=['GET'])
    app.add_url_rule('/login', view_func=views.get_login, methods=['GET'])
    app.add_url_rule('/login', view_func=views.do_login, methods=['POST'])
    app.add_url_rule('/logout', view_func=views.do_logout, methods=['GET'])
    app.add_url_rule('/deploy', view_func=views.do_deploy, methods=['POST'])
    app.add_url_rule('/ping/ping', view_func=views.healthcheck, methods=['GET'])
    app.register_error_handler(WBAPIHTTPError, views.wb_error_handler)
    app.register_error_handler(Exception, views.generic_error_handler)
    app.before_request(get_api_before_request)

    return app
Beispiel #11
0
def create_app(db_create_all=False):
    app = Flask(__name__)

    # Configurations
    app.config.from_object('config')

    # Blueprints
    from claimstore.modules.claims.restful import claims_restful
    from claimstore.modules.claims.views import claims_views

    app.register_blueprint(claims_views)
    app.register_blueprint(claims_restful)

    # Init databse
    db.init_app(app)
    if db_create_all:
        # Create schema
        with app.app_context():
            db.create_all()
            # Populate with predefined predicates
            from claimstore.modules.claims.models import Predicate
            predicates = [
                'is_same_as',
                'is_different_than',
                'is_erratum_of',
                'is_superseded_by',
                'is_cited_by',
                'is_software_for',
                'is_dataset_for'
            ]
            for pred_name in predicates:
                if not Predicate.query.filter_by(name=pred_name).first():
                    predicate = Predicate(name=pred_name)
                    db.session.add(predicate)
            db.session.commit()

    # Register exceptions
    app.register_error_handler(InvalidUsage, handle_invalid_usage)

    @app.errorhandler(404)
    def not_found(error):
        return render_template('404.html'), 404

    return app
Beispiel #12
0
def create_app(app_name='hermes_cms', config_obj=None, blueprints=None):
    """

    :type app_name: str
    :param app_name:
    :type config_obj: object|None
    :param config_obj:
    :type blueprints: list|None
    :param blueprints:
    :return:
    """
    app = Flask(app_name)

    if config_obj:
        app.config.from_object(config_obj)
    else:
        # todo this needs to be in Configuration Registry
        app.secret_key = 'testing-key'

    blueprints = blueprints or Registry().get('blueprint').get('blueprint')

    for blueprint in blueprints:
        module = __import__(blueprint['name'], fromlist=blueprint['from'])
        route = getattr(module, blueprint['from'])
        if hasattr(module, 'url_rules'):
            module.url_rules()

        app.register_blueprint(route, **blueprint.get('kwargs', {}))

    def error_handler(error):
        log.exception(str(error))
        return Response(response=json.dumps({
            'notify_msg': {
                'title': 'Server Error',
                'message': 'An internal server error occurred.',
                'type': 'success'
            }
        }), content_type='application/json', status=500)

    app.register_error_handler(Exception, error_handler)
    app.before_request_funcs.setdefault(None, []).append(db_connect)
    app.after_request_funcs.setdefault(None, []).append(db_close)

    return app
Beispiel #13
0
def create_app(configuration=None, instance_path='/etc/ihatemoney',
               instance_relative_config=True):
    app = Flask(
        __name__,
        instance_path=instance_path,
        instance_relative_config=instance_relative_config)

    # If a configuration object is passed, use it. Otherwise try to find one.
    load_configuration(app, configuration)
    app.wsgi_app = PrefixedWSGI(app)

    # Get client's real IP
    # Note(0livd): When running in a non-proxy setup, is vulnerable to requests
    # with a forged X-FORWARDED-FOR header
    app.wsgi_app = ProxyFix(app.wsgi_app)

    validate_configuration(app)
    app.register_blueprint(web_interface)
    app.register_blueprint(api)
    app.register_error_handler(404, page_not_found)

    # Configure the a, root="main"pplication
    setup_database(app)

    mail = Mail()
    mail.init_app(app)
    app.mail = mail

    # Jinja filters
    app.jinja_env.filters['minimal_round'] = minimal_round

    # Translations
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # get the lang from the session if defined, fallback on the browser "accept
        # languages" header.
        lang = session.get('lang', request.accept_languages.best_match(['fr', 'en']))
        setattr(g, 'lang', lang)
        return lang

    return app
Beispiel #14
0
def make_json_exception_app(name, **kwargs):
    '''
    Taken from snippet http://flask.pocoo.org/snippets/83/

    Method to make Flask app that returns all user unhandled
    exceptions as json by default
    '''
    def make_json_error(error):
        response = jsonify(message=str(error))
        response.status_code =\
            error.code if isinstance(error, HTTPException) else 500

        return response

    app = Flask(name, **kwargs)

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

    return app
Beispiel #15
0
def create_app(environment='ponyexpress.config.configuration.DefaultConfig'):
    app = Flask(__name__)

    # Load configuration
    app.config.from_object(environment)
    app.config.from_pyfile('/etc/pony-express/ponyexpress.cfg', True)

    # Database
    from ponyexpress.database import db

    db.init_app(app)

    # Register blueprints
    from ponyexpress.api.v1.collector import collector
    from ponyexpress.api.v1.query import query
    from ponyexpress.api.v1.updater import updater

    app.register_blueprint(collector)
    app.register_blueprint(query)
    app.register_blueprint(updater)

    # Error handler
    app.register_error_handler(InvalidAPIUsage, handle_invalid_usage)

    if app.debug is not True and app.testing is not True:
        import logging

        from logging.handlers import RotatingFileHandler

        file_handler = RotatingFileHandler(app.config.get('REQUEST_LOG', 'ponyexpress.log'), maxBytes=1024 * 1024 * 100,
                                           backupCount=20)
        file_handler.setLevel(logging.INFO)

        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        file_handler.setFormatter(formatter)

        app.logger.addHandler(file_handler)

        app.before_request(log_entry)

    return app
Beispiel #16
0
def create_app():
    app = Flask(__name__)
    Babel(app)

    with app.app_context():
        from . import index, youtube, vimeo, custom, autocomplete
        from newsic.functions import not_found
        
        app.register_blueprint(index.bp)
        app.register_blueprint(index.bp, url_prefix='/<lang_code>')
        app.register_blueprint(youtube.bp)
        app.register_blueprint(youtube.bp, url_prefix='/<lang_code>')
        app.register_blueprint(vimeo.bp)
        app.register_blueprint(vimeo.bp, url_prefix='/<lang_code>')
        app.register_blueprint(custom.bp)
        app.register_blueprint(custom.bp, url_prefix='/<lang_code>')
        app.register_blueprint(autocomplete.bp)

        app.register_error_handler(404, not_found)

    return app
Beispiel #17
0
def create_app():
    app = Flask(__name__)

    import os

    app.config.from_object(os.environ["APP_SETTINGS"])

    from .core import redis

    redis.init_app(app)

    from tasks.views import TasksView

    TasksView.register(app)

    from profiles.views import ProfilesView

    ProfilesView.register(app)

    from .handlers import not_found, bad_request, internal_error
    from .exceptions import DoesNotExist, ValidationError

    app.register_error_handler(DoesNotExist, not_found)
    app.register_error_handler(ValidationError, bad_request)
    app.register_error_handler(500, internal_error)

    @app.after_request
    def after_request(response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
        response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE")
        return response

    return app
Beispiel #18
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(settings)

    DB.init_app(app)
    redis_store.init_app(app)
    routes.configure_routes(app)
    configure_login(app)
    configure_logger(app)

    app.register_error_handler(400, error_400)
    app.register_error_handler(404, error_404)
    app.register_error_handler(405, error_405)
    app.register_error_handler(Exception, exception_handler)

    app.jinja_env.filters["json"] = json.dumps

    def epoch_to_date(s):
        import datetime

        return datetime.datetime.fromtimestamp(s).strftime("%B %-d, %Y")

    def epoch_to_ts(s):
        import datetime

        return datetime.datetime.fromtimestamp(s).strftime("%m-%-d-%Y %H:%M")

    app.jinja_env.filters["epoch_to_date"] = epoch_to_date
    app.jinja_env.filters["epoch_to_ts"] = epoch_to_ts
    app.config["CDN_DOMAIN"] = os.getenv(
        "CDN_DOMAIN", re.sub("https?://", "", settings.SERVICE_URL)
    )
    app.config["CDN_HTTPS"] = True
    cdn.init_app(app)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            if app.config["TESTING"]:
                # When testing, celery tasks are called eagerly, from the same thread
                # so don't push an app context, the request's app context is already there
                return self.run(*args, **kwargs)
            else:
                with app.app_context():
                    g.log = structlog.get_logger().new()
                    return self.run(*args, **kwargs)

    celery.Task = ContextTask

    if not app.debug and not app.testing:
        configure_ssl_redirect(app)

    Limiter(
        app,
        key_func=get_ipaddr,
        global_limits=[settings.RATE_LIMIT],
        storage_uri=settings.REDIS_RATE_LIMIT,
    )

    return app
Beispiel #19
0
def create_app(server):
    '''Create Flask application and attach TAXII server
    instance ``server`` to it.

    :param `opentaxii.server.TAXIIServer` server: TAXII server instance

    :return: Flask app
    '''

    app = Flask(__name__)

    app.taxii = server

    app.add_url_rule("/<path:relative_path>", "opentaxii_services_view",
            _server_wrapper(server), methods=['POST', 'OPTIONS'])

    app.register_blueprint(management, url_prefix='/management')

    app.register_error_handler(500, handle_internal_error)
    app.register_error_handler(StatusMessageException, handle_status_exception)

    return app
Beispiel #20
0
Datei: app.py Projekt: beav/crane
def create_app():
    """
    Creates the flask app, loading blueprints and the configuration.

    :return:    flask app
    :rtype:     Flask
    """
    init_logging()

    app = Flask(__name__)
    app.register_blueprint(v1.section)
    app.register_error_handler(exceptions.HTTPError, app_util.http_error_handler)

    config.load(app)
    # in case the config says that debug mode is on, we need to adjust the
    # log level
    set_log_level(app)
    data.start_monitoring_data_dir(app)
    search.load_config(app)

    logging.getLogger(__name__).info('application initialized')
    return app
Beispiel #21
0
def create_app(environment='ponyexpress.config.configuration.DevelopmentConfig'):
    app = Flask(__name__)

    # Load configuration
    #TODO: load configuration depending on environment
    app.config.from_object(environment)
    app.config.from_envvar('PONYEXPRES_CFG', True)

    # Database
    from ponyexpress.database import db
    db.init_app(app)

    # Register blueprints
    from ponyexpress.api.v1.collector import collector
    from ponyexpress.api.v1.query import query

    app.register_blueprint(collector)
    app.register_blueprint(query)

    # Error handler
    app.register_error_handler(InvalidAPIUsage, handle_invalid_usage)

    return app
Beispiel #22
0
def create_app(config_obj=None):
    """
    Create a Flask application object.

    :return: a Flask application object
    :rtype: flask.Flask
    """
    app = Flask(__name__)
    if config_obj:
        app.config.from_object(config_obj)
    else:
        load_config(app)

    if app.config['ENV'] != 'development':
        if app.config['SECRET_KEY'] == 'replace-me-with-something-random':
            raise RuntimeError('You need to change the SECRET_KEY configuration for production')
    for config in ('AD_DOMAIN', 'AD_LDAP_URI', 'AD_USERS_GROUP', 'AD_ADMINS_GROUP',
                   'AD_SERVICE_USERNAME', 'AD_SERVICE_PASSWORD', 'SQLALCHEMY_DATABASE_URI'):
        if not app.config.get(config):
            raise RuntimeError('You need to set the "{0}" setting'.format(config))

    init_logging(app)
    db.init_app(app)
    migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrations')
    Migrate(app, db, directory=migrations_dir)
    app.cli.command()(create_db)

    for status_code in default_exceptions.keys():
        app.register_error_handler(status_code, json_error)
    app.register_error_handler(ValidationError, json_error)
    app.register_error_handler(ConfigurationError, json_error)
    app.register_error_handler(ADError, json_error)

    app.after_request(insert_headers)
    app.register_blueprint(api_v1, url_prefix='/api/v1')

    jwt = JWTManager(app)
    jwt.token_in_blacklist_loader(BlacklistedToken.is_token_revoked)
    jwt.user_claims_loader(add_jwt_claims)
    app.cli.command()(prune_blacklisted_tokens)

    return app
Beispiel #23
0
Datei: app.py Projekt: janLo/sipa
    )


def errorpage(e):
    if e.code in (404,):
        flash(gettext(u"Seite nicht gefunden!"), "warning")
    elif e.code in (401, 403):
        flash(gettext(
            u"Sie haben nicht die notwendigen Rechte um die Seite zu sehen!"),
            "warning")
    else:
        flash(gettext(u"Es ist ein Fehler aufgetreten!"), "error")
    return redirect(url_for("index"))


app.register_error_handler(401, errorpage)
app.register_error_handler(403, errorpage)
app.register_error_handler(404, errorpage)


@app.errorhandler(OperationalError)
def exceptionhandler_sql(ex):
    """Handles global MySQL errors (server down).
    """
    flash(u"Connection to SQL server could not be established!", "error")
    # todo check if infinite redirection might still occur
    # Proviously, requesting `/` w/o having a connection to the mysql database
    # would result in an infinite loop of redirects to `/` since
    # OperationalError is being handled globally.
    # In the latter case, the cause was the request of the traffic chart data.
    # A quick fix was catching it and returning an error status.
Beispiel #24
0

from backend.views.users import user_blueprint
from backend.views.products import product_blueprint
from backend.views.prices import price_blueprint
from backend.views.businesses import business_blueprint
from backend.views.ocr import ocr_blueprint
from backend.utils import json_error


app = Flask(__name__, static_folder="frontend")
app.config["PROPAGATE_EXCEPTIONS"] = False
app.config["SECRET_KEY"] = '\x85\xe7\x98?L\xfaKa2\xbdQ\xef\xa5&\x03\x17\x9bj\x17 \xbc\xc8j\xbb'

json_error_500 = partial(json_error, status_code=500)
app.register_error_handler(500, json_error_500)


# Configure logging
log_format = logging.Formatter("%(asctime)s [%(name)s.%(funcName)s():%(lineno)d]\n\t%(levelname)8s: %(message)s\n")

logger = logging.getLogger()

stderr_handler = logging.StreamHandler()
stderr_handler.setLevel(logging.DEBUG)
stderr_handler.setFormatter(log_format)
logger.addHandler(stderr_handler)

file_handler = RotatingFileHandler("web.log", maxBytes=50000, backupCount=2)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(log_format)
Beispiel #25
0
class Server:
    """
    REST API server
    """
    auth = HTTPBasicAuth()

    def __init__(self):
        self.process = None
        self.app = Flask(__name__)
        self.api = Api(self.app)

        # initialize SSL context
        self.context = ('appqos.crt', 'appqos.key')

        self.api.add_resource(Apps, '/apps')
        self.api.add_resource(App, '/apps/<app_id>')
        self.api.add_resource(Pools, '/pools')
        self.api.add_resource(Pool, '/pools/<pool_id>')
        self.api.add_resource(Stats, '/stats')
        self.api.add_resource(Caps, '/caps')
        self.api.add_resource(Reset, '/reset')

        self.app.register_error_handler(RestError, Server.error_handler)


    def start(self, host, port, debug=False):
        """
        Start REST server

        Parameters:
            host: address to bind to
            port: port to bind to
            debug(bool): Debug flag

        Returns:
            0 on success
        """

        for ssl_ctx_file in self.context:
            if not os.path.isfile(ssl_ctx_file):
                log.error("SSL cert or key file missing.")
                return -1

        self.process = multiprocessing.Process(target=self.app.run,
                                               kwargs={'host': host,
                                                       'port': port,
                                                       'ssl_context': self.context,
                                                       'debug': debug,
                                                       'use_reloader': False,
                                                       'processes': 1})
        self.process.start()
        return 0


    def terminate(self):
        """
        Terminates server
        """
        os.kill(self.process.pid, signal.SIGINT)
        sleep(1)
        if self.process.is_alive():
            self.process.terminate()
        self.process.join()


    @staticmethod
    def error_handler(error):
        """
        Error handler

        Parameters:
            error: error
        """
        response = {"message": error.message}
        return json.dumps(response), error.code


    @staticmethod
    @auth.verify_password
    def verify(username, password):
        """
        Authenticate user, HTTP Basic Auth

        Parameters:
            username: Username
            password: Password

        Returns:
            Authentication result (bool)
        """
        if not (username and password):
            return False
        if 'auth' in common.CONFIG_STORE.get_config():
            if username == common.CONFIG_STORE.get_config()['auth']['username'] and \
                password == common.CONFIG_STORE.get_config()['auth']['password']:
                return True
        return False
Beispiel #26
0
from flask import Flask, Blueprint
from flask.ext.sqlalchemy import SQLAlchemy
import os
import os.path as op

# Initialize app
app = Flask(__name__)
app.debug = True
app.config.from_object('config')
#os.environ['PYTHON_EGG_CACHE'] = '/tmp/tmp2'
#db = SQLAlchemy(app)

from werkzeug.exceptions import default_exceptions, HTTPException
from app.views import error_handler
for exception in default_exceptions:
	app.register_error_handler(exception, error_handler)

from app.views import mod as mainModule
app.register_blueprint(mainModule)


#  For full text search
#import flask.ext.whooshalchemy as whooshalchemy
#from models import File, Gene, Condition

#whooshalchemy.whoosh_index(app, File)
#whooshalchemy.whoosh_index(app, Gene)
#whooshalchemy.whoosh_index(app, Condition)
Beispiel #27
0
    """A generic error handler"""
    return render_template(template, message=message), code


def not_found(message=None):
    """A generic 404 handler"""
    message = message or 'Page not found.'
    return error(404, message, 'errors/404.html')


def internal_server_error(message=None):
    """A generic 500 handler"""
    message = message or 'Something went wrong.'
    return error(500, message, 'errors/500.html')

app.register_error_handler(404, not_found)
app.register_error_handler(500, internal_server_error)


@app.context_processor
def catchy_thing():
    return dict(catchy=random.choice([
        'is awesome!',
        'is sweeter than honey!',
        'makes my mouth water!',
        'is the cat\'s pajamas!',
        ('is a very mysterious and powerful site and it\'s mystery is only '
         'exceeded by it\'s power.'),
        'is a banana stand.',
        'can do the kessel run in 11 parsecs.',
    ]))
Beispiel #28
0
class ArtBot(object):

    def __init__(self):
        try:
            with open('config.json', 'r') as configFile:
                self.config = json.load(configFile)
        except Exception as e:
            print('Unable to read config.json!')
            print(e)
            sys.exit(-1)

        self.app = Flask(__name__, static_folder='static')

        self.dbDict = None
        self.initDb()

        if self.config['USE_PIXIV']: self.pixiv = Pixiv(self.dbDict, self.config)
        if self.config['USE_DEVIANTART']: self.deviantart = DeviantArt(self.dbDict, 'http://localhost:{}{}'.format(self.config['PORT'], DA_AUTH_REDIRECT))
        if self.config['USE_ARTSTATION']: self.artstation = ArtStation(self.dbDict, self.config['ARTSTATION_USERNAME'])

        self.app.add_url_rule('/', 'index', self.index)
        self.app.add_url_rule('/getWorks', 'getWorks', self.getWorks)
        self.app.add_url_rule('/authorizeDeviantart', 'authorizeDeviantart', self.authorizeDeviantart)
        self.app.add_url_rule(DA_AUTH_REDIRECT, 'deviantartAuthorizationRedirect', self.deviantartAuthorizationRedirect)

        self.app.register_error_handler(DeviantArtApiError, self.handle_invalid_usage)

        self.app.run(debug=True, port=self.config['PORT'])


    def initDb(self):
        if os.path.isfile(DB_FILENAME):
            with open(DB_FILENAME, 'rb') as dbFile:
                try:
                    self.dbDict = pickle.load(dbFile)
                except Exception as e:
                    print('Exception loading db file:')
                    print(e)

        if not isinstance(self.dbDict, dict):
            print('Unable to parse db file, defaulting to empty db')
            self.dbDict = {}

        if not self.dbDict.get('works'): self.dbDict['works'] = {}


    def index(self):
        return send_file('static/index.html')


    def getWorks(self):
        if self.config['USE_DEVIANTART']: self.deviantart.loadWorks()
        if self.config['USE_PIXIV']:      self.pixiv.loadWorks()
        if self.config['USE_ARTSTATION']: self.artstation.loadWorks()

        works = list(sorted(self.dbDict['works'].values(), key=lambda x: x['imageTimestamp'], reverse=True))[:self.config['MAX_WORKS_ON_PAGE']]

        self.cleanDb(works)
        self.loadExtraWorkInfo()
        self.persistDb()
        return json.dumps(works)


    def loadExtraWorkInfo(self):
        if self.config['USE_ARTSTATION']: self.artstation.loadExtraWorkInfo()


    def cleanDb(self, works):
        discard = list(sorted(self.dbDict['works'].items(), key=lambda x: x[1]['imageTimestamp'], reverse=True))[self.config['MAX_WORKS_ON_PAGE']:]
        [self.dbDict['works'].pop(key) for (key, val) in discard]

        # Clean images
        keepImages = itertools.chain(*(work['imageUrls'] for work in works))
        keepImages = set(os.path.split(url)[1] for url in keepImages if not url.startswith('http'))
        existingImages = set(os.path.split(url)[1] for url in os.listdir(self.config['PIXIV_DOWNLOAD_DIRECTORY']))
        imagesToRemove = existingImages - keepImages

        [os.remove(os.path.join(self.config['PIXIV_DOWNLOAD_DIRECTORY'], name)) for name in imagesToRemove]

        # Clean avatars
        keepAvatars = (work['authorAvatarUrl'] for work in works)
        keepAvatars = set(os.path.split(url)[1] for url in keepAvatars if not url.startswith('http'))
        existingAvatars = set(os.path.split(url)[1] for url in os.listdir(self.config['PIXIV_AVATAR_DIRECTORY']))
        avatarsToRemove = existingAvatars - keepAvatars

        [os.remove(os.path.join(self.config['PIXIV_AVATAR_DIRECTORY'], name)) for name in avatarsToRemove]


    def persistDb(self):
        print('Persisting to disk')
        with open(DB_FILENAME, 'wb') as dbFile:
            pickle.dump(self.dbDict, dbFile)


    def authorizeDeviantart(self):
        return render_template('authorizeDeviantart.html', url=self.deviantart.getAuthorizationUrl())


    def deviantartAuthorizationRedirect(self):
        self.deviantart.handleAuthorizationCallback(request)
        return redirect('/')


    def handle_invalid_usage(self, error):
        print('ERROR HANDLING')
        print(error.message)
        print(self.deviantart.token)
        response = jsonify(error.message)
        response.status_code = error.status_code
        return response
Beispiel #29
0
    else:
        check_symbols = True

    # To reduce computation issues on single-threaded server, institute a timeout
    # for requests. If it takes longer than this to process, return an error.
    # This cannot interrupt numpy's computation, so care must be taken in selecting
    # a value for MAX_REQUEST_COMPUTATION_TIME.
    try:
        with TimeoutProtection(MAX_REQUEST_COMPUTATION_TIME):
            response_dict = check(test_str, target_str, symbols, check_symbols, description)
            return jsonify(**response_dict)
    except TimeoutException, e:
        print "ERROR: %s - Request took too long to process, aborting!" % type(e).__name__
        print "=" * 50
        error_dict = dict(target=target_str, test=test_str, error="Request took too long to process!")
        return jsonify(**error_dict)


@app.route("/", methods=["GET"])
def ping():
    return jsonify(code=200)


if __name__ == "__main__":
    # Make sure all outgoing error messages are in JSON format.
    # This will only work provided debug=False - otherwise the debugger hijacks them!
    for code in default_exceptions.iterkeys():
        app.register_error_handler(code, make_json_error)
    # Then run the app
    app.run(port=5000, host="0.0.0.0", debug=False)
book_view = BooksView.as_view('book_view')
app.add_url_rule('/books', view_func=book_view, methods=['POST', 'GET', 'PUT', 'DELETE'])

book_profile_view = BookProfileView.as_view('book_profile_view')
app.add_url_rule('/books/<int:book_id>', view_func=book_profile_view, methods=['GET'])

search_view = BookSearchView.as_view('search_view')
app.add_url_rule('/search', view_func=search_view, methods=['POST', 'GET'])

request_view = RequestView.as_view('request')
app.add_url_rule(rule='/requests/<int:request_id>', view_func=request_view,
                 methods=['PUT', 'DELETE'])
app.add_url_rule(rule='/books/<int:book_id>/requests', view_func=request_view,
                 methods=['POST'])
app.add_url_rule(rule='/requests', view_func=request_view,
                 methods=['GET'])

decline_request_view = DeclineRequestView.as_view('decline_request')
app.add_url_rule(rule='/requests/decline/<int:request_id>', view_func=decline_request_view,
                 methods=['POST'])

req_history_view = RequestHistoryView.as_view("req_history_view")
app.add_url_rule(rule="/requests/history", view_func=req_history_view, methods=['GET'])


app.register_error_handler(404, page_not_found)
app.register_error_handler(403, forbidden)
app.register_error_handler(410, gone)
app.register_error_handler(500, internal_server_error)