def test_missing_file(self):
        """
        When given a non-existent file path,
        prepare_redirects should not error
        """

        prepare_redirects(path="/tmp/non-existent-file.yaml")
Ejemplo n.º 2
0
    def __init__(self,
                 name,
                 service,
                 prepare_deleted=prepare_deleted(),
                 prepare_redirects=prepare_redirects(),
                 *args,
                 **kwargs):
        super().__init__(name, *args, **kwargs)

        self.service = service

        self.config.from_object(
            "canonicalwebteam.flask_base.config.BaseConfig")

        self.url_map.strict_slashes = False
        self.url_map.converters["regex"] = RegexConverter

        self.wsgi_app = (ProxyFix(self.wsgi_app) if not self.debug else
                         DebuggedApplication(self.wsgi_app))

        self.before_request(prepare_redirects)
        self.before_request(prepare_deleted)

        self.context_processor(base_context)

        talisker.flask.register(self)
        talisker.logs.set_global_extra({"service": self.service})
Ejemplo n.º 3
0
def create_app(testing=False):
    app = FlaskBase(
        __name__,
        "jaas.ai",
        template_folder="../templates",
        static_folder="../static",
    )

    app.testing = testing
    app.after_request(add_headers)
    app.before_request(prepare_redirects())
    app.before_request(prepare_deleted())

    blog_views = BlogViews(
        api=BlogAPI(
            session=session,
            thumbnail_width=354,
            thumbnail_height=180,
        ),
        blog_title="JAAS Case Studies",
        tag_ids=[3513],
        feed_description="Case Studies from happy JAAS users",
    )
    app.register_blueprint(build_blueprint(blog_views),
                           url_prefix="/case-studies")

    talisker.requests.configure(cs.session)

    init_handler(app)
    init_blueprint(app)
    init_dashboard(app)

    @app.template_filter("pluralize")
    def pluralize_filter(count):
        if int(count) > 1:
            return "s"
        else:
            return ""

    @app.context_processor
    def inject_utilities():
        return {
            "current_url_with_query": current_url_with_query,
            "external_urls": external_urls,
            "static_url": static_url,
        }

    @app.context_processor
    def inject_today_date():
        return {"current_year": datetime.date.today().year}

    app.jinja_env.add_extension("jinja2.ext.do")

    @app.context_processor
    def utility_processor():
        return {"image": image_template}

    return app
Ejemplo n.º 4
0
def create_app(testing=False):
    app = FlaskBase(
        __name__,
        "jaas.ai",
        template_folder="../templates",
        static_folder="../static",
    )

    app.testing = testing
    app.after_request(add_headers)
    app.before_request(prepare_redirects())
    app.before_request(prepare_deleted())

    BlogExtension(app, "JAAS Case Studies", [3513], "lang:en", "/case-studies")
    talisker.requests.configure(cs.session)

    init_handler(app)
    init_blueprint(app)

    @app.template_filter("pluralize")
    def pluralize_filter(count):
        if int(count) > 1:
            return "s"
        else:
            return ""

    @app.context_processor
    def inject_utilities():
        return {
            "current_url_with_query": current_url_with_query,
            "external_urls": external_urls,
            "static_url": static_url,
        }

    @app.context_processor
    def inject_today_date():
        return {"current_year": datetime.date.today().year}

    app.jinja_env.add_extension("jinja2.ext.do")

    @app.context_processor
    def utility_processor():
        return {"image": image_template}

    return app
Ejemplo n.º 5
0
    def test_adds_redirects(self):
        def _deleted_callback(context):
            return "Deleted", 410

        p_deleted = prepare_deleted(path="./tests/deleted.yaml",
                                    view_callback=_deleted_callback)
        p_redirects = prepare_redirects(path="./tests/redirects.yaml")

        app = FlaskBase(__name__, "canonicalwebteam.flask-base", p_deleted,
                        p_redirects)

        with app.test_client() as client:
            response = client.get("redirect")
            self.assertEqual(302, response.status_code)
            self.assertEqual(response.headers.get("Location"),
                             "https://httpbin.org/")

            response = client.get("deleted")
            self.assertEqual(410, response.status_code)
            self.assertEqual(response.data, b"Deleted")
