Build Python web application using Flask
1. Intro to Flask
1.1 Simplest Demo
1.1.1 install virtual environment to separate package
cd a new folder # see existing packages pip list # venv module pip install virtualenv # create a folder called proj_env and add in venv module python -m venv proj_env .\proj_env\Scripts\activate # activate virtual env pip install Flask
1.1.2 create .py
from flask import Flask app = Flask(__name__) @app.route("/welcome/<USERNAME>") def index(USERNAME): return f"Welcome to the index page. {USERNAME}"
1.1.3 run
py -m flask run
url:http://127.0.0.1:5000/welcome/Doris
1.2 With HTML & CSS
.py
from flask import Flask, render_template app = Flask(__name__) headings = ("Name","Role","Salary") data = ( ( ("A","WWWW","123123"), ("B","RRRR","123123"), ("C","WWWW","123123"), ("D","RRRR","123123") ) ) @app.route("/") def table(): return render_template("table.html",headings=headings,data=data)
add templates/table.html
-
{% for xx in xx %} ... {% endfor %}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/static/style.css"/> </head> <body> <table> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %} </tr> {% for row in data %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} <tr> {% endfor %} </table> </body> </html>
add static/style.css