Flask - (6)

Urls with flask

2020-01-04
by cS


A Flask route can have multiple urls, this is an example of how to handle two different urls for the same route.

# Level up the index route.
@app.route("/", methods=("GET",))
@app.route("/admin/report/<string:name>", methods=("GET",))
def index(name=None):
    date = datetime.datetime.now()
    stuff = {}
    # if the get request is for /
    if name is None:
        stuff["name"] = "anon"
    # if the get request is for /admin/report/<name>
    else: 
        stuff["name"] = name
    stuff.update({
        "location" : "Uranus",
        "unit" : "NVM-1999",
        "AO" : "Blue Fields",
        "operating_assets" : 13,
        "not_ok" : 0,
    })
    return render_template("home.html", stuff=stuff, date=date)

The home.html file may look like this.

{% block content %}
    {% if stuff.name %}
        <h1> Report for {{ stuff.name }}</h1>
    {% endif %}
    {{ date | report_head }}
    <h3>Drone units status</h3>
    <p> Unit Location {{ stuff.location }} </p>
    <p> Unit Name {{ stuff.unit }} </p>
    <p> Area of Operation {{ stuff.AO }} </p>
    <p> Unit Count {{ stuff.operating_assets }} </p>
    <p> Unit Casualties {{ stuff.not_ok }} </p>
    <style> body{ color: white; background: black;} </style>
{% endblock %}