DB Programming

DB programming tutorial

app.py

from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)

def get_conn():
    return pymysql.connect(
        host='localhost',
        user='tweninge',
        password='goirish',
        database='tweninge'
    )

@app.route("/")
def home():
    return render_template("web.html")

@app.route("/age", methods=["GET"])
def age():
    age = request.args.get("age", None)

    if age is None:
        return render_template("web.html")

    conn = get_conn()
    cur = conn.cursor()

    cur.execute(
        "INSERT INTO age_entries (age) VALUES (%s)",
        (age,)
    )
    conn.commit()

    cur.execute(
        "SELECT id, age, created_at "
        "FROM age_entries "
        "ORDER BY id DESC"
    )

    rows = cur.fetchall()

    cur.close()
    conn.close()

    return render_template(
        "web.html",
        age=age,
        rows=rows
    )

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

./templates/web.html

<!DOCTYPE html>
<html>
<head>
    <title>Web Programming Tutorial</title>
</head>

<body>

    <h1>Web Programming Basics</h1>

    <h2>1. HTML</h2>

    <p>This is a paragraph.</p>

    <a href="https://www.nd.edu">This is a link.</a>


    <h2>2. JavaScript and the DOM</h2>

    <p id="message">Nothing has happened yet.</p>

    <button onclick="document.getElementById('message').innerHTML='You clicked the button!'">
        Click Me
    </button>


    <h2>3. Forms and Databases</h2>

    <form action="/age" method="GET">
        Enter your age:
        <input type="text" name="age">
        <input type="submit" value="Submit">
    </form>


    {% if age %}

        <p>Your age is: {{ age }}</p>

        <h3>Previous Entries</h3>

        <table border="1">
            <tr>
                <th>ID</th>
                <th>Age</th>
                <th>Created</th>
            </tr>

            {% for row in rows %}
            <tr>
                <td>{{ row[0] }}</td>
                <td>{{ row[1] }}</td>
                <td>{{ row[2] }}</td>
            </tr>
            {% endfor %}

        </table>

    {% endif %}

</body>
</html>