kaki1013

3. 읽기 기능 구현 본문

버그바운티 스터디/FLASK

3. 읽기 기능 구현

kaki1013 2023. 7. 21. 19:57

# 예시 코드

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 ...'}
]


# 유지보수의 편의성을 위해서 기본 HTML 코드를 템플릿화
def template(contents, content):
    return f'''<!doctype html>
    <html>
        <body>
            <h1><a href="/">WEB</a></h1>
            <ol>
                {contents}
            </ol>
            {content}
        </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')


# id값을 정수로 받기 위해서 int로 지정해주었습니다.
@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():
    return 'Create'


app.run(debug=True)

'버그바운티 스터디 > FLASK' 카테고리의 다른 글

5. 쓰기 기능 구현 (2)  (0) 2023.07.22
4. 쓰기 기능 구현 (1)  (0) 2023.07.21
2. 홈페이지 구현  (0) 2023.07.21
1. Routing  (0) 2023.07.21
0. 수업 소개 및 개발환경 세팅  (0) 2023.07.21