수업소개
읽기 기능을 구현해봅니다.
강의
요약
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 ...'}
]
# 유지보수의 편의성을 위해서 기본 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)
차이점 : https://github.com/egoing/flask-tutorial-src/commit/255ccfbdd5865308f698dc23778cbeaa47784a59

