Flask进阶:构建RESTful API和数据库交互

在初级教程中,我们已经介绍了如何使用Flask构建基础的Web应用。在本篇中级教程中,我们将学习如何用Flask构建RESTful API,以及如何使用Flask-SQLAlchemy进行数据库操作。

一、构建RESTful API

REST(Representational State Transfer)是一种构建Web服务的方法,它利用了HTTP协议中的四种基本操作:GET、POST、PUT和DELETE。在Flask中,我们可以方便地为每种HTTP方法定义路由:

python 复制代码
from flask import Flask, request, jsonify
app = Flask(__name__)

todos = []

@app.route('/todos', methods=['GET'])
def get_todos():
    return jsonify(todos)

@app.route('/todos', methods=['POST'])
def add_todo():
    todos.append(request.json.get('todo', ''))
    return '', 204

@app.route('/todos/<int:index>', methods=['PUT'])
def update_todo(index):
    todos[index] = request.json.get('todo', '')
    return '', 204

@app.route('/todos/<int:index>', methods=['DELETE'])
def delete_todo(index):
    del todos[index]
    return '', 204

二、使用Flask-SQLAlchemy进行数据库操作

Flask-SQLAlchemy是Flask的一个扩展,它提供了SQLAlchemy的所有功能,并为其添加了一些方便的功能,如分页支持等。

首先,你需要安装Flask-SQLAlchemy:

python 复制代码
pip install flask-sqlalchemy

然后,我们可以定义一个模型,并进行数据库操作:

python 复制代码
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

@app.route('/')
def index():
    user = User.query.filter_by(name='John').first()
    return 'Hello, {}!'.format(user.name)

在上述代码中,我们首先配置了数据库的URI,然后定义了一个User模型,最后在视图函数中进行了数据库查询。

以上,我们介绍了如何使用Flask构建RESTful API,以及如何使用Flask-SQLAlchemy进行数据库操作。希望这篇文章能帮助你深入理解Flask,开发更复杂的Web应用。

相关推荐
子兮曰2 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰2 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
爱勇宝2 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
胡写代码2 天前
别再前后端各写一套表单校验了
java·后端
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
大勇前进2 天前
原生 PHP 还是 Laravel?小项目到底要不要上框架
后端