Quiz 2
Registry Synced

Learning Objectives

279 words
1 min read

Reading compass

Now · Step 1: Database Models

Learning Objectives

  • Design database schema with SQLAlchemy
  • Create RESTful API endpoints
  • Implement CRUD operations
  • Flask app from Milestone 1
  • SQLAlchemy and Flask-Migrate installed
  • Database design diagram (Diagram)

Step 1: Database Models

python
# backend/models.py
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy()
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(256))
    posts = db.relationship('Post', backref='author', lazy=True)
    def to_dict(self):
        return {'id': self.id, 'username': self.username, 'email': self.email}
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    def to_dict(self):
        return {
            'id': self.id, 'title': self.title,
            'content': self.content,
            'created_at': self.created_at.isoformat(),
            'author': self.author.username
        }

Step 2: REST API Endpoints

python
# backend/routes.py
from flask import Blueprint, request, jsonify
from models import db, Post
api = Blueprint('api', __name__)
@api.route('/posts', methods=['GET'])
def get_posts():
    posts = Post.query.order_by(Post.created_at.desc()).all()
    return jsonify([p.to_dict() for p in posts])
@api.route('/posts', methods=['POST'])
def create_post():
    data = request.get_json()
    post = Post(title=data['title'], content=data['content'], user_id=1)
    db.session.add(post)
    db.session.commit()
    return jsonify(post.to_dict()), 201
@api.route('/posts/<int:id>', methods=['GET'])
def get_post(id):
    post = Post.query.get_or_404(id)
    return jsonify(post.to_dict())
@api.route('/posts/<int:id>', methods=['DELETE'])
def delete_post(id):
    post = Post.query.get_or_404(id)
    db.session.delete(post)
    db.session.commit()
    return '', 204
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.