Flask webserver - adding HTML and CSS


Martin McBride, 2020-01-22
Tags css html
Categories flask

In the previous example, our web page wasn't a true web page at all. It was just a line of text, not HTML. A browser will display that as plain text, but you cannot format it in any way.

Flask allows us to create HTML files and use them as templates for our web pages.

Creating the HTML page

Create a basic HTML page, like this:

<html>
  <head>
  </head>
  <body>
    <h1>Home page</h1>
    <p>My first Flask site</p>
  </body>
</html>

Save this file is a folder called templates, under your working folder. Name the file index.html.

Changing the Python code

You will need to make a couple of changes to server.py. First you must import render_template from the Flask module. Change your first line to this:

from flask import Flask, render_template

Then you must change your index function to this:

@app.route('/')
def index():
    return render_template('index.html')

Here, instead of returning a string, our index() function returns the result of render_template(). This function reads is the html file index.html, and returns its content as a string. Flask looks in the templates folder to find the html file.

Run the program and view the file in your browser. It should look like this:

Adding CSS

The page so far looks pretty boring, like a web page from 1995. We can improve things a little bit by adding come colour and using different fonts. We do this using a CSS (cascading style sheets) file, like this:

body {
  background: Linen;
  margin-top: 50px;
  margin-left: 100px;
  }

p {
  font-family: Georgia, serif;
  font-size: 1.2em;
  color: DarkSlateGray;
  }

h1 {
  font-family: Verdana, Geneva, sans-serif;
  font-size: 2.5em;
  color: FireBrick;
  }

This code adds a background colour, and sets margins so that the text isn't crammed into the top corner. It also sets the font, size and colour of the heading text (h1) and the paragraph text (p). You can change these values if you wish.

Create a folder called static, under your working folder. Name the file main.css and store it in the folder.

You will also need to edit your html file to include the CSS file. Add the extra line in the head section like this:

<html>
  <head>
    <link rel="stylesheet" href='/static/main.css' />
  </head>
  <body>
    <h1>Home page</h1>
    <p>My first Flask site</p>
  </body>
</html>

Your page should now look like this:

adding-html-2

If you found this article useful, you might be interested in the book Functional Programming in Python or other books by the same author.

Prev

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart polygon positional parameter print pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip