Connecting PookieDB to Flask
You know how to use PookieDB on its own. Now you are going to bring it into a Flask project — and the first decision is where the database code lives.
Keep database logic in its own file
Your Flask project will now have two Python files:
flask-project/
├── .venv/
├── templates/
│ └── index.html
├── database.py ← connection, model, create_table()
└── app.py ← Flask routes, imports Patient from database.py
database.py handles everything to do with the database. app.py handles everything to do with Flask. They stay separate.
This is the same idea you already know — from flask import Flask borrows code from the Flask package. Here, from database import Patient borrows code from your own file.
database.py
import pookiedb
pookiedb.connect("sqlite:///patients.sqlite3")
class Patient(pookiedb.Model):
name = pookiedb.CharField(max_length=100)
age = pookiedb.IntegerField()
class Meta:
db_table = "patients"
Patient.create_table()
This file connects to the database, defines the Patient table, and creates it if it does not exist yet. Nothing Flask-specific here at all.
app.py
from flask import Flask, render_template, request, redirect, url_for
from database import Patient
app = Flask(__name__)
@app.route('/')
def home():
patients = Patient.objects.all()
return render_template('index.html', patients=patients)
@app.route('/add', methods=['POST'])
def add():
Patient.objects.create(
name=request.form["patient_name"],
age=int(request.form["age"])
)
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)
app.py only imports Patient. It does not know or care about PookieDB directly — that is database.py's job. app.py just uses Patient.objects.all() and Patient.objects.create() as if they were any other Python tool.
What happens when you run it
When you run python app.py:
- Python imports
database.py(because offrom database import Patient) database.pyconnects topatients.sqlite3and creates the table if needed- Flask starts and waits for requests
The patients.sqlite3 file appears in your project folder on the first run and stays there permanently.
Challenge
Set up the two-file structure above in a fresh project folder. Create database.py exactly as shown. Create app.py exactly as shown. Run python app.py and confirm you see the Flask server start without errors. The next page adds the template and ties everything together.