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 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
学Linux的语莫9 天前
python基础语法
开发语言·python
你的人类朋友9 天前
(●'◡'●)从Dockerfile快速入门Docker Compose
后端
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python
Ven%9 天前
PyTorch 张量(Tensors)全面指南:从基础到实战
人工智能·pytorch·python
mahuifa9 天前
PySide环境配置及工具使用
python·qt·环境配置·开发经验·pyside
GetcharZp9 天前
「神器推荐」Rclone:轻松玩转云端存储,FTP 也能飞起来!
后端
华子w9089258599 天前
基于 SpringBoot+JSP 的医疗预约与诊断系统设计与实现
java·spring boot·后端