Skip to content

Commit

Permalink
add 404 handling
Browse files Browse the repository at this point in the history
Signed-off-by: chang-ning <[email protected]>
  • Loading branch information
crazyguitar committed Oct 10, 2018
1 parent a9394c3 commit b84bc79
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
10 changes: 8 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import os

from flask import Flask, abort, send_from_directory
from flask import Flask, abort, send_from_directory, render_template
from flask_sslify import SSLify
from flask_seasurf import SeaSurf
from flask_talisman import Talisman
Expand Down Expand Up @@ -39,7 +39,7 @@ def find_key(token):
"frame-ancestors": "'none'",
"object-src": "'none'",
}
app = Flask(__name__)
app = Flask(__name__, template_folder=ROOT)
app.config["SECRET_KEY"] = os.urandom(16)
app.config["SESSION_COOKIE_NAME"] = "__Secure-session"
app.config["SESSION_COOKIE_SAMESITE"] = "Strict"
Expand All @@ -53,6 +53,12 @@ def find_key(token):
sslify = SSLify(app, skips=[".well-known"])


@app.errorhandler(404)
def page_not_found(e):
"""Redirect to 404.html."""
return render_template("404.html"), 404


@app.after_request
def add_feature_policy(response):
"""Add feature policy."""
Expand Down
6 changes: 6 additions & 0 deletions app_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
static_proxy,
index_redirection,
add_feature_policy,
page_not_found,
)

from app import ROOT
Expand Down Expand Up @@ -139,6 +140,11 @@ def test_static_proxy(self):
self.assertEqual(resp.status_code, 200)
resp.close()

def test_page_not_found(self):
"""Test page not found."""
html, status_code = page_not_found(None)
self.assertEqual(status_code, 404)


if __name__ == "__main__":
unittest.main()
8 changes: 8 additions & 0 deletions docs/404.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
:orphan:

404 Page Not Found
==================

What you were looking for is just not there.

`Click here to go back to homepage. </>`_
9 changes: 9 additions & 0 deletions docs/_templates/layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,14 @@
gtag('config', '{{ tracking_id }}');
</script>
{% endif -%}
{%- if pagename == '404' -%}
<script>
gtag('event', '404', {
'event_category': 'error',
'event_label': document.referrer,
'non_interaction': true
});
</script>
{%- endif -%}
{% endblock %}
{% set css_files = css_files + [ "_static/style.css" ] %}

0 comments on commit b84bc79

Please sign in to comment.