생활코딩

Coding Everybody

코스 전체목록

닫기

수정 기능 구현

수업

 

 

 

강의

 

 

 

요약

1. server.py에 아래 코드를 적용해주세요

from flask import Flask, request, redirect

app = Flask(__name__)


nextId = 4
topics = [
    {'id': 1, 'title': 'html', 'body': 'html is ...'},
    {'id': 2, 'title': 'css', 'body': 'css is ...'},
    {'id': 3, 'title': 'javascript', 'body': 'javascript is ...'}
]


def template(contents, content, id=None):
    contextUI = ''
    if id != None:
        contextUI = f'''
            <li><a href="/update/{id}/">update</a></li>
        '''
    return f'''<!doctype html>
    <html>
        <body>
            <h1><a href="/">WEB</a></h1>
            <ol>
                {contents}
            </ol>
            {content}
            <ul>
                <li><a href="/create/">create</a></li>
                {contextUI}
            </ul>
        </body>
    </html>
    '''


def getContents():
    liTags = ''
    for topic in topics:
        liTags = liTags + f'<li><a href="/read/{topic["id"]}/">{topic["title"]}</a></li>'
    return liTags


@app.route('/')
def index():
    return template(getContents(), '<h2>Welcome</h2>Hello, WEB')


@app.route('/read/<int:id>/')
def read(id):
    title = ''
    body = ''
    for topic in topics:
        if id == topic['id']:
            title = topic['title']
            body = topic['body']
            break
    return template(getContents(), f'<h2>{title}</h2>{body}', id)


@app.route('/create/', methods=['GET', 'POST'])
def create():
    if request.method == 'GET': 
        content = '''
            <form action="/create/" method="POST">
                <p><input type="text" name="title" placeholder="title"></p>
                <p><textarea name="body" placeholder="body"></textarea></p>
                <p><input type="submit" value="create"></p>
            </form>
        '''
        return template(getContents(), content)
    elif request.method == 'POST':
        global nextId
        title = request.form['title']
        body = request.form['body']
        newTopic = {'id': nextId, 'title': title, 'body': body}
        topics.append(newTopic)
        url = '/read/'+str(nextId)+'/'
        nextId = nextId + 1
        return redirect(url)


@app.route('/update/<int:id>/', methods=['GET', 'POST'])
def update(id):
    if request.method == 'GET': 
        title = ''
        body = ''
        for topic in topics:
            if id == topic['id']:
                title = topic['title']
                body = topic['body']
                break
        content = f'''
            <form action="/update/{id}/" method="POST">
                <p><input type="text" name="title" placeholder="title" value="{title}"></p>
                <p><textarea name="body" placeholder="body">{body}</textarea></p>
                <p><input type="submit" value="update"></p>
            </form>
        '''
        return template(getContents(), content)
    elif request.method == 'POST':
        global nextId
        title = request.form['title']
        body = request.form['body']
        for topic in topics:
            if id == topic['id']:
                topic['title'] = title
                topic['body'] = body
                break
        url = '/read/'+str(id)+'/'
        return redirect(url)

app.run(debug=True)

차이점 : https://github.com/egoing/flask-tutorial-src/commit/ac8eb60d93556f3b76ff52e273ba89b07917c131

 

 

댓글

댓글 본문
  1. Sansol Park
    'update' 라우트에서 POST 메소드를 처리하는 부분에서 문제가 생긴 것 같습니다.

    보신 것처럼, 'update' 라우트의 POST 메소드 처리 부분에서 'nextId' 변수를 사용하고 있습니다. 이 변수는 새로운 항목을 생성할 때 사용하는 것으로, 'update' 동작에서는 필요하지 않습니다. 이 부분은 'create' 라우트의 코드를 복사해서 사용하면서 실수로 남아있는 것으로 보입니다.

    따라서 'update' 라우트의 POST 메소드 처리 부분에서 'nextId' 관련 코드를 제거하면 문제가 해결될 것입니다. 수정된 코드는 다음과 같습니다:

    @app.route('/update/<int:id>/', methods=['GET', 'POST'])
    def update(id):
    if request.method == 'GET':
    # 기존 코드 생략
    elif request.method == 'POST':
    title = request.form['title']
    body = request.form['body']
    for topic in topics:
    if id == topic['id']:
    topic['title'] = title
    topic['body'] = body
    break
    url = '/read/'+str(id)+'/'
    return redirect(url)

    위와 같이 수정하면, 'update' 동작을 수행할 때 새로운 항목을 생성하는 대신 기존 항목을 수정하게 됩니다. 이렇게 하면 문제가 해결되어야 합니다.

    GPT-4의 답변입니다.
    대화보기
    • darkbob
      영상 마지막 6분 50초즈음부터 마지막 예제 execution 보여주실 때, 이게 create 가 아니고 update 라서 1. html 이 1.html5 가 되어야 하는데 4로 생성되네요? 이건 create 를 실행한것이랑 같은데 저장이 안되어서 잘못된 execution 인거지요?
    • 루미꼬짱
      감사합니다.
    graphittie 자세히 보기