Example #1
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
Example #2
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
Example #3
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
Example #4
0
File: server.py Project: csu/modapi
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)
Example #5
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")
Example #6
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
Example #7
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
Example #8
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__}
        )
Example #9
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
Example #10
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
Example #11
0
def create_app(root: str, config: str) -> Flask:
    """Create a new Flask application with the provided configuration.

    :param root: The application root module name.
    :param config: The application configuration mode.
    """
    app = Flask(__name__)
    app.config.from_object(CONFIG_PATH_FORMAT % (root, config))

    if app.config["INIT"]["debug"]:
        print(LOG_MODE_DEBUG)
    else:
        print(LOG_MODE_PRODUCTION)

    if app.config["GOOGLECLIENTID"]:
        print(LOG_ID_FORMAT % app.config["GOOGLECLIENTID"])
    else:
        print(LOG_ID_NOT_FOUND)

    # Async socket initialization
    eventlet.monkey_patch()
    socketio.init_app(app)

    # Configuration for mySQL database
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = app.config["DATABASE_URL"].replace("mysql", "mysql+pymysql", 1)
    db.init_app(app)

    # Configuration for login sessions
    app.secret_key = app.config["SECRET_KEY"]
    login_manager.init_app(app)

    # Flask Debug Toolbar
    toolbar.init_app(app)

    # Database migration management
    migrate.init_app(app, db)
    migration_manager(app)

    from .public.views import public
    from .queue.views import queue
    from .admin.views import admin
    from .dashboard.views import dashboard

    BLUEPRINTS = [public, queue, admin, dashboard]

    for blueprint in BLUEPRINTS:
        print(' * Registering blueprint "%s"' % blueprint.name)
        app.register_blueprint(blueprint)

    # subdomain routes with special urls
    app.register_blueprint(admin, url_prefix="/subdomain/<string:queue_url>/admin")
    app.register_blueprint(queue, url_prefix="/subdomain/<string:queue_url>")

    # register error handlers
    app.register_error_handler(401, standard_error)
    app.register_error_handler(404, error_not_found)
    app.register_error_handler(500, error_server)

    return app
Example #12
0
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_blueprint(crane.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
Example #13
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
Example #14
0
        check_symbols = str(body["check_symbols"]).lower() == "true"
    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)
Example #15
0
@app.route("/")
def hello_world():
    raise Exception


# list of tuples in (error_code, html_page) format
_handlers = (
    [(400, "400.html"), (403, "403.html"), (404, "404.html")]
    + [(error_code, "4xx.html") for error_code in [401, 402, 405, 406, 407, 408, 409, 410]]
    + [(error_code, "5xx.html") for error_code in [500, 501, 502, 503, 504, 505]]
)

for ec, ep in _handlers:

    def funky(_ec, _ep):
        def something_hundred_error(e):
            return render_template(os.path.join("errors", _ep)), _ec

        return something_hundred_error

    app.register_error_handler(ec, funky(ec, ep))

if __name__ == "__main__":
    try:
        if sys.argv[1] == "debug":
            app.debug = True
    except IndexError:
        pass

    app.run(host="0.0.0.0", port=5000, use_reloader=False)
Example #16
0
File: app.py Project: strebbin/sipa
        chart=render_traffic_chart,
    )


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.
    return redirect(url_for("index"))
