모각코 15주차 모임 결과 (22.10.13 / 목요일 / 15시 ~ 18시 / Google Meet)

KIMA·2022년 10월 16일
0
post-thumbnail

목표

FastAPI, sqlite3를 이용한 CRUD API 구현

결과

from fastapi import FastAPI
from pydantic import BaseModel
import sqlite3

app = FastAPI()

conn = sqlite3.connect('answer.db', check_same_thread=False) # 주의! : check_same_thread=False은 실습때만 사용
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS Paste(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    content TEXT);''')
conn.commit()


class Paste(BaseModel):
    content: str


@app.get('/')
def root():
    return {'message': 'Hello World'}


@app.get('/paste/{paste_id}')
def get_paste(paste_id: int):
    res = cur.execute(
        'SELECT id, content FROM Paste WHERE id=?', (paste_id,))
    data = res.fetchone()

    if data is not None:
        paste = Paste(content=data[1])
        return {'paste_id': data[0],
                'paste': paste}
    else:
        return {'paste_id': paste_id,
                'paste': None}


@app.post('/paste/')
def post_paste(paste: Paste):
    cur.execute('INSERT INTO Paste(content) VALUES(?)', (paste.content,))
    conn.commit()
    res = cur.execute(
        'SELECT id, content FROM Paste WHERE content=?', (paste.content,))
    data = res.fetchone()

    return {'paste_id': data[0],
            'paste': Paste(content=data[1])}


@app.put('/paste/{paste_id}')
def put_paste(paste_id: int, paste: Paste):
    cur.execute('UPDATE Paste SET content=? WHERE id=?',
                (paste.content, paste_id))
    conn.commit()
    res = cur.execute(
        'SELECT id, content FROM Paste WHERE id=?', (paste_id,))
    data = res.fetchone()

    return {'paste_id': data[0],
            'paste': Paste(content=data[1])}


@app.delete('/paste/{paste_id}')
def delete_paste(paste_id: int):
    cur.execute('DELETE FROM Paste WHERE id=?', (paste_id,))
    conn.commit()

    return {'message': 'Delete Complete! id=' + str(paste_id)}
profile
안녕하세요.

0개의 댓글