Ejemplo n.º 6
0
def create_app(testing=False):
    app = FlaskBase(
        __name__,
        "jaas.ai",
        template_folder="../templates",
        static_folder="../static",
    )

    app.testing = testing
    app.after_request(add_headers)
    app.before_request(prepare_redirects())
    app.before_request(prepare_deleted())

    init_handler(app)
    init_blueprint(app)

    @app.template_filter("pluralize")
    def pluralize(count):
        if count != 1:
            return "s"
        return ""

    @app.context_processor
    def inject_utilities():
        return {
            "current_url_with_query": current_url_with_query,
            "external_urls": external_urls,
            "static_url": static_url,
        }

    @app.context_processor
    def inject_today_date():
        return {"current_year": datetime.date.today().year}

    app.jinja_env.add_extension("jinja2.ext.do")

    return app
Ejemplo n.º 7
0
def create_app(testing=False):
    app = flask.Flask(__name__,
                      template_folder="../templates",
                      static_folder="../static")

    app.config.from_object("webapp.config")
    app.testing = testing

    app.wsgi_app = ProxyFix(app.wsgi_app)
    if app.debug:
        app.wsgi_app = DebuggedApplication(app.wsgi_app)

    app.url_map.strict_slashes = False
    app.url_map.converters["regex"] = helpers.RegexConverter

    if not testing:
        init_extensions(app)

        talisker.flask.register(app)
        talisker.requests.configure(webapp.api.blog.api_session)
        talisker.requests.configure(webapp.api.dashboard.api_session)
        talisker.requests.configure(webapp.api.sso.api_session)
        talisker.logs.set_global_extra({"service": "snapcraft.io"})

    app.config.from_object("webapp.configs." + app.config["WEBAPP"])

    app.before_request(prepare_redirects())
    app.before_request(prepare_deleted())

    set_handlers(app)

    if app.config["WEBAPP"] == "snapcraft":
        init_snapcraft(app, testing)
    else:
        init_brandstore(app)

    return app
    def __init__(self,
                 name,
                 service,
                 favicon_url=None,
                 template_404=None,
                 template_500=None,
                 *args,
                 **kwargs):
        super().__init__(name, *args, **kwargs)

        self.service = service

        self.config["SECRET_KEY"] = os.environ["SECRET_KEY"]

        self.url_map.strict_slashes = False
        self.url_map.converters["regex"] = RegexConverter

        if self.debug:
            self.wsgi_app = DebuggedApplication(self.wsgi_app)

        self.wsgi_app = ProxyFix(self.wsgi_app)

        self.before_request(clear_trailing_slash)

        self.before_request(
            prepare_redirects(
                path=os.path.join(self.root_path, "..", "redirects.yaml")))
        self.before_request(
            prepare_redirects(
                path=os.path.join(self.root_path, "..",
                                  "permanent-redirects.yaml"),
                permanent=True,
            ))
        self.before_request(
            prepare_deleted(
                path=os.path.join(self.root_path, "..", "deleted.yaml")))

        self.after_request(set_security_headers)
        self.after_request(set_cache_control_headers)
        self.after_request(set_permissions_policy_headers)
        self.after_request(set_clacks)

        self.context_processor(base_context)

        talisker.flask.register(self)
        talisker.logs.set_global_extra({
            "service": self.service,
            "pid": os.getpid()
        })

        # Default error handlers
        if template_404:

            @self.errorhandler(404)
            def not_found_error(error):
                return (
                    flask.render_template(template_404,
                                          message=error.description),
                    404,
                )

        if template_500:

            @self.errorhandler(500)
            def internal_error(error):
                return (
                    flask.render_template(template_500,
                                          message=error.description),
                    500,
                )

        # Default routes
        @self.route("/fish")
        def fish_chips():
            return "chips"

        # Default routes
        @self.route("/_status/check")
        def status_check():
            return STATUS_CHECK

        favicon_path = os.path.join(self.root_path, "../static", "favicon.ico")
        if os.path.isfile(favicon_path):

            @self.route("/favicon.ico")
            def favicon():
                return flask.send_file(favicon_path,
                                       mimetype="image/vnd.microsoft.icon")

        elif favicon_url:

            @self.route("/favicon.ico")
            def favicon():
                return flask.redirect(favicon_url)

        robots_path = os.path.join(self.root_path, "..", "robots.txt")
        humans_path = os.path.join(self.root_path, "..", "humans.txt")
        security_path = os.path.join(self.root_path, "..", "security.txt")

        if os.path.isfile(robots_path):

            @self.route("/robots.txt")
            def robots():
                return flask.send_file(robots_path)

        if os.path.isfile(humans_path):

            @self.route("/humans.txt")
            def humans():
                return flask.send_file(humans_path)

        if os.path.isfile(security_path):

            @self.route("/.well-known/security.txt")
            def security():
                return flask.send_file(security_path)
