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,就能获取到数据了

相关推荐
一方热衷.9 小时前
YOLO26-Seg ONNXruntime C++/python推理
开发语言·c++·python
YMWM_10 小时前
如何将包路径添加到conda环境lerobot的python路径中呢?
人工智能·python·conda
田里的水稻10 小时前
ubuntu22.04_openclaw_ROS2
人工智能·python·机器人
凤山老林10 小时前
SpringBoot 使用 H2 文本数据库构建轻量级应用
java·数据库·spring boot·后端
梁正雄11 小时前
Python前端-2-css练习
前端·css·python
清汤饺子11 小时前
用 Cursor 半年了,效率还是没提升?是因为你没用对这 7 个功能
前端·后端·cursor
雨夜之寂11 小时前
Browser Use + DeepSeek,我踩了哪些坑
后端·面试
wefly201711 小时前
开发者效率神器!jsontop.cn一站式工具集,覆盖开发全流程高频需求
前端·后端·python·django·flask·前端开发工具·后端开发工具
dreamread11 小时前
【SpringBoot整合系列】SpringBoot3.x整合Swagger
java·spring boot·后端
6+h11 小时前
【java】基本数据类型与包装类:拆箱装箱机制
java·开发语言·python