from flask import Flask, request, redirect
import random
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" placeholder="title" name="title"></p>
<p><textarea placeholder="body" name="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 = f'/read/{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" placeholder="title" name="title" value={title}></p>
<p><textarea placeholder="body" name="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 = f'/read/{str(id)}/'
return redirect(url)
# 가변 라우팅 받기
@app.route('/read/<int:id>/')
def read(id): # 여기로 전달되는 인자는 int로 전달
title = ''
body = ''
for topic in topics:
if id == topic['id']:
title = topic['title']
body = topic['body']
break
print(title, body)
return template(getContents(), f'<h2>{title}</h2>{body}', id)
app.run(debug=True)
댓글남기기