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 端口。

相关推荐
码事漫谈20 小时前
我花了一周时间,看AI公司怎么"管"AI,结果越看越后背发凉
后端
大可不必了1 天前
03 函数定义和调用
开发语言·python
承渊政道1 天前
【Python编程—从入门到实践】(记分与闯关:用Python+Pygame,打造越战越精彩的太空大战!)
开发语言·python·pycharm·游戏程序·pygame
爱学习的程序媛1 天前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
GISer_Jing1 天前
Agent核心内容
后端·ai·langchain
imgsq1 天前
GESP Python 一到四级:备考路线与真题特点
python·青少年编程
budingxiaomoli1 天前
Spring统一功能处理
java·后端·spring
eggwyw1 天前
Anaconda安装卸载的详细流程指南
开发语言·python
2601_967979121 天前
纯手写:Python安装pip完整教程,搞了几小时,终于成功
python·教程·pip·安装·包管理
某鹏1 天前
网关选型:Go、Java、Graal 谁都不能完胜
后端