Beispiel #1
1
def setup_app(warnings=None):
    if warnings is None:
        warnings = []

    app = Flask(__name__)
    cfy_config = config.instance()

    _detect_debug_environment()

    app.logger_name = "manager-rest"
    # setting up the app logger with a rotating file handler, in addition to
    #  the built-in flask logger which can be helpful in debug mode.
    create_logger(
        logger_name=app.logger.name,
        log_level=cfy_config.rest_service_log_level,
        log_file=cfy_config.rest_service_log_path,
        log_file_size_MB=cfy_config.rest_service_log_file_size_MB,
        log_files_backup_count=cfy_config.rest_service_log_files_backup_count,
    )

    # log all warnings passed to function
    for w in warnings:
        app.logger.warning(w)

    # secure the app according to manager configuration
    if cfy_config.security_enabled:
        app.logger.info("initializing rest-service security")
        init_secured_app(app)

    app.before_request(log_request)
    app.after_request(log_response)

    # saving flask's original error handlers
    flask_handle_exception = app.handle_exception
    flask_handle_user_exception = app.handle_user_exception

    api = Api(app)

    # saving flask-restful's error handlers
    flask_restful_handle_exception = app.handle_exception
    flask_restful_handle_user_exception = app.handle_user_exception

    # setting it so that <500 codes use flask-restful's error handlers,
    # while 500+ codes use original flask's error handlers (for which we
    # register an error handler on somewhere else in this module)
    def handle_exception(flask_method, flask_restful_method, e):
        code = getattr(e, "code", 500)
        if code >= 500:
            return flask_method(e)
        else:
            return flask_restful_method(e)

    app.handle_exception = functools.partial(handle_exception, flask_handle_exception, flask_restful_handle_exception)
    app.handle_user_exception = functools.partial(
        handle_exception, flask_handle_user_exception, flask_restful_handle_user_exception
    )

    endpoint_mapper.setup_resources(api)
    return app
Beispiel #2
1
def create_app(config):
    """
    This method is a factory for our Flask app which configures all the
    necessary behavior and register all the blueprints.

    All our views should belong to a blueprint and the blueprints mounted on
    the main App.

    To run our application you need only to instantiate a app using this
    function, given a config object, and call its run method.

    example:

        datalog_app = create_app(my_config_obj)
        datalog_app.run()

    """
    app = Flask("datalog")
    app.config.from_object(config)

    db = config.get_db()

    def call_end_request(response):
        """
        flush pending mongodb requests
        and return the connection to the poll
        """
        db.connection.end_request()
        return response

    def add_db_to_request():
        """
        makes possible to access the db directly from any view
        (possible, but **not encouraged**, avoid doing this)
        """
        g.db = db

    def permanet_sessions():
        """
        makes the session persistent for
        PERMANENT_SESSION_LIFETIME
        """
        session.permanent = True

    app.before_request(add_db_to_request)
    app.before_request(permanet_sessions)
    app.after_request(call_end_request)

    # register blueprints
    app.register_blueprint(app_views)

    connect_models(config)

    return app
Beispiel #3
0
def create_app(config_obj):
    app = Flask(__name__)
    app.config.from_object(config_obj)
    app.after_request(req_end)
    db.init_app(app)
    app.register_blueprint(blueprint, url_prefix="/library")
    return app
Beispiel #4
0
def create_application(name=__name__, env="testing"):

    app = Flask(__name__, static_path="/static")

    # Load our default configuration
    load_configuration(app, env)

    # Setup Mail
    mail.init_app(app)

    # Setup OAuth2 Provider
    oauth.init_app(app)

    # Load our application's blueprints
    load_blueprints(app)

    rq.init_app(app)

    """
    Setup Flask Security 
    
    We cannot load the security information until after our blueprints
    have been loaded into our application.
    """
    from CommonsCloudAPI.models.user import user_datastore

    security.init_app(app, user_datastore)

    # Initialize our database and create tables
    db.init_app(app)
    db.app = app
    db.create_all()

    # Load default application routes/paths
    load_errorhandlers(app)

    def add_cors_header(response):
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
        response.headers[
            "Access-Control-Allow-Headers"
        ] = "Authorization, Accept, Content-Type, X-Requested-With, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Cache-Control, Expires, Set-Cookie"
        response.headers["Access-Control-Allow-Credentials"] = True
        return response

    app.after_request(add_cors_header)

    return app
Beispiel #5
0
def create_app(config_filename="config.yaml"):
    app = Flask(__name__)
    app.response_class = TextResponse
    app.url_map.converters["sid"] = SIDConverter
    app.url_map.converters["sha1"] = SHA1Converter
    app.url_map.converters["label"] = LabelConverter

    load_yaml(app, config_filename)
    init_db(app)
    init_cache(app)

    app.after_request(cors)

    app.register_blueprint(paste)

    return app
Beispiel #6
0
    def app(self):
        """ derive flask app based on the combination of command-line
            options and the contents of the .ini files
        """

        ## set flask specific things that are non-optional
        error = (
            lambda k: 'Fatal: You need to specify a "flask" section '
            + 'with an entry like  "'
            + k
            + '=..." in your .ini file'
        )
        try:
            app_name = self["flask.app"]
        except KeyError:
            raise SystemExit(error("app"))
        try:
            secret_key = self["flask.secret_key"]
        except KeyError:
            raise SystemExit(error("secret_key"))
        app = Flask(app_name)
        app.secret_key = secret_key

        ## set flask specific things that are optional
        if "flask.template_path" in self:
            app.jinja_loader = FileSystemLoader(self["template_path"])
        if "flask.before_request" in self:
            before_request = self["flask.before_request"]
            before_request = namedAny(before_request)
            app.before_request(before_request)
        if "flask.after_request" in self:
            after_request = self["flask.after_request"]
            after_request = namedAny(after_request)
            app.after_request(after_request)

        ## setup views
        try:
            view_holder = self["corkscrew.views"]
        except KeyError:
            error = 'Fatal: could not "view=<dotpath>" entry in your .ini file'
            raise SystemExit(error)
        else:
            view_list = namedAny(view_holder)
            [v(app=app, settings=self) for v in view_list]

            return app
def create_app(config_name):
    """
    Flask app factory
    """
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    api = Api()
    db.init_app(app)

    from .resources import MonsterResource, MonsterListResource

    api.add_resource(MonsterListResource, "/monsters", endpoint="monsters")
    api.add_resource(MonsterResource, "/monster/<int:id>", endpoint="monster")
    api.init_app(app)
    app.after_request(add_cors_headers)

    return app
