Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ __pycache__/
*.pyc
app.db
auth.db
university.db
39 changes: 39 additions & 0 deletions class-2/week2-sqlite/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from fastapi import FastAPI
from pathlib import Path
import sqlite3

app = FastAPI()


# Check where you are connecting! Ask yourself: "Which one is my database?"
# The students table lives in university.db, created in Part 1 by setup_students.sql.
# Careful: sqlite3.connect() silently CREATES an empty file if this path does not
# exist, so a wrong filename shows up later as "no such table", not "file not found".
DB_PATH = Path(__file__).parent / "university.db"


def get_connection():
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row

return connection


@app.get("/")
def home():
return {"message": "University API is running"}


@app.get("/students")
def get_students():
connection = get_connection()

try:
cursor = connection.cursor()
cursor.execute("select * from students")
students = cursor.fetchall()

finally:
connection.close()

return students
2 changes: 2 additions & 0 deletions class-2/week2-sqlite/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fastapi==0.141.1
uvicorn==0.52.4
14 changes: 14 additions & 0 deletions class-2/week2-sqlite/setup_students.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
course TEXT NOT NULL,
year INTEGER NOT NULL
);

INSERT INTO students (name, course, year)
VALUES ('Ada Lovelace', 'Cloud Computing', 2);
INSERT INTO students (name, course, year)
VALUES ('Alan Turing', 'Artificial Intelligence', 3);

INSERT INTO students (name, course, year)
VALUES ('Grace Hopper', 'Software Engineering', 2);