Server-Side Scripting/Routes and Templates/Python (Flask)

app.py edit

# Demonstrates a complete server-side website using:
#   * static HTML and CSS
#   * a template
#   * a code module
#
# NOTE: Static pages (html, css, images, etc.) must be placed in
# a folder named "static". Template pages must be placed in a folder
# named "templates".
#
# Folder structure:
# app.py
# hello.py
# static
#   index.html
#   static.html
#   styles.css
# templates
#   template.html
#
# References:
#   https://en.wikiversity.org/wiki/Flask/Hello_World
#   https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

import flask

app = flask.Flask(__name__)

@app.route("/")
def show_root():
    return route_path("index.html")

@app.route("/<path:path>")
def route_path(path):
    if path == "code":
        return hello.main()
    elif path == "template":
        data = {
            "greeting": "Hello",
            "name": "world"
        }
        return flask.render_template('template.html', data=data)
    else:
        # Process any unrecognized route as a static file request
        return flask.send_from_directory(app.static_folder, path)  

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

hello.py edit

# This module returns "Hello code world!"

def main():
    return "Hello code world!"

static/index.html edit

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <h1>Hello World</h1>
      <ul>
          <li><a href="static.html">Static</a></li>
          <li><a href="template">Template</a></li>
          <li><a href="code">Code</a></li>
      </ul>
  </body>
</html>

static/static.html edit

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <link rel="stylesheet" href="styles.css">    
  </head>
  <body>
    <p>Hello static world!</p>
  </body>
</html>

static/styles.css edit

body {
    color: blue;
    font-family: Arial, Helvetica, sans-serif;
    font-size: larger;
}

templates/template.html edit

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <p>{{data.greeting}} template {{data.name}}!</p>
  </body>
</html>

Try It edit

Copy and paste the code above into the following free online development environment or use your own Python (Flask) compiler / interpreter / IDE.

See Also edit