Beispiel #8
0
def create_app(config_file):
    """ Create the webservice application using the configuration provided in
    config_file, and initialize SQLAlchemy, Redis and OAuth services. Also
    installs webservice routes.
    """

    app = Flask(__name__.split(".")[0])
    app.config.from_pyfile(config_file)
    app.after_request(add_cors_header)

    # Initialize Flask extensions
    api = Api(app)
    db.init_app(app)
    cache.init_app(app)
    oauth_provider.init_app(app)

    # Initialize OAuth handler
    import bbws.oauth

    bbws.oauth.init(app)

    # Initialize custom endpoints
    import bbws.custom

    bbws.custom.init(app)

    # Initialize webservice routes
    import bbws.entity
    import bbws.revision
    import bbws.user
    import bbws.entityspecific
    import bbws.relationship
    import bbws.musicbrainz

    bbws.entity.create_views(api)
    bbws.revision.create_views(api)
    bbws.user.create_views(api)
    bbws.entityspecific.create_views(api)
    bbws.relationship.create_views(api)
    bbws.musicbrainz.create_views(api)

    return app
Beispiel #9
0
def create_app():
    app = Flask(__name__)
    app.config.from_object("polipoly2.default_settings")
    app.config.from_envvar("POLIPOLY2_SETTINGS", silent=True)

    register_converters(app)

    init_engine(app.config["DATABASE_URI"])

    def shutdown_session(response):
        session.remove()
        return response

    app.after_request(shutdown_session)

    from polipoly2.views import views

    app.register_module(views)

    return app
Beispiel #10
0
def create_app(config):
    """
    This method is a factory for our Flask app which configures all the
    necessary behavior and register all the blueprints.

    All our views should belong to a blueprint and the blueprints mounted on
    the main App.

    To run our application you need only to instantiate a app using this
    function, given a config object, and call its run method.

    example:

        komoo_app = create_app(my_config_obj)
        komoo_app.run()

    """
    app = Flask("komoo")
    app.config.from_object(config)

    db = config.get_db()

    # flush pending mongodb requests
    def call_end_request(response):
        db.connection.end_request()
        return response

    # makes possible to access the db directly from any view
    # (possible, but **not encouraged**, avoid doing this)
    def add_db_to_request():
        g.db = db

    app.before_request(add_db_to_request)
    app.after_request(call_end_request)

    # register all blueprints
    for bp in blueprints:
        app.register_blueprint(bp[0], url_prefix=bp[1])

    return app
def create_app():
    app = Flask(__name__)
    app.before_request(on_before_request(app))
    app.after_request(on_after_request(app))
    app.add_url_rule("/", view_func=index)
    return app
def create_app():
    from config import configs

    application = Flask(__name__)

    application.config.from_object(configs[os.environ["NOTIFY_ENVIRONMENT"]])

    init_app(application)
    statsd_client.init_app(application)
    logging.init_app(application, statsd_client)
    init_csrf(application)
    request_id.init_app(application)

    service_api_client.init_app(application)
    user_api_client.init_app(application)
    api_key_api_client.init_app(application)
    job_api_client.init_app(application)
    notification_api_client.init_app(application)
    status_api_client.init_app(application)
    invite_api_client.init_app(application)
    template_statistics_client.init_app(application)
    events_api_client.init_app(application)
    provider_client.init_app(application)
    organisations_client.init_app(application)

    login_manager.init_app(application)
    login_manager.login_view = "main.sign_in"
    login_manager.login_message_category = "default"
    login_manager.session_protection = None

    from app.main import main as main_blueprint

    application.register_blueprint(main_blueprint)

    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint)

    proxy_fix.init_app(application)

    application.session_interface = ItsdangerousSessionInterface()

    application.add_template_filter(format_datetime)
    application.add_template_filter(format_datetime_24h)
    application.add_template_filter(format_datetime_normal)
    application.add_template_filter(format_datetime_short)
    application.add_template_filter(format_time)
    application.add_template_filter(syntax_highlight_json)
    application.add_template_filter(valid_phone_number)
    application.add_template_filter(linkable_name)
    application.add_template_filter(format_date)
    application.add_template_filter(format_date_normal)
    application.add_template_filter(format_date_short)
    application.add_template_filter(format_datetime_relative)
    application.add_template_filter(format_delta)
    application.add_template_filter(format_notification_status)
    application.add_template_filter(format_notification_status_as_time)
    application.add_template_filter(format_notification_status_as_field_status)
    application.add_template_filter(format_notification_status_as_url)

    application.after_request(useful_headers_after_request)
    application.after_request(save_service_after_request)
    application.before_request(load_service_before_request)

    @application.context_processor
    def _attach_current_service():
        return {"current_service": current_service}

    register_errorhandlers(application)

    setup_event_handlers()

    return application
Beispiel #13
0
from functools import wraps
from flask import Flask, g, request, render_template, make_response, jsonify, abort

from lib import PING_PERIOD, ARCHIVE_PERIOD, IP_BAN_PERIOD, CHAT_FLAGS, get_time
from lib.api import ping, change_state, disconnect, get_online_state
from lib.groups import MOD_GROUPS, GROUP_RANKS, MINIMUM_RANKS
from lib.messages import send_message, get_userlists, parse_messages
from lib.requests import connect_redis, create_chat_session, set_cookie, disconnect_redis

app = Flask(__name__)

# Pre and post request stuff
app.before_request(connect_redis)
app.before_request(create_chat_session)
app.after_request(set_cookie)
app.after_request(disconnect_redis)

# Decorators


