Flask 创建API接口服务

完整的 Flask API框架代码

python 复制代码
# modules/routes.py
from flask import Blueprint, request

# 创建一个蓝图对象,命名为 "routes"
blueprint = Blueprint("routes", __name__)

# 定义 GET /get_test 路由,返回一个简单的字符串消息
@blueprint.route("/get_test")
def get_test():
    test = "get test succ"
    return test

# 定义 GET / 路由,返回 HTML 文档
@blueprint.route("/")
def home():
    return "<h1>Test接口运行正常</h1>"

# 定义 POST /post_test 路由,处理 JSON 请求并返回修改后的 JSON 对象
@blueprint.route("/post_test", methods=["POST"])
def post_test():
    input_args = request.get_json()  # 从请求体中获取 JSON 参数
    input_args["status"] = 1  # 添加 "status" 键并设置为 1
    return input_args

# app.py
from flask import Flask
from modules.routes import blueprint

def create_app():
    """
    Flask Web APP 工厂函数。

    Linux环境启动指令:gunicorn --workers=5 --timeout=60 --bind=0.0.0.0:5000 "app:create_app()"
    :return: app
    """
    app = Flask(__name__)
    app.register_blueprint(blueprint)  # 注册蓝图

    return app

if __name__ == "__main__":
    # 开发环境测试用
    web_app = create_app()
    web_app.run(host="0.0.0.0", port=5000)

在开发环境中,可以直接运行 app.py 来启动应用。在生产环境中,可以使用以下命令通过 Gunicorn 启动应用:

bash 复制代码
gunicorn --workers=5 --timeout=60 --bind=0.0.0.0:5000 "app:create_app()"

这个命令设置了 5 个工作进程,每个请求的超时时间为 60 秒,并将应用绑定到 0.0.0.0 地址的 5000 端口。

相关推荐
BS30813_vx9 分钟前
基于 Express + uni-app 的养老院管理系统设计与实现
后端·uni-app·express
青 春 记 忆11 分钟前
零基础入门python69:为 FastAPI 项目构建可复现 Docker 镜像
python·fastapi·后端开发
<花开花落>14 分钟前
Python 项目迁移到 uv:经验小结与可复用工作流
python·uv
databook16 分钟前
正态分布撒谎时:用柯西分布捕捉生活中的“黑天鹅”
python·数据挖掘·数据分析
明月_清风19 分钟前
DeepSeek Harness 安全审计实录:四个 PoC 揭露的 Agent 运行时"信任危机"
后端·安全·agent
Java后端的Ai之路20 分钟前
LangChain Deep Agents 从入门到企业实战
开发语言·人工智能·python·langchain·deepagents
2601_9623815821 分钟前
Mac和Windows,哪种电脑适合新手学Python|数智码力分享
windows·python·mac·编程环境·学习入门
会飞的拖把24 分钟前
Python文件操作详解:从文件读写到os、shutil模块实战
开发语言·python
RS迷途小书童29 分钟前
Python 解析大疆无人机 SRT 字幕日志
开发语言·python·无人机
苏三说技术33 分钟前
再见了EasyExcel,我决定用Apache Fesod
后端