생활코딩

Coding Everybody

코스 전체목록

닫기

쓰기 기능 구현

수업소개

쓰기 기능의 구현 방법을 소개합니다. 

 

 

 

강의 1/2

 

 

 

요약

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

from flask import Flask

app = Flask(__name__)


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):
    return f'''<!doctype html>
    <html>
        <body>
            <h1><a href="/">WEB</a></h1>
            <ol>
                {contents}
            </ol>
            {content}
            <ul>
                <li><a href="/create/">create</a></li>
            </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}')


@app.route('/create/')
def create():
    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)


app.run(debug=True)

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

 

2. 서버로 전송할 사용자의 입력 정보는 form 태그로 그룹핑 합니다. 

3. <input type="submit"> 버튼은 form 태그 안의 입력 정보를 form의 action 속성으로 method 방식으로 전송합니다. 

4. <form method="XXX"> 가 GET일 때는 브라우저가 서버의 정보를 가져올 때 사용하고, POST는 브라우저가 서버의 정보를 변경할 때 사용합니다.

GET 방식으로 URL을 통해서 입력 정보가 전달 됩니다. 따라서 입력 정보가 노출되고, 길어질 경우 오류가 발생할 수 있습니다. 

POST는 http 통신의 body를 통해서 전송됩니다. 입력 정보가 감춰지고, 대용량의 데이터를 전송 할 수 있습니다. 

 

 

 

강의 2/2

 

 

 

요약 

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):
    return f'''<!doctype html>
    <html>
        <body>
            <h1><a href="/">WEB</a></h1>
            <ol>
                {contents}
            </ol>
            {content}
            <ul>
                <li><a href="/create/">create</a></li>
            </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}')


@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.run(debug=True)

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

 

 2. 브라우저의 요청 정보를 확인하기 위해서는 flask.request 모듈을 이용합니다. 

 

3. request.method는 브라우저가 전송한 method를 확인할 수 있습니다. 

 

4. request.form['NAME'] 는 브라우저가 전송한 POST 데이터를 확인할 수 있습니다. 

 

댓글

댓글 본문
  1. 드가자
    리스트에 추가된 제목과 본문은 어디에 저장되는건가요? 파이썬을 껏다 켜면 저장된 텍스트는 날아가버리네요
  2. 루미꼬짱
    감사합니다.
  3. 헤밍웨이
    어렵지만 하나하나 알아가는 재미가 있습니다 :)
  4. Lithium3
    코드 바꿔가면서도 하는게 재밌습니다.
graphittie 자세히 보기