this_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(this_dir)

app_redirects = Flask("redirects", template_folder=f"{this_dir}/templates")
app_permanent_redirects = Flask("redirects",
                                template_folder=f"{this_dir}/templates")
app_empty_redirects = Flask("empty_redirects",
                            template_folder=f"{this_dir}/templates")
app_deleted = Flask("deleted", template_folder=f"{this_dir}/templates")
app_empty_deleted = Flask("empty_deleted",
                          template_folder=f"{this_dir}/templates")
app_deleted_callback = Flask("deleted_callback",
                             template_folder=f"{this_dir}/templates")

app_redirects.before_request(
    prepare_redirects(path=f"{parent_dir}/redirects.yaml"))
app_permanent_redirects.before_request(
    prepare_redirects(path=f"{parent_dir}/redirects.yaml", permanent=True))
app_deleted.before_request(prepare_deleted(path=f"{parent_dir}/deleted.yaml"))
app_deleted_callback.before_request(
    prepare_deleted(path=f"{parent_dir}/deleted.yaml", view_callback=callback))
app_empty_redirects.before_request(
    prepare_redirects(path=f"{parent_dir}/empty.yaml"))
app_empty_deleted.before_request(
    prepare_deleted(path=f"{parent_dir}/empty.yaml"))


@app_redirects.route("/homepage")
@app_deleted.route("/homepage")
def homepage():
    return "hello world"
Ejemplo n.º 10
0
# Local
from webapp.blueprint import jp_website
from webapp.handlers import set_handlers


class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]


app = flask.Flask(__name__,
                  template_folder="../templates",
                  static_folder="../static")

app.before_request(prepare_redirects())

app.url_map.strict_slashes = False
app.url_map.converters["regex"] = RegexConverter

app.wsgi_app = ProxyFix(app.wsgi_app)
if app.debug:
    app.wsgi_app = DebuggedApplication(app.wsgi_app)

talisker.flask.register(app)
talisker.logs.set_global_extra({"service": "jp.ubuntu.com"})

set_handlers(app)
app.register_blueprint(jp_website)

blog_views = BlogViews(blog_title="Ubuntu blog", tag_ids=[3184])
Ejemplo n.º 11
0
    def __init__(
        self,
        name,
        service,
        favicon_url=None,
        template_404=None,
        template_500=None,
        *args,
        **kwargs
    ):
        super().__init__(name, *args, **kwargs)

        self.service = service

        self.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "base_secret")

        self.url_map.strict_slashes = False
        self.url_map.converters["regex"] = RegexConverter

        if self.debug:
            self.wsgi_app = DebuggedApplication(self.wsgi_app)

        self.wsgi_app = ProxyFix(self.wsgi_app)

        self.before_request(clear_trailing_slash)

        self.before_request(
            prepare_redirects(
                path=os.path.join(self.root_path, "..", "redirects.yaml")
            )
        )
        self.before_request(
            prepare_redirects(
                path=os.path.join(
                    self.root_path, "..", "permanent-redirects.yaml"
                ),
                permanent=True,
            )
        )
        self.before_request(
            prepare_deleted(
                path=os.path.join(self.root_path, "..", "deleted.yaml")
            )
        )

        self.context_processor(base_context)

        talisker.flask.register(self)
        talisker.logs.set_global_extra({"service": self.service})

        # Default error handlers
        if template_404:

            @self.errorhandler(404)
            def not_found_error(error):
                return flask.render_template(template_404), 404

        if template_500:

            @self.errorhandler(500)
            def internal_error(error):
                return flask.render_template(template_500), 500

        # Default routes
        if favicon_url:

            @self.route("/favicon.ico")
            def favicon():
                return flask.redirect(favicon_url)

        robots_path = os.path.join(self.root_path, "..", "robots.txt")
        humans_path = os.path.join(self.root_path, "..", "humans.txt")

        if os.path.isfile(robots_path):

            @self.route("/robots.txt")
            def robots():
                return flask.send_file(robots_path)

        if os.path.isfile(humans_path):

            @self.route("/humans.txt")
            def humans():
                return flask.send_file(humans_path)