Example #17
0
def create_app(config=None, **kwargs):
    """Create the WSGI application that is this app.

    In addition to the arguments documented below, this function accepts as a
    keyword agument all agruments to :py:class:`flask.Flask` except
    `import_name`, which is set to 'evesrp'. Additionally, the value of
    `instance_relative_config` has a default value of `True`.

    If the `config` argument isn't specified, the app will attempt to use the
    file 'config.py' in the instance folder if it exists, and will then fall
    back to using the value of the EVESRP_SETTINGS environment variable as a
    path to a config file.

    :param config: The app configuration file. Can be a Python
        :py:class:`dict`, a path to a configuration file, or an importable
        module name containing the configuration.
    :type config: str, dict
    """
    # Default instance_relative_config to True to let the config fallback work
    kwargs.setdefault("instance_relative_config", True)
    app = Flask("evesrp", **kwargs)
    app.request_class = AcceptRequest
    app.config.from_object("evesrp.default_config")
    # Push the instance folder path onto sys.path to allow importing from there
    sys.path.insert(0, app.instance_path)
    # Check in config is a dict, python config file, or importable object name,
    # in that order. Finally, check the EVESRP_SETTINGS environment variable
    # as a last resort.
    if isinstance(config, dict):
        app.config.update(config)
    elif isinstance(config, six.string_types):
        if config.endswith((".txt", ".py", ".cfg")):
            app.config.from_pyfile(config)
        else:
            app.config.from_object(config)
    elif config is None:
        try:
            app.config.from_pyfile("config.py")
        except OSError:
            app.config.from_envvar("EVESRP_SETTINGS")

    # Register SQLAlchemy monitoring before the DB is connected
    app.before_request(sqlalchemy_before)

    db.init_app(app)

    from .views.login import login_manager

    login_manager.init_app(app)

    before_csrf = list(app.before_request_funcs[None])
    csrf.init_app(app)
    # Remove the context processor that checks CSRF values. All it is used for
    # is the template function.
    app.before_request_funcs[None] = before_csrf

    # Hook up OAuth
    oauth.init_app(app)

    # Connect views
    from .views import index, error_page, update_navbar, divisions, login, requests, api

    app.add_url_rule(rule=u"/", view_func=index)
    for error_code in (400, 403, 404, 500):
        app.register_error_handler(error_code, error_page)
    app.after_request(update_navbar)
    app.register_blueprint(divisions.blueprint, url_prefix="/division")
    app.register_blueprint(login.blueprint)
    app.register_blueprint(requests.blueprint, url_prefix="/request")
    app.register_blueprint(api.api, url_prefix="/api")
    app.register_blueprint(api.filters, url_prefix="/api/filter")

    from .views import request_count

    app.add_template_global(request_count)

    from .json import SRPEncoder

    app.json_encoder = SRPEncoder

    # Configure the Jinja context
    # Inject variables into the context
    from .auth import PermissionType

    @app.context_processor
    def inject_enums():
        return {
            "ActionType": models.ActionType,
            "PermissionType": PermissionType,
            "app_version": __version__,
            "site_name": app.config["SRP_SITE_NAME"],
            "url_for_page": requests.url_for_page,
        }

    # Auto-trim whitespace
    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    init_app(app)

    return app
Example #18
0
cmdline_options, args = opt_parser.parse_args()

socketio = SocketIO()
app = Flask(__name__, static_url_path="")
app.config["SESSION_TYPE"] = "redis"
app.config["SESSION_KEY_PREFIX"] = "mxcube:session:"
app.config["SECRET_KEY"] = "nosecretfornow"


def exception_handler(e):
    err_msg = "Uncaught exception while calling %s" % request.path
    logging.getLogger("exceptions").exception(err_msg)
    return err_msg + ": " + traceback.format_exc(), 409


app.register_error_handler(Exception, exception_handler)
sess = Session()
sess.init_app(app)
app.debug = False
# this line important for socketio msg, otherwise no msg is sent...
socketio.init_app(app)

# the following test prevents Flask from initializing twice
# (because of the Reloader)
if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true":
    ###Initialization of the HardwareObjects
    # this is to allow Hardware Objects to do
    # 'from HardwareRepository import ...'
    sys.path.insert(0, os.path.dirname(__file__))
    from HardwareRepository import HardwareRepository as hwr, removeLoggingHandlers
Example #19
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
        message="You must be logged in to do that",
        action={"text": "Log in", "url": login_url},
    )


@app.errorhandler(utils.SessionExpired)
def session_expired(e):
    login_url = url_for("login.index", section="login-choices")
    return render_template(
        "error.html",
        page_title="Session expired",
        message="Your last action was more than a day ago "
        "and as a consequence your session has "
        "expired. Please login again.",
        action={"text": "Log in", "url": login_url},
    )


@app.errorhandler(utils.SessionUserDetailsIncomplete)
def session_user_details_incomplete(e):
    return redirect(url_for("login.user_details"))


@app.errorhandler(utils.SessionUserDisabled)
def session_user_disabled(e):
    return login.user_disabled_response()


