Flask python开发篇: 写一个简单的接口

第一步:新建flask项目

参考使用pycharm新建一个项目

打开pycharm,根据下面图中箭头顺序,新建一个flask的项目;

第二步:运行项目,

安装成功以后,会有个app.py文件,打开以后,运行它;

可以使用右上角的运行按钮运行;也可以在文件内右击运行,如下图:

运行以后,会出现访问地址,这时候浏览器就能打开访问了

第三步:编写自己的第一个接口

复制代码
from flask import Flask, request, jsonify

app = Flask(__name__)

# 假设博客文章数据存储在一个列表中
posts = [
    {"id": 1, "title": "Hello World", "content": "This is the first blog post."},
    {"id": 2, "title": "Introduction to Flask", "content": "A tutorial on using Flask to build web applications."}
]

# 获取所有博客文章列表
@app.route('/api/posts', methods=['GET'])
def get_posts():
    return jsonify(posts)

# 获取单篇博客文章
@app.route('/api/posts/<int:post_id>', methods=['GET'])
def get_post(post_id):
    post = next((p for p in posts if p["id"] == post_id), None)
    if post:
        return jsonify(post)
    else:
        return jsonify({"message": "Post not found"}), 404

# 创建新的博客文章
@app.route('/api/posts', methods=['POST'])
def create_post():
    data = request.get_json()
    if "title" in data and "content" in data:
        new_post = {
            "id": len(posts) + 1,
            "title": data["title"],
            "content": data["content"]
        }
        posts.append(new_post)
        return jsonify(new_post), 201
    else:
        return jsonify({"message": "Invalid data"}), 400

# 更新博客文章
@app.route('/api/posts/<int:post_id>', methods=['PUT'])
def update_post(post_id):
    post = next((p for p in posts if p["id"] == post_id), None)
    if post:
        data = request.get_json()
        post["title"] = data.get("title", post["title"])
        post["content"] = data.get("content", post["content"])
        return jsonify(post)
    else:
        return jsonify({"message": "Post not found"}), 404

# 删除博客文章
@app.route('/api/posts/<int:post_id>', methods=['DELETE'])
def delete_post(post_id):
    global posts
    posts = [p for p in posts if p["id"] != post_id]
    return '', 204

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

这里假设数据存储在一个列表里,并不是从数据库中取出的,先跑起来哈,下一篇我再分享怎么连接数据库;

这时候访问http://127.0.0.1:5000/api/posts,就能获取到数据了

相关推荐
果粒蹬i1 分钟前
Python + AI:打造你的智能害虫识别助手
开发语言·人工智能·python
阿钱真强道2 分钟前
09 jetlinks-mqtt-属性主动上报-windows-python-实现
开发语言·windows·python·网络协议
Blossom.1182 分钟前
从单点工具到智能流水线:企业级多智能体AI开发工作流架构实战
人工智能·笔记·python·深度学习·神经网络·架构·whisper
亚林瓜子3 分钟前
pyspark添加一列时间戳数据并改名
python·spark
咖啡啡不加糖3 分钟前
Arthas 使用指南:Java 应用诊断利器
java·spring boot·后端
2401_841495643 分钟前
【机器学习】标准化流模型(NF)
人工智能·python·机器学习·标准化流模型·概率生成模型·可逆变换·概率密度变换
J_liaty4 分钟前
SpringBoot整合Canal实现数据库实时同步
数据库·spring boot·后端·canal
lead520lyq4 分钟前
Golang Grpc接口调用实现账号密码认证
开发语言·后端·golang
Blossom.1185 分钟前
从“金鱼记忆“到“超级大脑“:2025年AI智能体记忆机制与MoE架构的融合革命
人工智能·python·算法·架构·自动化·whisper·哈希算法
JaguarJack7 分钟前
Laravel AI SDK 在 Laracon India 2026 首次亮相
后端·php·laravel