上一篇規劃完後就該來一步步完成 todo list API 了,使用 Flask 框架能及幫助我們在短時間內建立一個簡易的 API 專案,基於 MVC 架構我們會將負責處理資料儲存的 model 與控制資料的 Controller 及使用者介面的 Views 分開,在 model 的資料處理上我們會使用 peewee 作為我們的 ORM(Object Relational Mapping) 套件,話不多說,開始實作吧~
$ mkdir todo_list_backend
$ touch app.py
from flask import Flask
from flask_cors import CORS
def create_app():
app = Flask(__name__)
CORS(app)
@app.route('/', methods=['GET'])
def home():
return "<h1>Hello Flask!</h1>"
return app
from peewee import MySQLDatabase, Model, DateTimeField
from datetime import datetime
from config import Config
def connection_resolver():
return MySQLDatabase(
Config.DB_NAME,
user=Config.DB_USERNAME,
password=Config.DB_PASSWORD,
host=Config.DB_HOST,
port=3306,
autorollback=True
)
connection = connection_resolver()
class BaseModel(Model):
created_at = DateTimeField(default=datetime.now)
updated_at = DateTimeField(default=datetime.now)
def save(self, *args, **kwargs):
self.updated_at = datetime.now()
return super(BaseModel, self).save(*args, **kwargs)
class Meta:
database = connection
from .base import BaseModel
from peewee import CharField, IntegerField, DateTimeField
class Task(BaseModel):
name = CharField()
finish_at = DateTimeField(null=True)
deleted_at = IntegerField(default=-1)
class Meta:
indexes = [
(('name', ), True),
]
from flask_restful import Resource, reqparse
from src.models import Task
class TaskList(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True,)
def post(self):
data = TaskList.parser.parse_args()
status = 200
message = '新增成功'
try:
name = data['name']
task_id = Task.create(name=name)
except Exception as e:
status = 409
message = '新增失敗'
return {
'message': message,
}, status
先撰寫 /tasks [POST] 的功能,輸入任務名稱可以新增一筆任務資訊至資料庫
from flask import Blueprint
from flask_restful import Api
from src.resource.task import TaskList
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
@api_bp.route('/')
def show():
return "this is todo list API"
api.add_resource(TaskList, '/tasks')
from flask import Flask
from flask_cors import CORS
from src.routes.router import api_bp
def create_app():
app = Flask(__name__)
CORS(app)
@app.route('/', methods=['GET'])
def home():
return "<h1>Hello Flask!</h1>"
app.register_blueprint(api_bp, url_prefix='/api')
return app
$ python3 -m flask run --host=0.0.0.0 --port=80
如此一來,簡易的 flask todo list API初步就算完成,下一篇會將剩餘的 API 做完並殃前端串接完成