def mark_alive(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        g.joining = ping(g.redis, request.form["chat"], g.user, g.chat_type)
        return f(*args, **kwargs)

    return decorated_function


# Views
Beispiel #14
0
class Phial(object):
    def __init__(self, appname, settings="settings"):
        self.__appname = appname
        self.__settings = __import__("%s.%s" % (appname, settings), fromlist=[settings.split(".")[1:]])
        self.__flask = None
        self.__celery = None

    def __default_debug_404(self, error):
        from flask import request
        from . import __version__ as phial_version

        return (
            render_template(
                "phial/default_debug_404.html",
                phial_version=phial_version,
                error=error,
                method=request.method,
                path=request.path,
                lst_route=self.__flask.url_map.iter_rules(),
            ),
            404,
        )

    def __default_welcome(self):
        from . import __version__ as phial_version

        return render_template("phial/default_welcome.html", phial_version=phial_version)

    def initApp(self, **kwargs):
        # Initialize Flask
        self.__flask = Flask(
            import_name=self.__appname,
            template_folder=self.__settings.FLASK_TEMPLATES_DIR,
            static_folder=self.__settings.FLASK_STATIC_DIR,
            **kwargs
        )
        self.__flask.secret_key = self.__settings.SECRET_KEY

        # Init G
        from . import g

        setattr(g, "__cur_phial", self)
        setattr(g, "__settings", self.__settings)

        # WSGI support
        self.__flask.wsgi_app = ProxyFix(self.__flask.wsgi_app)

        # Fix UTF-8 issue on python 2.x
        if sys.version_info[0] < 3:
            reload(sys)
            sys.setdefaultencoding("utf-8")

        # Add regex on Flask URL map
        self.__flask.url_map.converters["regex"] = FlaskURLMapRegexConverter

        # Init Peewee
        from .peewee_tools import base_model as peewee_bm

        if peewee_bm.BaseModel is not None and getattr(self.__settings, "DATABASE_CONN_STRING", None) is not None:
            if self.__settings.DATABASE_CONN_STRING.startswith("mysql://") is True:
                # Load lib
                try:
                    from peewee import MySQLDatabase
                except ImportError:
                    print("[Phial][ERRO] MySQL driver is not installed (pip install MySQL-python or PyMySQL)")
                    sys.exit(1)
                peewee_bm.gl_database_type = 1
                hdl = MySQLDatabase(None)

                # Override Peewee init to work with connstring
                from .peewee_tools import peewee_overrided_database_init
                from peewee import Database

                funcType = type(Database.init)
                hdl.init = funcType(peewee_overrided_database_init, hdl, Database)

                # Register to Proxy
                peewee_bm.gl_database.initialize(hdl)
            elif self.__settings.DATABASE_CONN_STRING.startswith("sqlite") is True:
                # Load lib
                try:
                    from peewee import SqliteDatabase
                except ImportError:
                    print("[Phial][ERRO] sqlite3 is not installed")
                    sys.exit(1)
                peewee_bm.gl_database_type = 2
                hdl = SqliteDatabase(None)

                # Override Peewee init to work with connstring
                from .peewee_tools import peewee_overrided_database_init
                from peewee import Database

                funcType = type(Database.init)
                hdl.init = funcType(peewee_overrided_database_init, hdl, Database)

                # Register to Proxy
                peewee_bm.gl_database.initialize(hdl)
            else:
                print("[Phial][ERRO] Database backend not supported")
                sys.exit(1)

            # Init Database
            peewee_bm.gl_database.init(self.__settings.DATABASE_CONN_STRING)

        # Session handler
        if (
            getattr(self.__settings, "FLASK_SESSION_HANDLER", None)
            and getattr(self.__settings, "FLASK_SESSION_HANDLER_CFG", None)
        ) is not None:
            try:
                mod_path = self.__settings.FLASK_SESSION_HANDLER.rsplit(".", 1)[0]
                class_name = self.__settings.FLASK_SESSION_HANDLER.split(".")[-1]
                hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
                sess_handler = getattr(hdl, class_name)
                try:
                    self.__flask.session_interface = sess_handler(**self.__settings.FLASK_SESSION_HANDLER_CFG)
                except:
                    print("[Phial][ERRO] Session handler is misconfigured")
                    sys.exit(1)
            except (ImportError, AttributeError) as e:
                print('[Phial][ERRO] Can\'t load session backend "%s": %s' % (self.__settings.FLASK_SESSION_HANDLER, e))
                sys.exit(1)

        # Load user-defined routes
        try:
            url_map = __import__("%s.routes" % self.__appname, fromlist=["routes"])
            for u in getattr(url_map, "routes", []):
                try:
                    try:
                        self.__flask.add_url_rule(u[0], view_func=u[1], methods=u[2], defaults=u[3])
                    except IndexError:
                        self.__flask.add_url_rule(u[0], view_func=u[1], methods=u[2])
                except AttributeError:
                    print("[Phial][WARN] Ignoring bad route entry: %s" % str(u))
            for u in getattr(url_map, "errors", []):
                self.__flask.error_handler_spec[None][u[0]] = u[1]
        except ImportError:
            try:
                from cStringIO import StringIO
            except ImportError:
                from StringIO import StringIO
            import traceback

            stream_output = StringIO()
            traceback.print_exc(file=stream_output)
            print('[Phial][ERRO] File "%s.routes" does not exist or contain some errors...' % (self.__appname))
            print(stream_output.getvalue())
            sys.exit(1)

        # Set default welcome page if user-defined routes map is empty
        if len(self.__flask.url_map._rules) < 2:
            from os.path import dirname, join

            self.__flask.template_folder = join(dirname(__file__), "assets/templates")
            self.__flask.static_folder = join(dirname(__file__), "assets/static")
            self.__flask.add_url_rule("/", view_func=self.__default_welcome, methods=["GET"])

        # If application DEBUG==True -> redefine 404 error page
        if self.__settings.FLASK_DEBUG is True:
            self.__flask.error_handler_spec[None][404] = self.__default_debug_404

        # Jinja2 DEBUG
        self.__flask.jinja_env.globals.update({"DEBUG": self.__settings.FLASK_DEBUG})

        # Jinja2 built-in extensions
        self.__flask.jinja_env.add_extension("jinja2.ext.do")
        self.__flask.jinja_env.add_extension("jinja2.ext.with_")
        self.__flask.jinja_env.add_extension("jinja2.ext.i18n")
        self.__flask.jinja_env.add_extension("phial.jinja_tools.ext.SelectiveHTMLCompress")
        self.__flask.jinja_env.add_extension("phial.jinja_tools.ext.DatetimeExtension")

        # Jinja2 i18n callables
        self.__flask.jinja_env.install_gettext_callables(
            lambda x: jinja_get_translation_engine().ugettext(x),
            lambda s, p, n: jinja_get_translation_engine().ungettext(s, p, n),
            newstyle=True,
        )

        # Jinja2 user-defined extensions
        mod_path = getattr(self.__settings, "JINJA_CUSTOM_EXTENSION_DIR", "%s.phial.jinja.extension" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                try:
                    self.__flask.jinja_env.add_extension("%s.%s" % (mod_path, im))
                except AttributeError:
                    print('[Phial][WARN] Extension "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Jinja2 user-defined filters
        mod_path = getattr(self.__settings, "JINJA_CUSTOM_FILTER_DIR", "%s.phial.jinja.filter" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    self.__flask.jinja_env.filters.update({im: item_hdl})
                else:
                    print('[Phial][WARN] Filter "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Jinja2 user-defined functions
        mod_path = getattr(self.__settings, "JINJA_CUSTOM_FUNCTION_DIR", "%s.phial.jinja.function" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    self.__flask.jinja_env.globals.update({im: item_hdl})
                else:
                    print('[Phial][WARN] Function "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Register before & after callback
        from .flask_tools.callback import flask_before_url_remove_trailing_slash, flask_before_i18n_set_user_language
        from .flask_tools.callback import flask_before_peewee_connect, flask_after_peewee_close

        self.__flask.before_request(flask_before_url_remove_trailing_slash)
        self.__flask.before_request(flask_before_peewee_connect)
        self.__flask.before_request(flask_before_i18n_set_user_language)
        self.__flask.after_request(flask_after_peewee_close)
        for im in getattr(self.__settings, "FLASK_REQUEST_CALLBACK", []):
            try:
                mod_path = im[1].rsplit(".", 1)[0]
                class_name = im[1].split(".")[-1]
                hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
                call_hdl = getattr(hdl, class_name)
                if im[0] == "before":
                    self.__flask.before_request(call_hdl)
                elif im[0] == "after":
                    self.__flask.after_request(call_hdl)
            except (ImportError, AttributeError) as e:
                print('[Phial][WARN] Can\'t load flask callback "%s": %s' % (im[1], e))
            except IndexError:
                print("[Phial][ERRO] FLASK_REQUEST_CALLBACK is misconfigured: %s" % e)
                sys.exit(1)

        # Register Celery (if lib is installed) and settings OK
        if getattr(self.__settings, "CELERY_BROKER_URL", None) is not None:
            try:
                from celery import Celery
            except ImportError:
                print("[Phial][ERRO] Celery is not installed (pip install -U celery)")
                sys.exit(1)
            else:
                self.__flask.config.update(
                    CELERY_BROKER_URL=self.__settings.CELERY_BROKER_URL,
                    CELERY_RESULT_BACKEND=getattr(self.__settings, "CELERY_RESULT_BACKEND"),
                    CELERY_ACCEPT_CONTENT=getattr(self.__settings, "CELERY_ACCEPT_CONTENT"),
                )
                self.__celery = Celery(
                    main=self.__flask.import_name,
                    broker=self.__flask.config["CELERY_BROKER_URL"],
                    backend=self.__flask.config["CELERY_RESULT_BACKEND"],
                )
                self.__celery.config_from_object(self.__flask.config)

                # Override Task to set the Flask app context
                TaskBase = self.__celery.Task

                class ContextTask(TaskBase):
                    abstract = True

                    def __call__(self, *args, **kwargs):
                        from . import current_phial

                        with current_phial.flaskapp.app_context():
                            return TaskBase.__call__(self, *args, **kwargs)

                setattr(self.__celery, "Task", ContextTask)

                # Register to globals
                setattr(g, "__celery", self.__celery)

                # Register tasks
                mod_path = getattr(self.__settings, "CELERY_CUSTOM_TASKS_DIR", "%s.celery" % self.__appname)
                try:
                    hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
                    for im in getattr(hdl, "__all__", []):
                        item_hdl = getattr(hdl, im, None)
                        if item_hdl is not None:
                            self.__celery.tasks.register(item_hdl)
                        else:
                            print('[Phial][WARN] Async task "%s.%s" does not exist' % (mod_path, im))
                except ImportError as e:
                    print("[Phial][ERRO] Can't load celery async tasks: %s" % e)
                    sys.exit(1)

        # Register error handlers (RELEASE MODE ONLY)
        if (
            self.__settings.FLASK_DEBUG is False
            and len(self.__settings.ADMINS) > 0
            and len(self.__settings.MAIL_USERNAME) > 0
        ):
            hMailHandler = SMTPHandler(
                (self.__settings.MAIL_SMTP, self.__settings.MAIL_SMTP_PORT),
                self.__settings.MAIL_USERNAME,
                [a[1] for a in self.__settings.ADMINS],
                self.__settings.LOGGING_MAIL_TITLE,
                (self.__settings.MAIL_USERNAME, self.__settings.MAIL_PASSWORD),
            )
            if getattr(self.__settings, "LOGGING_MAIL_TEMPLATE", None) is not None:
                hMailHandler.setFormatter(Formatter(self.__settings.LOGGING_MAIL_TEMPLATE))
            hMailHandler.setLevel(ERROR)
            self.__flask.logger.addHandler(hMailHandler)
        hFileHandler = RotatingFileHandler(
            self.__settings.LOGGING_FILE_FILENAME,
            "a",
            self.__settings.LOGGING_FILE_MAXSIZE,
            self.__settings.LOGGING_FILE_NBROTATE,
        )
        if getattr(self.__settings, "LOGGING_FILE_TEMPLATE", None) is not None:
            hFileHandler.setFormatter(Formatter(self.__settings.LOGGING_FILE_TEMPLATE))
        hFileHandler.setLevel(ERROR)
        self.__flask.logger.addHandler(hFileHandler)

    @property
    def appname(self):
        return self.__appname

    @property
    def flaskapp(self):
        return self.__flask

    @property
    def celery(self):
        return self.__celery

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

    def startApp(self):
        # Create arguments parser
        parser = argparse.ArgumentParser(prog="phial")

        # Add built-in modules and retrieve user-defined modules
        lst_management = [("help", parser.print_help, False)]
        mod_path = "phial.phial_management"
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    lst_management.append((item_hdl.initParser(parser), item_hdl, True))
                else:
                    print('[Phial][WARN] Management class "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass
        mod_path = getattr(self.__settings, "PHIAL_CUSTOM_MANAGEMENT_DIR", "%s.phial.management" % self.__appname)
        try:
            hdl = __import__(mod_path, fromlist=[mod_path.split(".")[-1]])
            for im in getattr(hdl, "__all__", []):
                item_hdl = getattr(hdl, im, None)
                if item_hdl is not None:
                    lst_management.append((item_hdl.initParser(parser), item_hdl, True))
                else:
                    print('[Phial][WARN] Management class "%s.%s" does not exist' % (mod_path, im))
        except ImportError:
            pass

        # Check arguements and run command
        from .flask_tools.callback import flask_before_i18n_set_user_language

        res = vars(parser.parse_args())
        for m in lst_management:
            if res.get(m[0], None) is not None:
                if m[0] != "server":
                    with self.__flask.test_request_context():
                        flask_before_i18n_set_user_language("en")
                        if m[1]() if m[2] is False else m[1]().run(self, res) is True:
                            break
                else:
                    if m[1]() if m[2] is False else m[1]().run(self, res) is True:
                        break

    def runServer(self):
        self.__flask.run(
            host=self.__settings.FLASK_LISTEN_ADDRESS,
            port=self.__settings.FLASK_LISTEN_PORT,
            debug=self.__settings.FLASK_DEBUG,
            use_reloader=self.__settings.FLASK_USE_RELOADER,
            threaded=getattr(self.__settings, "FLASK_THREADED_DEBUG_SERVER", False),
        )
Beispiel #15
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
Beispiel #16
0
def create_app(config="config.ProductionDevelopmentConfig", apptype="profi"):
    app = Flask(__name__, static_folder="./static")

    app.config.from_object(config)

    app.teardown_request(close_database)

    app.debug = app.config["DEBUG"] if "DEBUG" in app.config else False
    app.testing = app.config["TESTING"] if "TESTING" in app.config else False

    app.before_request(load_database(app.config["SQLALCHEMY_DATABASE_URI"]))
    app.before_request(lambda: load_user(apptype))
    app.before_request(setup_authomatic(app))

    def add_map_headers_to_less_files(response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        if request.path and re.search(r"\.css$", request.path):
            mapfile = re.sub(r"\.css$", r".css.map", request.path)
            if os.path.isfile(os.path.realpath(os.path.dirname(__file__)) + mapfile):
                response.headers.add("X-Sourcemap", mapfile)
        return response

    app.after_request(add_map_headers_to_less_files)

    if apptype == "front":

        # relative paths
        def join_path(template, parent):
            return os.path.join(os.path.dirname(parent), template)

        app.jinja_env.join_path = join_path

        def load_portal():
            from profapp.models.portal import Portal

            portal = g.db.query(Portal).filter_by(host=request.host).first()
            g.portal = portal if portal else None
            g.portal_id = portal.id if portal else None
            g.portal_layout_path = portal.layout.path if portal else ""
            g.lang = g.portal.lang if g.portal else g.user_dict["lang"] if portal else "en"

        app.before_request(load_portal)
        from profapp.controllers.blueprints_register import register_front as register_blueprints_front

        register_blueprints_front(app)

    elif apptype == "static":
        from profapp.controllers.blueprints_register import register_static as register_blueprints_static

        register_blueprints_static(app)
    elif apptype == "file":
        from profapp.controllers.blueprints_register import register_file as register_blueprints_file

        register_blueprints_file(app)
    else:
        from profapp.controllers.blueprints_register import register_profi as register_blueprints_profi

        register_blueprints_profi(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    # moment.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = "basic"

    @login_manager.user_loader
    def load_user_manager(user_id):
        return g.db.query(User).get(user_id)

    update_jinja_engine(app)

    session_opts = {"session.type": "ext:memcached", "session.url": "memcached.profi:11211"}

    class BeakerSessionInterface(SessionInterface):
        def open_session(self, app, request):
            _session = request.environ["beaker.session"]
            return _session

        def save_session(self, app, session, response):
            session.save()

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    return app
Beispiel #17
0
class TarbellSite:
    def __init__(self, path, client_secrets_path=None, quiet=False):
        self.app = Flask(__name__)

        self.quiet = quiet

        self.app.jinja_env.finalize = silent_none  # Don't print "None"
        self.app.debug = True  # Always debug

        self.path = path
        self.project, self.base = self.load_project(path)

        self.data = {}
        self.hooks = self.process_hooks(hooks)
        self.expires = 0

        # add routes
        self.app.add_url_rule("/", view_func=self.preview)
        self.app.add_url_rule("/<path:path>", view_func=self.preview)
        self.app.add_url_rule("/data.json", view_func=self.data_json)

        self.app.register_blueprint(filters)

        self.app.before_request(self.add_site_to_context)
        self.app.after_request(self.never_cache_preview)

        # centralized freezer setup
        self.app.config.setdefault("FREEZER_RELATIVE_URLS", True)
        self.app.config.setdefault("FREEZER_REMOVE_EXTRA_FILES", False)
        self.app.config.setdefault("FREEZER_DESTINATION", os.path.join(os.path.realpath(self.path), "_site"))

        self.freezer = Freezer(self.app)
        self.freezer.register_generator(self.find_files)

    def add_site_to_context(self):
        """
        Add current Tarbell object to Flask's `g`
        """
        g.current_site = self

    def never_cache_preview(self, response):
        """
        Ensure preview is never cached
        """
        response.cache_control.max_age = 0
        response.cache_control.no_cache = True
        response.cache_control.must_revalidate = True
        response.cache_control.no_store = True
        return response

    def process_hooks(self, hooks):
        """
        Process all project hooks
        """
        try:
            enabled_hooks = self.project.HOOKS
        except AttributeError:
            return hooks

    def call_hook(self, hook, *args, **kwargs):
        """
        Calls each registered hook
        """
        for function in self.hooks[hook]:
            function.__call__(*args, **kwargs)

    def _get_base(self, path):
        """
        Get project blueprint
        """
        base = None

        # Slightly ugly DRY violation for backwards compatibility with old
        # "_base" convention
        if os.path.isdir(os.path.join(path, "_blueprint")):
            base_dir = os.path.join(path, "_blueprint/")
            # Get the blueprint template and register it as a blueprint
            if os.path.exists(os.path.join(base_dir, "blueprint.py")):
                filename, pathname, description = imp.find_module("blueprint", [base_dir])
                base = imp.load_module("blueprint", filename, pathname, description)
                self.blueprint_name = "_blueprint"
            else:
                puts("No _blueprint/blueprint.py file found")
        elif os.path.isdir(os.path.join(path, "_base")):
            puts("Using old '_base' convention")
            base_dir = os.path.join(path, "_base/")
            if os.path.exists(os.path.join(base_dir, "base.py")):
                filename, pathname, description = imp.find_module("base", [base_dir])
                base = imp.load_module("base", filename, pathname, description)
                self.blueprint_name = "_base"
            else:
                puts("No _base/base.py file found")

        if base:
            base.base_dir = base_dir
            self.app.register_blueprint(base.blueprint, site=self)

        return base

    def load_project(self, path):
        """
        Load a Tarbell project
        """
        base = self._get_base(path)

        filename, pathname, description = imp.find_module("tarbell_config", [path])
        project = imp.load_module("project", filename, pathname, description)

        try:
            self.key = project.SPREADSHEET_KEY
            self.client = get_drive_api()
        except AttributeError:
            self.key = None
            self.client = None

        try:
            project.CREATE_JSON
        except AttributeError:
            project.CREATE_JSON = False

        try:
            project.S3_BUCKETS
        except AttributeError:
            project.S3_BUCKETS = {}

        try:
            project.EXCLUDES
        except AttributeError:
            project.EXCLUDES = []

        if base:
            try:
                base.EXCLUDES
            except AttributeError:
                base.EXCLUDES = []

            # Merge excludes
            project.EXCLUDES = EXCLUDES + base.EXCLUDES + list(set(project.EXCLUDES) - set(base.EXCLUDES))

        # merge project template types with defaults
        project.TEMPLATE_TYPES = set(getattr(project, "TEMPLATE_TYPES", [])) | set(TEMPLATE_TYPES)

        try:
            project.DEFAULT_CONTEXT
        except AttributeError:
            project.DEFAULT_CONTEXT = {}

        project.DEFAULT_CONTEXT.update(
            {
                "PROJECT_PATH": self.path,
                "ROOT_URL": "127.0.0.1:5000",
                "SPREADSHEET_KEY": self.key,
                "BUCKETS": project.S3_BUCKETS,
                "SITE": self,
            }
        )

        # Set up template loaders
        template_dirs = [path]
        if base:
            template_dirs.append(base.base_dir)
        error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "error_templates")
        template_dirs.append(error_path)

        self.app.jinja_loader = TarbellFileSystemLoader(template_dirs)

        # load the project blueprint, if it exists
        if hasattr(project, "blueprint") and isinstance(project.blueprint, Blueprint):
            self.app.register_blueprint(project.blueprint, site=self)

        return project, base

    def _resolve_path(self, path):
        """
        Resolve static file paths
        """
        filepath = None
        mimetype = None

        for root, dirs, files in self.filter_files(self.path):
            # Does it exist in error path?
            error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "error_templates", path)
            try:
                with open(error_path):
                    mimetype, encoding = mimetypes.guess_type(error_path)
                    filepath = error_path
            except IOError:
                pass

            # Does it exist in Tarbell blueprint?
            if self.base:
                basepath = os.path.join(root, self.blueprint_name, path)
                try:
                    with open(basepath):
                        mimetype, encoding = mimetypes.guess_type(basepath)
                        filepath = basepath
                except IOError:
                    pass

            # Does it exist under regular path?
            fullpath = os.path.join(root, path)
            try:
                with open(fullpath):
                    mimetype, encoding = mimetypes.guess_type(fullpath)
                    filepath = fullpath
            except IOError:
                pass

        return filepath, mimetype

    def data_json(self, extra_context=None, publish=False):
        """
        Serve site context as JSON. Useful for debugging.
        """
        if not self.project.CREATE_JSON:
            # nothing to see here, but the right mimetype
            return jsonify()

        if not self.data:
            # this sets site.data by spreadsheet or gdoc
            self.get_context(publish)

        return jsonify(self.data)

    def preview(self, path=None, extra_context=None, publish=False):
        """
        Serve up a project path
        """
        try:
            self.call_hook("preview", self)

            if path is None:
                path = "index.html"

            # Detect files
            filepath, mimetype = self._resolve_path(path)

            # Serve dynamic
            if filepath and mimetype and mimetype in self.project.TEMPLATE_TYPES:
                context = self.get_context(publish)
                context.update({"PATH": path, "PREVIEW_SERVER": not publish, "TIMESTAMP": int(time.time())})
                if extra_context:
                    context.update(extra_context)

                rendered = render_template(path, **context)
                return Response(rendered, mimetype=mimetype)

            # Serve static
            if filepath:
                dir, filename = os.path.split(filepath)
                return send_from_directory(dir, filename)

        except Exception as e:
            ex_type, ex, tb = sys.exc_info()
            try:
                # Find template with name of error
                cls = e.__class__
                ex_type, ex, tb = sys.exc_info()

                context = self.project.DEFAULT_CONTEXT
                context.update({"PATH": path, "traceback": traceback.format_exception(ex_type, ex, tb), "e": e})
                if extra_context:
                    context.update(extra_context)

                try:
                    error_path = "_{0}.{1}.html".format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)
                except TemplateNotFound:
                    # Find template without underscore prefix, @TODO remove in v1.1
                    error_path = "{0}.{1}.html".format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)

                return Response(rendered, mimetype="text/html")
            except TemplateNotFound:
                # Otherwise raise old error
                raise ex_type, ex, tb

        # Last ditch effort -- see if path has "index.html" underneath it
        if not path.endswith("index.html"):
            if not path.endswith("/"):
                path = "{0}/".format(path)
            path = "{0}{1}".format(path, "index.html")
            return self.preview(path)

        # It's a 404
        if path.endswith("/index.html"):
            path = path[:-11]
        rendered = render_template("404.html", PATH=path)
        return Response(rendered, status=404)

    def get_context(self, publish=False):
        """
        Use optional CONTEXT_SOURCE_FILE setting to determine data source.
        Return the parsed data.

        Can be an http|https url or local file. Supports csv and excel files.
        """
        context = self.project.DEFAULT_CONTEXT
        try:
            file = self.project.CONTEXT_SOURCE_FILE
            # CSV
            if re.search(r"(csv|CSV)$", file):
                context.update(self.get_context_from_csv())
            # Excel
            if re.search(r"(xlsx|XLSX|xls|XLS)$", file):
                context.update(self.get_context_from_xlsx())
        except AttributeError:
            context.update(self.get_context_from_gdoc())

        return context

    def get_context_from_xlsx(self):
        """
        Get context from an Excel file
        """
        if re.search("^(http|https)://", self.project.CONTEXT_SOURCE_FILE):
            resp = requests.get(self.project.CONTEXT_SOURCE_FILE)
            content = resp.content
        else:
            try:
                with open(self.project.CONTEXT_SOURCE_FILE) as xlsxfile:
                    content = xlsxfile.read()
            except IOError:
                filepath = "%s/%s" % (os.path.abspath(self.path), self.project.CONTEXT_SOURCE_FILE)
                with open(filepath) as xlsxfile:
                    content = xlsxfile.read()

        data = process_xlsx(content)
        if "values" in data:
            data = copy_global_values(data)

        return data

    def get_context_from_csv(self):
        """
        Open CONTEXT_SOURCE_FILE, parse and return a context
        """
        if re.search("^(http|https)://", self.project.CONTEXT_SOURCE_FILE):
            data = requests.get(self.project.CONTEXT_SOURCE_FILE)
            reader = csv.reader(data.iter_lines(), delimiter=",", quotechar='"')
            ret = {rows[0]: rows[1] for rows in reader}
        else:
            try:
                with open(self.project.CONTEXT_SOURCE_FILE) as csvfile:
                    reader = csv.reader(csvfile, delimiter=",", quotechar='"')
                    ret = {rows[0]: rows[1] for rows in reader}
            except IOError:
                file = "%s/%s" % (os.path.abspath(self.path), self.project.CONTEXT_SOURCE_FILE)
                with open(file) as csvfile:
                    reader = csv.reader(csvfile, delimiter=",", quotechar='"')
                    ret = {rows[0]: rows[1] for rows in reader}
        ret.update({"CONTEXT_SOURCE_FILE": self.project.CONTEXT_SOURCE_FILE})
        return ret

    def get_context_from_gdoc(self):
        """
        Wrap getting context from Google sheets in a simple caching mechanism.
        """
        try:
            start = int(time.time())
            if not self.data or start > self.expires:
                self.data = self._get_context_from_gdoc(self.project.SPREADSHEET_KEY)
                end = int(time.time())
                ttl = getattr(self.project, "SPREADSHEET_CACHE_TTL", SPREADSHEET_CACHE_TTL)
                self.expires = end + ttl
            return self.data
        except AttributeError:
            return {}

    def _get_context_from_gdoc(self, key):
        """
        Create a Jinja2 context from a Google spreadsheet.
        """
        try:
            content = self.export_xlsx(key)
            data = process_xlsx(content)
            if "values" in data:
                data = copy_global_values(data)
            return data
        except BadStatusLine:
            # Stale connection, reset API and data
            puts("Connection reset, reloading drive API")
            self.client = get_drive_api()
            return self._get_context_from_gdoc(key)

    def export_xlsx(self, key):
        """
        Download xlsx version of spreadsheet.
        """
        spreadsheet_file = self.client.files().get(fileId=key).execute()
        links = spreadsheet_file.get("exportLinks")
        downloadurl = links.get("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        resp, content = self.client._http.request(downloadurl)
        return content

    def generate_static_site(self, output_root=None, extra_context=None):
        """
        Bake out static site
        """
        self.app.config["BUILD_PATH"] = output_root

        # use this hook for registering URLs to freeze
        self.call_hook("generate", self, output_root, extra_context)

        if output_root is not None:
            # realpath or this gets generated relative to the tarbell package
            self.app.config["FREEZER_DESTINATION"] = os.path.realpath(output_root)

        self.freezer.freeze()

    def filter_files(self, path):
        """
        Exclude files based on blueprint and project configuration as well as hidden files.
        """
        excludes = r"|".join([fnmatch.translate(x) for x in self.project.EXCLUDES]) or r"$."
        for root, dirs, files in os.walk(path, topdown=True):
            dirs[:] = [d for d in dirs if not re.match(excludes, d)]
            dirs[:] = [os.path.join(root, d) for d in dirs]
            rel_path = os.path.relpath(root, path)

            paths = []
            for f in files:
                if rel_path == ".":
                    file_path = f
                else:
                    file_path = os.path.join(rel_path, f)
                if not re.match(excludes, file_path):
                    paths.append(f)

            files[:] = paths
            yield root, dirs, files

    def find_files(self):
        """
        Find all file paths for publishing, yield (urlname, kwargs)
        """
        # yield blueprint paths first
        if getattr(self, "blueprint_name", None):
            for path in walk_directory(os.path.join(self.path, self.blueprint_name), ignore=self.project.EXCLUDES):
                yield "preview", {"path": path}

        # then yield project paths
        for path in walk_directory(self.path, ignore=self.project.EXCLUDES):
            yield "preview", {"path": path}
Beispiel #18
0
from flask.ext.babel import Babel, gettext

app = Flask(__name__)
app.url_map.strict_slashes = False
app.config["SERVER_NAME"] = os.environ["BASE_DOMAIN"]

app.config["PROPAGATE_EXCEPTIONS"] = True

babel = Babel(app)
app.jinja_env.globals.update(gettext=gettext)

app.before_request(redis_connect)

app.before_request(check_csrf_token)

app.after_request(set_cookie)
app.after_request(db_commit)

app.teardown_request(db_disconnect)
app.teardown_request(redis_disconnect)


def make_rules(subdomain, path, func, formats=False, paging=False):
    # Keep subdomain here for consistency with charat2's route names.
    name = (subdomain + "_" + func.__name__) if subdomain else func.__name__
    app.add_url_rule(path, name, func, methods=("GET",))
    if formats:
        app.add_url_rule(path + ".<fmt>", name, func, methods=("GET",))
    if paging:
        app.add_url_rule(path + "/<int:page>", name, func, methods=("GET",))
    if formats and paging:
        app.add_url_rule(path + "/<int:page>.<fmt>", name, func, methods=("GET",))
Beispiel #19
0
def create_app(config="config.ProductionDevelopmentConfig", apptype="profi"):
    app = Flask(__name__, static_folder="./static")

    app.config.from_object(config)
    # babel = Babel(app)

    app.teardown_request(close_database)
    app.config["DEBUG"] = True

    app.before_request(load_database(app.config["SQLALCHEMY_DATABASE_URI"]))
    app.before_request(lambda: load_user(apptype))
    app.before_request(setup_authomatic(app))

    def add_map_headers_to_less_files(response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        if request.path and re.search(r"\.css$", request.path):
            mapfile = re.sub(r"\.css$", r".css.map", request.path)
            if os.path.isfile(os.path.realpath(os.path.dirname(__file__)) + mapfile):
                response.headers.add("X-Sourcemap", mapfile)
        return response

    app.after_request(add_map_headers_to_less_files)

    if apptype == "front":

        # relative paths
        def join_path(template, parent):
            return os.path.join(os.path.dirname(parent), template)

        app.jinja_env.join_path = join_path

        def load_portal():
            # class RelEnvironment(jinja2.Environment):
            #     """Override join_path() to enable relative template paths."""
            #     def join_path(self, template, parent):
            #         return os.path.join(os.path.dirname(parent), template)

            from profapp.models.portal import Portal

            portal = g.db.query(Portal).filter_by(host=request.host).one()
            g.portal = portal
            g.portal_id = portal.id
            g.portal_layout_path = portal.layout.path
            g.lang = g.portal.lang if g.portal else g.user_dict["lang"]

        app.before_request(load_portal)
        from profapp.controllers.blueprints_register import register_front as register_blueprints_front

        register_blueprints_front(app)

    elif apptype == "static":
        from profapp.controllers.blueprints_register import register_static as register_blueprints_static

        register_blueprints_static(app)
    elif apptype == "file":
        from profapp.controllers.blueprints_register import register_file as register_blueprints_file

        register_blueprints_file(app)
    else:
        from profapp.controllers.blueprints_register import register_profi as register_blueprints_profi

        register_blueprints_profi(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = "basic"

    @login_manager.user_loader
    def load_user_manager(user_id):
        return g.db.query(User).get(user_id)

    csrf.init_app(app)

    # read this: http://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
    # app.jinja_env.globals.update(flask_endpoint_to_angular=flask_endpoint_to_angular)

    app.jinja_env.globals.update(raw_url_for=raw_url_for)
    app.jinja_env.globals.update(pre=pre)
    app.jinja_env.globals.update(translates=translates)
    app.jinja_env.globals.update(fileUrl=fileUrl)
    app.jinja_env.globals.update(prImage=prImage)
    app.jinja_env.globals.update(url_page=url_page)
    app.jinja_env.globals.update(config_variables=config_variables)
    app.jinja_env.globals.update(_=translate_phrase)
    app.jinja_env.globals.update(__=translate_html)
    app.jinja_env.globals.update(tinymce_format_groups=HtmlHelper.tinymce_format_groups)
    app.jinja_env.globals.update(pr_help_tooltip=pr_help_tooltip)

    app.jinja_env.filters["nl2br"] = nl2br

    # see: http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/
    # Flask will automatically remove database sessions at the end of the
    # request or when the application shuts down:
    # from db_init import db_session

    # @app.teardown_appcontext
    # def shutdown_session(exception=None):
    #     try:
    #         db_session.commit()
    #     except Exception:
    #         session.rollback()
    #         raise
    #     finally:
    #         session.close()  # optional, depends on use case
    #     # db_session.remove()

    session_opts = {"session.type": "ext:memcached", "session.url": "memcached.profi:11211"}

    class BeakerSessionInterface(SessionInterface):
        def open_session(self, app, request):
            _session = request.environ["beaker.session"]
            return _session

        def save_session(self, app, session, response):
            session.save()

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    return app
Beispiel #20
0
    response.headers.add("content-length", str(pdf_output.getbuffer().nbytes))
    return response


def render_rst(content):
    input_file = StringIO(content)
    parser = ReStructuredTextParser()
    document_tree = parser.parse(input_file)
    document = Article(document_tree, OPTIONS, backend=pdf)
    pdf_output = BytesIO()
    document.render(file=pdf_output)
    pdf_output.seek(0)
    return pdf_output


ALLOW_ORIGIN = "*" if DEV_MODE else "http://www.opqode.com"


def article_allow_origin(response):
    if request.path == "/wake":
        response.headers.add("Access-Control-Allow-Origin", ALLOW_ORIGIN)
    return response


app.after_request(article_allow_origin)


if __name__ == "__main__":
    app.run(debug=True)
else:
    os.chdir(os.path.dirname(__file__))
Beispiel #21
0
def setup_logging():
    log_handler.set_up_logging(app, "read", getenv("GOVUK_ENV", "development"))


app = Flask(__name__)

# Configuration
app.config.from_object("backdrop.read.config.%s" % getenv("GOVUK_ENV", "development"))

db = database.Database(app.config["MONGO_HOST"], app.config["MONGO_PORT"], app.config["DATABASE_NAME"])

setup_logging()

app.before_request(create_request_logger(app))
app.after_request(create_response_logger(app))


class JsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return json.JSONEncoder.default(self, obj)


def raw_queries_allowed(bucket_name):
    raw_queries_config = app.config.get("RAW_QUERIES_ALLOWED", {})
    return bool(raw_queries_config.get(bucket_name, False))
Beispiel #22
0
# Caching total number of graphs
NB_GRAPHS = sum(len(n.data["graphs"]) for _, n in DATA.iter_all_nodes())


# PREPARING APP
#
format_ = "[%(asctime)s] [%(levelname)s] %(message)s"
handler = logging.FileHandler(CONF["logfile"])
handler.setFormatter(logging.Formatter(format_))
handler.setLevel(logging.INFO)

app = Flask(__name__)
app.secret_key = "jlrgh(*&)(&$)(#*$&"
app.logger.addHandler(handler)
app.after_request(after_request_log)
app.jinja_env.add_extension("jinja2.ext.do")


# CUSTOM Markdown Jinja filter
#
app.template_filter("md")(md_convert)
app.template_filter("mdi")(md_iconvert)  # inline version, no surrounding <p>


# CUSTOM Sort filters
#
app.template_filter("sortsons")(sort_sons)
app.template_filter("sortlabels")(sort_labels)
app.template_filter("sortindexes")(sort_indexes)
Beispiel #23
0
app.wsgi_app = ProxyFix(app.wsgi_app)

# -------------------
# Settings
# -------------------


def add_cors_header(response):
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
    response.headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, PATCH, DELETE, OPTIONS"
    return response


app.after_request(add_cors_header)


# -------------------
# Types
# -------------------


class JsonType(Mutable, types.TypeDecorator):
    """ JSON wrapper type for TEXT database storage.

        References:
        http://stackoverflow.com/questions/4038314/sqlalchemy-json-as-blob-text
        http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/mutable.html
    """
Beispiel #24
0
from flask.ext.sqlalchemy import SQLAlchemy

# Local modules
from lib import importConfig, authDecorator, CORS

# Data model
from db import models as m
from db import data_access

app = Flask(__name__)

# Configure application and interfaces
importConfig(app)
db = SQLAlchemy(app)
Resource.method_decorators.append(authDecorator(app))
app.after_request(CORS.allowALLTheThings)

# setup custom error messages
errors = {
    "NotAcceptable": {
        "message": "Your client indicated that it does not accept any of the representations we support.",
        "status": 406,
    }
}

# configure flask restful
api = Api(app, default_mediatype=None, catch_all_404s=True, errors=errors)
api.representations = {}
home_api = Api(app, default_mediatype=None, catch_all_404s=True, errors=errors)
home_api.representations = {}