Ejemplo n.º 12
0
def create_app(testing=False):
    app = FlaskBase(
        __name__,
        "jaas.ai",
        template_folder="../templates",
        static_folder="../static",
    )

    app.testing = testing
    app.after_request(add_headers)
    app.before_request(prepare_redirects("redirects.yaml"))
    app.before_request(
        prepare_redirects("permanent-redirects.yaml", permanent=True))
    app.before_request(prepare_deleted())

    blog_views = BlogViews(
        api=BlogAPI(
            session=session,
            thumbnail_width=354,
            thumbnail_height=180,
        ),
        blog_title="JAAS Case Studies",
        tag_ids=[3513],
        feed_description="Case Studies from happy JAAS users",
    )
    app.register_blueprint(build_blueprint(blog_views),
                           url_prefix="/case-studies")

    # Handlers
    # ===
    @app.errorhandler(404)
    def page_not_found(error):
        """
        For 404 pages, display the 404.html template,
        passing through the error description.
        """

        return flask.render_template("404.html", error=error.description), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        """
        For 500 pages, display the 500.html template,
        passing through the error.
        """

        return flask.render_template("500.html", error=error), 500

    @app.errorhandler(410)
    def gone(error):
        """
        For 410 pages, display the 410.html template,
        passing through the error.
        """

        return flask.render_template("410.html", error=error), 410

    # Blueprints
    # ===
    app.register_blueprint(jaasai)

    # Dashboard and redirect views
    # ===
    @app.route("/models")
    @app.route("/models/<path:path>")
    @app.route("/controllers")
    @app.route("/controllers/<path:path>")
    def dashboard_index(path=None):
        """
        Send /models and /controllers to the index page
        """

        return flask.render_template("dashboard/index.html")

    @app.route("/config.js")
    @app.route("/manifest.json")
    @app.route("/ghost-bundle.svg")
    def dashboard_files():
        """
        Load dashboard files directly
        """

        return flask.render_template("dashboard" + flask.request.path)

    @app.route("/q/")
    @app.route("/q/<path:path>")
    def search_redirect(path=None):
        """
        Handle redirects from jujucharms.com search URLS to the jaas.ai format.
        e.g. /q/k8s/demo?sort=-name&series=xenial will redirect to
        /search?q=k8s+demo&sort=-name&series=xenial
        """
        query_string = []
        if path:
            query_string.append("q={}".format(path.replace("/", "+")))
        if flask.request.query_string:
            query_string.append(str(flask.request.query_string, "utf-8"))
        return flask.redirect("/search?{}".format("&".join(query_string)),
                              code=302)

    @app.route("/<charm_or_bundle_name>")
    @app.route("/<charm_or_bundle_name>/<series_or_version>")
    @app.route("/<charm_or_bundle_name>/<series_or_version>/<version>")
    def details_redirect(
        charm_or_bundle_name,
        series_or_version=None,
        version=None,
    ):

        charmhub_url = "https://charmhub.io/" + charm_or_bundle_name
        return flask.redirect(charmhub_url, code=301)

    # Template filters
    # ===
    @app.template_filter("pluralize")
    def pluralize_filter(count):
        if int(count) > 1:
            return "s"
        else:
            return ""

    @app.context_processor
    def inject_utilities():
        return {
            "current_url_with_query": current_url_with_query,
            "external_urls": external_urls,
            "static_url": static_url,
        }

    @app.context_processor
    def inject_today_date():
        return {"current_year": datetime.date.today().year}

    app.jinja_env.add_extension("jinja2.ext.do")

    @app.context_processor
    def utility_processor():
        return {"image": image_template}

    return app