Flask入门:轻松掌握API路由定义

你是不是总觉得Flask路由定义复杂难记?事实上,超过80%的Python Web开发者首次接触Flask时都在路由配置上栽过跟头!
本文将从零开始讲解Flask路由的核心知识,重点演示常见API路由的定义方法,包括:

  • 基础路由配置

  • 动态URL参数处理

  • HTTP方法限定技巧

  • 完整可运行代码示例

✨ Flask路由是什么?

路由就像是Web应用的交通指挥系统,它决定了当用户访问某个URL时,应该执行哪段代码来响应请求。

🚀 基础路由定义

最简单的路由就是一个URL对应一个函数:

复制代码
@app.route('/')
def home():
    return '欢迎来到首页!'

🎯 动态路由参数

想要处理像/user/123这样的URL?使用动态参数

复制代码
@app.route('/user/<username>')
def show_user(username):
    return f'用户:{username}'

🔧 常见API路由类型

  • GET请求:获取数据

    @app.route('/api/users', methods=['GET'])
    def get_users():
    return {'users': ['张三', '李四']}

  • POST请求:创建数据

    @app.route('/api/users', methods=['POST'])
    def create_user():
    # 处理创建用户逻辑
    return {'status': '用户创建成功'}

  • 参数类型限定

    @app.route('/post/int:post_id')
    def show_post(post_id):
    return f'文章ID:{post_id}'

💡 完整代码示例

下面是一个完整的Flask应用示例:

复制代码
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    return '首页'

@app.route('/user/<username>')
def user_profile(username):
    return f'用户主页:{username}'

@app.route('/api/data', methods=['GET', 'POST'])
def handle_data():
    if request.method == 'POST':
        return {'method': 'POST', 'status': 'created'}
    return {'method': 'GET', 'data': 'some data'}

if __name__ == '__main__':
    app.run(debug=True)

喜欢本文?点赞👍收藏⭐,关注我,一起学习更多有用的知识,完善你的技能树!

相关推荐
AI探索者5 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者5 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh7 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅7 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽8 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时11 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿14 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python