FLASK

[FLASK] 삭제(Delete)

판다조아 2022. 11. 14. 10:42

 

 

 

현재 코드 ▼

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('/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('/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('/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':
        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)

 

 

 

마지막으로 삭제 기능을 구현해 보도록 하겠습니다 !

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

삭제 기능도 id가 있을 때 활성화 되어야 하므로

contextUI에 삭제 버튼을 만들어 주도록 합니다!

 

create나 update는 수정과 추가라는 ui가 필요했고

이동하기 위해서 <a>태그를 사용했습니다.

예를 들어 create를 클릭하면 생성 페이지로 이동하고

글을 쓰고 create버튼을 누르면 생성이 완료됩니다.

삭제 기능은 클릭하면 바로 삭제가 되도록 할 것이므로

링크 사용이 필요하지 않습니다 !

 

<form>태그를 이용해

action 속성에 데이터를 전송할 url을 적어주고

method=POST로 명시해 줍니다.

 

누군가 직접 url을 치고 들어간다 하더라도

그것은 GET 방식이기 때문에 삭제가 되지 않고

의도적으로 "POST"방식으로 전송시에만 삭제가 됩니다 !

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

위와 같이 delete 라우트를 만들어 줍니다.

id값을 받고 method는 POST 방식만을 허용합니다.

 

id가 topic의 id와 같아면

remove() 함수를 이용하여 topics에서 제거합니다.

 

삭제가 완료되면 홈페이지로('/') 이동합니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

잘 작동하는지 확인해 보겠습니다 !

홈페이지에서 html을 클릭하면 ~

 

 

 

 

 

 

 

 

 

 

 

read페이지로 이동하고

delete버튼이 보입니다.

 

 

 

 

 

 

 

 

 

 

 

 

삭제가 완료되어 홈페이지로 이동하고

html이 목록에서 사라졌습니다 !

 

 

 

 

 

 

 

 

 

 

 

삭제(Delete) 완성!

@app.route('/delete/<int:id>/', methods=['POST'])
def delete(id):
    for topic in topics:
        if id == topic['id']:
            topics.remove(topic)
            break
    return redirect('/')

 

 

 

 

 

 

 

 

출처