Python網頁設計:Flask使用筆記(四) -ToDoList網頁APP(CSS+SQL+Template)

Yanwei Liu
4 min readMay 31, 2019

--

教學影片
from flask import Flask, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app) #連接SQL資料庫
class Todo(db.Model): #產生功能
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
#上述步驟完成後,必須建立test.db檔案
#進入python環境
#from app import db
#db.create_all()
#exit()
@app.route('/', methods=['POST', 'GET']) #使用POST和GET方法
def index():
if request.method == 'POST':
task_content = request.form['content']
new_task = Todo(content=task_content)
try:
db.session.add(new_task) #添加任務
db.session.commit()
return redirect('/')
except:
return 'There was an issue adding your task'
else: #從資料庫中取得剛才添加的任務
tasks = Todo.query.order_by(Todo.date_created).all()
return render_template('index.html', tasks=tasks)
@app.route('/delete/<int:id>')
def delete(id):
task_to_delete = Todo.query.get_or_404(id)
try:
db.session.delete(task_to_delete) #刪除資料庫中的任務
db.session.commit()
return redirect('/') #重新導向到根目錄
except:
return 'There was a problem deleting that task'
@app.route('/update/<int:id>', methods=['GET', 'POST'])
#使用GET和POST方法
def update(id):
task = Todo.query.get_or_404(id)
if request.method == 'POST':
task.content = request.form['content'] #新增任務
try:
db.session.commit()
return redirect('/')
except:
return 'There was an issue updating your task'
else:
return render_template('update.html', task=task)
if __name__ == "__main__":
app.run(debug=True)

程式完成後,可搭配Flask使用筆記(三)- 佈署到Google Computer Engine,將APP部屬到GCE上,透過瀏覽器瀏覽

--

--

Responses (1)