Inno/62/flask code
รุ่นแก้ไขเมื่อ 03:14, 10 มีนาคม 2563 โดย Jittat (คุย | มีส่วนร่วม)
เนื้อหา
หลังคลิป 2
main.py
from flask import Flask
from flask import render_template
from datetime import datetime
app = Flask(__name__)
news_items = {
1: {'id': 1,
'title': 'COVID-19 update',
'body': 'This is a news on COVID-19'},
2: {'id': 2,
'title': 'Facemasks found',
'body': 'Recent news on facemask production'},
3: {'id': 3,
'title':'Python 4',
'body':'Python 4 will be out soon.... this is FAKE'},
}
@app.route('/')
def index():
name = 'Somchai'
time = datetime.now()
return render_template('index.html',
name=name,
time=time,
news_items=news_items.values())
@app.route('/news/<id>/')
def show_news_item(id):
news_item = news_items[int(id)]
return render_template('news_item.html',
id=news_item['id'],
title=news_item['title'],
body=news_item['body'])
templates/index.html
<html>
<body>
<h1>Hello!! {{ name }}</h1>
Hi. This is {{ time }}. This is recent news.
<ul>
{% for item in news_items %}
<li>
<a href="{{ url_for('show_news_item', id=item.id) }}">{{ item.title }}</a>
</li>
{% endfor %}
</ul>
</body>
</html>
templates/show.html
<html>
<body>
<h1>{{ title }}</h1>
<p>{{ body }}</p>
<a href="{{ url_for('index') }}">Home</a>
</body>
</html>
หลังคลิป 3
main.py
from flask import Flask
from flask import render_template, redirect, url_for
from flask import request
from datetime import datetime
app = Flask(__name__)
news_items = {
1: {'id': 1,
'title': 'COVID-19 update',
'body': 'This is a news on COVID-19'},
2: {'id': 2,
'title': 'Facemasks found',
'body': 'Recent news on facemask production'},
3: {'id': 3,
'title':'Python 4',
'body':'Python 4 will be out soon.... this is FAKE'},
}
@app.route('/')
def index():
name = 'Somchai'
time = datetime.now()
return render_template('index.html',
name=name,
time=time,
news_items=news_items.values())
@app.route('/news/<id>/')
def show_news_item(id):
news_item = news_items[int(id)]
return render_template('news_item.html',
id=news_item['id'],
title=news_item['title'],
body=news_item['body'])
def new_news_item(title, body):
new_id = max(news_items.keys()) + 1
return {
'id': new_id,
'title': title,
'body': body
}
@app.route('/news/create/', methods=['POST'])
def create_news_item():
item = new_news_item(request.form['title'],
request.form['body'])
news_items[item['id']] = item
return redirect(url_for('index'))
templates/index.html
<html>
<body>
<h1>Hello!! {{ name }}</h1>
Hi. This is {{ time }}. This is recent news.
<ul>
{% for item in news_items %}
<li>
<a href="{{ url_for('show_news_item', id=item.id) }}">{{ item.title }}</a>
</li>
{% endfor %}
</ul>
<form action="{{ url_for('create_news_item') }}" method="POST">
Title: <input name="title"/><br />
Body: <textarea name="body"></textarea><br />
<input type="submit" value="Save"/>
</form>
</body>
</html>