tinycodinglm / code /appdev-0075.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
3.01 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

Walk me through building a database app: key concepts, concrete details and common pitfalls. Include a runnable code example with its expected output.

Assistant

Full-Stack SQLite App (contacts manager):

python
import sqlite3
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

def init_db():
    conn = sqlite3.connect('contacts.db')
    conn.execute('''CREATE TABLE IF NOT EXISTS contacts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT UNIQUE,
        phone TEXT
    )''')
    conn.commit()
    conn.close()

init_db()

class Contact(BaseModel):
    name: str
    email: str
    phone: Optional[str] = None

@app.get('/contacts')
def list_contacts():
    conn = sqlite3.connect('contacts.db')
    rows = conn.execute('SELECT * FROM contacts').fetchall()
    conn.close()
    return [{'id': r[0], 'name': r[1], 'email': r[2], 'phone': r[3]} for r in rows]

@app.post('/contacts', status_code=201)
def create_contact(c: Contact):
    conn = sqlite3.connect('contacts.db')
    try:
        conn.execute('INSERT INTO contacts (name, email, phone) VALUES (?, ?, ?)',
                     (c.name, c.email, c.phone))
        conn.commit()
        id = conn.execute('SELECT last_insert_rowid()').fetchone()[0]
    except sqlite3.IntegrityError:
        raise HTTPException(400, 'Email already exists')
    finally:
        conn.close()
    return {'id': id, **c.model_dump()}

@app.get('/contacts/{id}')
def get_contact(id: int):
    conn = sqlite3.connect('contacts.db')
    row = conn.execute('SELECT * FROM contacts WHERE id = ?', (id,)).fetchone()
    conn.close()
    if not row:
        raise HTTPException(404, 'Contact not found')
    return {'id': row[0], 'name': row[1], 'email': row[2], 'phone': row[3]}

@app.delete('/contacts/{id}')
def delete_contact(id: int):
    conn = sqlite3.connect('contacts.db')
    conn.execute('DELETE FROM contacts WHERE id = ?', (id,))
    conn.commit()
    conn.close()
    return {'deleted': id}

Testing:

bash
# Create
curl -X POST http://localhost:8000/contacts \
  -H 'Content-Type: application/json' \
  -d '{"name": "Alice", "email": "alice@example.com"}'

# List
curl http://localhost:8000/contacts