# This handler must be added last, since the others are subclasses.
app.register_error_handler(utils.SessionInvalid, session_absent)
Example #21
0
File: app.py Project: rclanan/radar
def create_app():
    app = Flask(__name__)
    app.config.from_object("radar.default_settings")
    app.config.from_object("radar.web.default_settings")
    app.config.from_envvar("RADAR_SETTINGS")

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    login_manager.login_view = "auth.login"

    Markdown(app)

    mail.init_app(app)

    app.register_blueprint(radar_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(disease_groups_bp, url_prefix="/disease-groups")
    app.register_blueprint(units_bp, url_prefix="/units")
    app.register_blueprint(users_bp, url_prefix="/users")
    app.register_blueprint(patients_bp, url_prefix="/patients")
    app.register_blueprint(recruit_bp, url_prefix="/patients")
    app.register_blueprint(news_bp, url_prefix="/news")
    app.register_blueprint(stats_bp, url_prefix="/stats")

    patient_blueprints = [
        (diagnosis_bp, "/diagnosis"),
        (dialysis_bp, "/dialysis"),
        (genetics_bp, "/genetics"),
        (hospitalisations_bp, "/hospitalisations"),
        (results_bp, "/results"),
        (medications_bp, "/medications"),
        (pathology_bp, "/pathology"),
        (plasmapheresis_bp, "/plasmapheresis"),
        (renal_imaging_bp, "/renal-imaging"),
        (salt_wasting_bp, "/salt-wasting"),
        (transplants_bp, "/transplants"),
    ]

    patient_base = "/patients/<int:patient_id>"

    for bp, url_prefix in patient_blueprints:
        app.register_blueprint(bp, url_prefix=patient_base + url_prefix)

    app.before_request(require_login)
    app.before_request(force_password_change)

    # Register template filters
    app.add_template_filter(strftime)
    app.add_template_filter(year_format)
    app.add_template_filter(date_format)
    app.add_template_filter(datetime_format)
    app.add_template_filter(nl2br)
    app.add_template_filter(missing)
    app.add_template_filter(yn)
    app.add_template_filter(number_format)

    # Register template globals/functions
    app.add_template_global(url_for_order_by)
    app.add_template_global(url_for_page)
    app.add_template_global(url_for_per_page)

    # Register context processors (data available in all templates)
    app.context_processor(inject_navigation)
    app.context_processor(inject_delete_form)

    # Register error handlers
    app.register_error_handler(403, forbidden)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(500, internal_server_error)

    # Automatically set the created_user and modified_user
    event.listen(SignallingSession, "before_flush", before_flush_set_created_listener)
    event.listen(SignallingSession, "before_flush", before_flush_set_modified_listener)

    return app
Example #22
0
def create_instance():
    """
    Construct a new Flask instance and return it.
    """
    import os

    app = Flask(__name__)
    app.config.from_object("notifico.config")

    if app.config.get("NOTIFICO_ROUTE_STATIC"):
        # We should handle routing for static assets ourself (handy for
        # small and quick deployments).
        import os.path
        from werkzeug import SharedDataMiddleware

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/": os.path.join(os.path.dirname(__file__), "static")})

    if not app.debug:
        # If sentry (http://getsentry.com) is configured for
        # error collection we should use it.
        if app.config.get("SENTRY_DSN"):
            sentry.dsn = app.config.get("SENTRY_DSN")
            sentry.init_app(app)

    # Setup our redis connection (which is already thread safe)
    app.redis = Redis(host=app.config["REDIS_HOST"], port=app.config["REDIS_PORT"], db=app.config["REDIS_DB"])
    # Attach Flask-Cache to our application instance. We override
    # the backend configuration settings because we only want one
    # Redis instance.
    cache.init_app(
        app, config={"CACHE_TYPE": "redis", "CACHE_REDIS_HOST": app.redis, "CACHE_OPTIONS": {"key_prefix": "cache_"}}
    )
    # Attach Flask-Mail to our application instance.
    mail.init_app(app)
    # Attach Flask-SQLAlchemy to our application instance.
    db.init_app(app)

    # Update celery's configuration with our application config.
    celery.config_from_object(app.config)

    # Import and register all of our blueprints.
    from notifico.views.account import account
    from notifico.views.public import public
    from notifico.views.projects import projects
    from notifico.views.pimport import pimport
    from notifico.views.admin import admin

    app.register_blueprint(account, url_prefix="/u")
    app.register_blueprint(projects)
    app.register_blueprint(public)
    app.register_blueprint(pimport, url_prefix="/i")
    app.register_blueprint(admin, url_prefix="/_")

    # Register our custom error handlers.
    from notifico.views import errors

    app.register_error_handler(500, errors.error_500)

    # cia.vc XML-RPC kludge.
    from notifico.services.hooks.cia import handler

    handler.connect(app, "/RPC2")

    # Setup some custom Jinja2 filters.
    app.jinja_env.filters["pretty_date"] = pretty.pretty_date
    app.jinja_env.filters["plural"] = pretty.plural
    app.jinja_env.filters["fix_link"] = pretty.fix_link

    return app
Example #23
0
class Application(SingletonObject):
    # set default values
    _settings = {
        "port": 9000,
        "host": "127.0.0.1",
        "debug": False,
        "external_debug": False,
        "debug_level": 0,
        "output": "json",
        "enable_jsonp": False,
    }

    _flask = None
    # init internal objects
    cfg = None

    def __init__(self):
        self.cfg = Configuration.get_instance()
        self._log = alogger.getLogger(__name__, cfg=self.cfg)
        self._apply_settings()
        self._flask = Flask(__name__)
        self._flask.register_error_handler(404, self._error_404_handler)
        self._flask.register_error_handler(405, self._error_405_handler)
        self._flask.register_error_handler(500, self._error_500_handler)
        self._response_wrapper = ResponseWrapperFactory.get_wrapper(self._settings["output"])

        # serve static content, please use that possibility only for testing.
        # in production please use nginx, apache, etc for this.
        if self._settings["static_enabled"]:
            self._log.info(
                'Static content serving enabled, serving "%s" at mountpoint "%s"'
                % (self._settings["static_path"], self._settings["static_endpoint"])
            )
            self._flask.static_folder = self._settings["static_path"]
            self.serve_static_content()

    def _apply_settings(self):
        try:
            self._settings.update(
                {
                    "host": self.cfg.get("server.host", check_type=str),
                    "port": self.cfg.get("server.port", default=9000, check_type=int),
                    "debug": self.cfg.get("server.debug.enabled", default=False, check_type=bool),
                    "external_debug": self.cfg.get("server.debug.external_debug", default=False, check_type=bool),
                    "debug_level": self.cfg.get("server.debug.debug_level", default=0, check_type=int),
                    "enable_jsonp": self.cfg.get("server.api.enable_jsonp", default=False, check_type=bool),
                    "api_enabled": self.cfg.get("server.api.enabled", default=True, check_type=bool),
                    "static_enabled": self.cfg.get("server.static.enabled", default=False, check_type=bool),
                    "static_path": self.cfg.get("server.static.path", default="", check_type=str),
                    "static_index": self.cfg.get("server.static.index", default="", check_type=str),
                    "storage_api_enabled": self.cfg.get("server.storage-api.enabled", default=False, check_type=bool),
                    "storage_api_secret": self.cfg.get("server.storage-api.secret", default="", check_type=str),
                    "storage_module": self.cfg.get(
                        "server.storage-api.storage-module", default="storage", check_type=str
                    ),
                    "storage_api_check_token": self.cfg.get(
                        "server.storage-api.check_token", default=True, check_type=bool
                    ),
                    "endpoints": {
                        "api": self.cfg.get("server.api.endpoint", default="/api", check_type=str),
                        "static": self.cfg.get("server.static.endpoint", default="/", check_type=str),
                        "storage": self.cfg.get("server.storage-api.endpoint", default="/storage", check_type=str),
                    },
                }
            )
            if self._settings["endpoints"]["storage"] == "":
                self._settings["endpoints"]["storage"] = "/storage"
            # ToDo: Check endpoints to be not math one location

            if self._settings["endpoints"]["api"][-1:] == "/":
                self._settings["endpoints"]["api"] = self._settings["endpoints"]["api"][:-1]
            # set highest log level for flask to suppress info messages
            if not self.cfg.get("logging.enabled", default=False, check_type=bool):
                from flask import logging as flask_logging

                alogger.setLogLevel(flask_logging.getLogger("werkzeug"), "critiacal")
            else:
                from flask import logging as flask_logging

                not self.cfg.get("logging.url_log", default=True, check_type=bool) and alogger.setLogLevel(
                    flask_logging.getLogger("werkzeug"), "ERROR"
                )

            # for debugging we could ignore json transforms and rest notation
            if self._settings["debug"] and self._settings["debug_level"] >= 100:
                self._settings["output"] = "string"

            if self._settings["output"] != "json":  # disable jsonp if base filter is not json
                self._settings["enable_jsonp"] = False
        except KeyError:
            self._log.warning("Server settings not found (%s), use default ones", KeyError)
        except ValueError as err:
            self._log.error("Was passed unknown or wrong parameters. Please check configuration items, shutting down.")

    @property
    def settings(self):
        return self._settings

    def start(self):
        mode = "debug" if self._settings["debug"] else "normal"
        self._log.info("Starting server in %s mode on %s:%s", mode, self._settings["host"], self._settings["port"])
        flask_args = {
            "threaded": True,
            "host": self._settings["host"],
            "port": self._settings["port"],
            "debug": self._settings["debug"],
        }
        if self._settings["external_debug"] and self._settings["debug"]:
            flask_args["use_debugger"] = False
            flask_args["use_reloader"] = False

        self._load_views()

        # start server
        self._flask.run(**flask_args)

    def abort(self, code):
        abort(code)

    def _load_views(self):
        exclude_list = []
        include_list = []
        if not self._settings["storage_api_enabled"]:
            exclude_list.append("storage.index")
        else:
            include_list.append("storage.index")

        if self._settings["api_enabled"]:
            alist.views.load(disabled_views=exclude_list)
        elif len(include_list) > 0:
            alist.views.load(allowed_views=include_list)

    def _error_404_handler(self, e):
        return self._response_wrapper.response_http_exception("", 404, Exception("Not found")), 404

    def _error_500_handler(self, e):
        return self._response_wrapper.response_http_exception("", 500, e), 500

    def _error_405_handler(self, e):
        return self._response_wrapper.response_http_exception("", 405, e), 405

    def route(self, rule, **options):
        """
     Stub to pass decorator back to flask, actually doing almost same thing as flask decorator

     Difference is in return value, view can return any value which could pass stringify str() function in debug mode
     and serialization via json for normal mode
    """
        # here is decorator work
        def decorator(f):
            self.add_route(rule, f, **options)

        return decorator

    def add_route(self, rule, f, **options):
        # here we make some trick, and push back only json string, except we are in debug mode
        def wrapper(*args, **kwargs):
            req_args = request.args.to_dict()
            if "args" in f.__code__.co_varnames:
                kwargs["args"] = req_args
            if "headers_dict" in f.__code__.co_varnames:
                headers = {}
                for item in request.headers:
                    headers.update({item[0]: item[1]})
                kwargs["headers_dict"] = headers
            if "headers" in f.__code__.co_varnames:
                kwargs["headers"] = request.headers

            if self._settings["enable_jsonp"] and "jsonp" in req_args:
                return ResponseWrapperFactory.get_wrapper("jsonp").response_by_function_call(
                    request.path, f, flags={"callback": req_args["jsonp"]}, *args, **kwargs
                )

            return self._response_wrapper.response_by_function_call(request.path, f, *args, **kwargs)

        endpoint = options.pop("endpoint", None)
        wrapper.__name__ = "%s_wrap" % f.__name__
        self._flask.add_url_rule("%s%s" % (self._settings["endpoints"]["api"], rule), endpoint, wrapper, **options)

        return f

    def serve_static_content(self):
        def static_route(path):
            return self._flask.send_static_file(path)

        def static_index():
            return self._flask.send_static_file(self._settings["static_index"])

        route = "%s/<path:path>" % (
            self._settings["endpoints"]["static"] if self._settings["endpoints"]["static"] != "/" else ""
        )

        self._flask.add_url_rule(self._settings["endpoints"]["static"], view_func=static_index)
        self._flask.add_url_rule(route, view_func=static_route)